text stringlengths 2 1.04M | meta dict |
|---|---|
add_import_path "vendor/foundation/scss"
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "css"
sass_dir = "scss"
images_dir = "img"
javascripts_dir = "js"
# You can select your preferred output style here (can be overridden via the command line):
output_style = :compressed
# To enable relative paths to assets via compass helper functions. Uncomment:
relative_assets = true
# To disable debugging comments that display the original location of your selectors. Uncomment:
line_comments = false
# disable asset cache buster
asset_cache_buster do |http_path, real_path|
nil
end
| {
"content_hash": "7aa4b24cbc5e1109a12664e99ab8d54a",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 96,
"avg_line_length": 27.954545454545453,
"alnum_prop": 0.7544715447154472,
"repo_name": "thiagosf/HTMLSimpleApp",
"id": "840c489a5c4ca22a551bfc83b98462117e3a3604",
"size": "662",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "57031"
},
{
"name": "HTML",
"bytes": "533"
},
{
"name": "JavaScript",
"bytes": "1787"
},
{
"name": "Nginx",
"bytes": "184"
},
{
"name": "Ruby",
"bytes": "662"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe User, models: true do
include Gitlab::CurrentSettings
describe 'modules' do
subject { described_class }
it { is_expected.to include_module(Gitlab::ConfigHelper) }
it { is_expected.to include_module(Gitlab::CurrentSettings) }
it { is_expected.to include_module(Referable) }
it { is_expected.to include_module(Sortable) }
it { is_expected.to include_module(TokenAuthenticatable) }
end
describe 'associations' do
it { is_expected.to have_one(:namespace) }
it { is_expected.to have_many(:snippets).class_name('Snippet').dependent(:destroy) }
it { is_expected.to have_many(:project_members).dependent(:destroy) }
it { is_expected.to have_many(:groups) }
it { is_expected.to have_many(:keys).dependent(:destroy) }
it { is_expected.to have_many(:events).class_name('Event').dependent(:destroy) }
it { is_expected.to have_many(:recent_events).class_name('Event') }
it { is_expected.to have_many(:issues).dependent(:destroy) }
it { is_expected.to have_many(:notes).dependent(:destroy) }
it { is_expected.to have_many(:assigned_issues).dependent(:destroy) }
it { is_expected.to have_many(:merge_requests).dependent(:destroy) }
it { is_expected.to have_many(:assigned_merge_requests).dependent(:destroy) }
it { is_expected.to have_many(:identities).dependent(:destroy) }
it { is_expected.to have_one(:abuse_report) }
it { is_expected.to have_many(:spam_logs).dependent(:destroy) }
it { is_expected.to have_many(:todos).dependent(:destroy) }
it { is_expected.to have_many(:award_emoji).dependent(:destroy) }
it { is_expected.to have_many(:builds).dependent(:nullify) }
it { is_expected.to have_many(:pipelines).dependent(:nullify) }
describe '#group_members' do
it 'does not include group memberships for which user is a requester' do
user = create(:user)
group = create(:group, :public)
group.request_access(user)
expect(user.group_members).to be_empty
end
end
describe '#project_members' do
it 'does not include project memberships for which user is a requester' do
user = create(:user)
project = create(:project, :public)
project.request_access(user)
expect(user.project_members).to be_empty
end
end
end
describe 'validations' do
describe 'username' do
it 'validates presence' do
expect(subject).to validate_presence_of(:username)
end
it 'rejects blacklisted names' do
user = build(:user, username: 'dashboard')
expect(user).not_to be_valid
expect(user.errors.values).to eq [['dashboard is a reserved name']]
end
it 'validates uniqueness' do
expect(subject).to validate_uniqueness_of(:username).case_insensitive
end
end
it { is_expected.to validate_presence_of(:projects_limit) }
it { is_expected.to validate_numericality_of(:projects_limit) }
it { is_expected.to allow_value(0).for(:projects_limit) }
it { is_expected.not_to allow_value(-1).for(:projects_limit) }
it { is_expected.to validate_length_of(:bio).is_within(0..255) }
it_behaves_like 'an object with email-formated attributes', :email do
subject { build(:user) }
end
it_behaves_like 'an object with email-formated attributes', :public_email, :notification_email do
subject { build(:user).tap { |user| user.emails << build(:email, email: email_value) } }
end
describe 'email' do
context 'when no signup domains whitelisted' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return([])
end
it 'accepts any email' do
user = build(:user, email: "info@example.com")
expect(user).to be_valid
end
end
context 'when a signup domain is whitelisted and subdomains are allowed' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com', '*.example.com'])
end
it 'accepts info@example.com' do
user = build(:user, email: "info@example.com")
expect(user).to be_valid
end
it 'accepts info@test.example.com' do
user = build(:user, email: "info@test.example.com")
expect(user).to be_valid
end
it 'rejects example@test.com' do
user = build(:user, email: "example@test.com")
expect(user).to be_invalid
end
end
context 'when a signup domain is whitelisted and subdomains are not allowed' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['example.com'])
end
it 'accepts info@example.com' do
user = build(:user, email: "info@example.com")
expect(user).to be_valid
end
it 'rejects info@test.example.com' do
user = build(:user, email: "info@test.example.com")
expect(user).to be_invalid
end
it 'rejects example@test.com' do
user = build(:user, email: "example@test.com")
expect(user).to be_invalid
end
end
context 'domain blacklist' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist_enabled?).and_return(true)
allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist).and_return(['example.com'])
end
context 'when a signup domain is blacklisted' do
it 'accepts info@test.com' do
user = build(:user, email: 'info@test.com')
expect(user).to be_valid
end
it 'rejects info@example.com' do
user = build(:user, email: 'info@example.com')
expect(user).not_to be_valid
end
end
context 'when a signup domain is blacklisted but a wildcard subdomain is allowed' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:domain_blacklist).and_return(['test.example.com'])
allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['*.example.com'])
end
it 'gives priority to whitelist and allow info@test.example.com' do
user = build(:user, email: 'info@test.example.com')
expect(user).to be_valid
end
end
context 'with both lists containing a domain' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:domain_whitelist).and_return(['test.com'])
end
it 'accepts info@test.com' do
user = build(:user, email: 'info@test.com')
expect(user).to be_valid
end
it 'rejects info@example.com' do
user = build(:user, email: 'info@example.com')
expect(user).not_to be_valid
end
end
end
context 'owns_notification_email' do
it 'accepts temp_oauth_email emails' do
user = build(:user, email: "temp-email-for-oauth@example.com")
expect(user).to be_valid
end
end
end
end
describe "scopes" do
describe ".with_two_factor" do
it "returns users with 2fa enabled via OTP" do
user_with_2fa = create(:user, :two_factor_via_otp)
user_without_2fa = create(:user)
users_with_two_factor = User.with_two_factor.pluck(:id)
expect(users_with_two_factor).to include(user_with_2fa.id)
expect(users_with_two_factor).not_to include(user_without_2fa.id)
end
it "returns users with 2fa enabled via U2F" do
user_with_2fa = create(:user, :two_factor_via_u2f)
user_without_2fa = create(:user)
users_with_two_factor = User.with_two_factor.pluck(:id)
expect(users_with_two_factor).to include(user_with_2fa.id)
expect(users_with_two_factor).not_to include(user_without_2fa.id)
end
it "returns users with 2fa enabled via OTP and U2F" do
user_with_2fa = create(:user, :two_factor_via_otp, :two_factor_via_u2f)
user_without_2fa = create(:user)
users_with_two_factor = User.with_two_factor.pluck(:id)
expect(users_with_two_factor).to eq([user_with_2fa.id])
expect(users_with_two_factor).not_to include(user_without_2fa.id)
end
end
describe ".without_two_factor" do
it "excludes users with 2fa enabled via OTP" do
user_with_2fa = create(:user, :two_factor_via_otp)
user_without_2fa = create(:user)
users_without_two_factor = User.without_two_factor.pluck(:id)
expect(users_without_two_factor).to include(user_without_2fa.id)
expect(users_without_two_factor).not_to include(user_with_2fa.id)
end
it "excludes users with 2fa enabled via U2F" do
user_with_2fa = create(:user, :two_factor_via_u2f)
user_without_2fa = create(:user)
users_without_two_factor = User.without_two_factor.pluck(:id)
expect(users_without_two_factor).to include(user_without_2fa.id)
expect(users_without_two_factor).not_to include(user_with_2fa.id)
end
it "excludes users with 2fa enabled via OTP and U2F" do
user_with_2fa = create(:user, :two_factor_via_otp, :two_factor_via_u2f)
user_without_2fa = create(:user)
users_without_two_factor = User.without_two_factor.pluck(:id)
expect(users_without_two_factor).to include(user_without_2fa.id)
expect(users_without_two_factor).not_to include(user_with_2fa.id)
end
end
end
describe "Respond to" do
it { is_expected.to respond_to(:is_admin?) }
it { is_expected.to respond_to(:name) }
it { is_expected.to respond_to(:private_token) }
it { is_expected.to respond_to(:external?) }
end
describe 'before save hook' do
context 'when saving an external user' do
let(:user) { create(:user) }
let(:external_user) { create(:user, external: true) }
it "sets other properties aswell" do
expect(external_user.can_create_team).to be_falsey
expect(external_user.can_create_group).to be_falsey
expect(external_user.projects_limit).to be 0
end
end
end
describe '#confirm' do
before do
allow_any_instance_of(ApplicationSetting).to receive(:send_user_confirmation_email).and_return(true)
end
let(:user) { create(:user, confirmed_at: nil, unconfirmed_email: 'test@gitlab.com') }
it 'returns unconfirmed' do
expect(user.confirmed?).to be_falsey
end
it 'confirms a user' do
user.confirm
expect(user.confirmed?).to be_truthy
end
end
describe '#to_reference' do
let(:user) { create(:user) }
it 'returns a String reference to the object' do
expect(user.to_reference).to eq "@#{user.username}"
end
end
describe '#generate_password' do
it "executes callback when force_random_password specified" do
user = build(:user, force_random_password: true)
expect(user).to receive(:generate_password)
user.save
end
it "does not generate password by default" do
user = create(:user, password: 'abcdefghe')
expect(user.password).to eq('abcdefghe')
end
it "generates password when forcing random password" do
allow(Devise).to receive(:friendly_token).and_return('123456789')
user = create(:user, password: 'abcdefg', force_random_password: true)
expect(user.password).to eq('12345678')
end
end
describe 'authentication token' do
it "has authentication token" do
user = create(:user)
expect(user.authentication_token).not_to be_blank
end
end
describe '#recently_sent_password_reset?' do
it 'is false when reset_password_sent_at is nil' do
user = build_stubbed(:user, reset_password_sent_at: nil)
expect(user.recently_sent_password_reset?).to eq false
end
it 'is false when sent more than one minute ago' do
user = build_stubbed(:user, reset_password_sent_at: 5.minutes.ago)
expect(user.recently_sent_password_reset?).to eq false
end
it 'is true when sent less than one minute ago' do
user = build_stubbed(:user, reset_password_sent_at: Time.now)
expect(user.recently_sent_password_reset?).to eq true
end
end
describe '#disable_two_factor!' do
it 'clears all 2FA-related fields' do
user = create(:user, :two_factor)
expect(user).to be_two_factor_enabled
expect(user.encrypted_otp_secret).not_to be_nil
expect(user.otp_backup_codes).not_to be_nil
expect(user.otp_grace_period_started_at).not_to be_nil
user.disable_two_factor!
expect(user).not_to be_two_factor_enabled
expect(user.encrypted_otp_secret).to be_nil
expect(user.encrypted_otp_secret_iv).to be_nil
expect(user.encrypted_otp_secret_salt).to be_nil
expect(user.otp_backup_codes).to be_nil
expect(user.otp_grace_period_started_at).to be_nil
end
end
describe 'projects' do
before do
@user = create :user
@project = create :project, namespace: @user.namespace
@project_2 = create :project, group: create(:group) # Grant MASTER access to the user
@project_3 = create :project, group: create(:group) # Grant DEVELOPER access to the user
@project_2.team << [@user, :master]
@project_3.team << [@user, :developer]
end
it { expect(@user.authorized_projects).to include(@project) }
it { expect(@user.authorized_projects).to include(@project_2) }
it { expect(@user.authorized_projects).to include(@project_3) }
it { expect(@user.owned_projects).to include(@project) }
it { expect(@user.owned_projects).not_to include(@project_2) }
it { expect(@user.owned_projects).not_to include(@project_3) }
it { expect(@user.personal_projects).to include(@project) }
it { expect(@user.personal_projects).not_to include(@project_2) }
it { expect(@user.personal_projects).not_to include(@project_3) }
end
describe 'groups' do
before do
@user = create :user
@group = create :group
@group.add_owner(@user)
end
it { expect(@user.several_namespaces?).to be_truthy }
it { expect(@user.authorized_groups).to eq([@group]) }
it { expect(@user.owned_groups).to eq([@group]) }
it { expect(@user.namespaces).to match_array([@user.namespace, @group]) }
end
describe 'group multiple owners' do
before do
@user = create :user
@user2 = create :user
@group = create :group
@group.add_owner(@user)
@group.add_user(@user2, GroupMember::OWNER)
end
it { expect(@user2.several_namespaces?).to be_truthy }
end
describe 'namespaced' do
before do
@user = create :user
@project = create :project, namespace: @user.namespace
end
it { expect(@user.several_namespaces?).to be_falsey }
it { expect(@user.namespaces).to eq([@user.namespace]) }
end
describe 'blocking user' do
let(:user) { create(:user, name: 'John Smith') }
it "blocks user" do
user.block
expect(user.blocked?).to be_truthy
end
end
describe '.filter' do
let(:user) { double }
it 'filters by active users by default' do
expect(User).to receive(:active).and_return([user])
expect(User.filter(nil)).to include user
end
it 'filters by admins' do
expect(User).to receive(:admins).and_return([user])
expect(User.filter('admins')).to include user
end
it 'filters by blocked' do
expect(User).to receive(:blocked).and_return([user])
expect(User.filter('blocked')).to include user
end
it 'filters by two_factor_disabled' do
expect(User).to receive(:without_two_factor).and_return([user])
expect(User.filter('two_factor_disabled')).to include user
end
it 'filters by two_factor_enabled' do
expect(User).to receive(:with_two_factor).and_return([user])
expect(User.filter('two_factor_enabled')).to include user
end
it 'filters by wop' do
expect(User).to receive(:without_projects).and_return([user])
expect(User.filter('wop')).to include user
end
end
describe '.not_in_project' do
before do
User.delete_all
@user = create :user
@project = create :project
end
it { expect(User.not_in_project(@project)).to include(@user, @project.owner) }
end
describe 'user creation' do
describe 'normal user' do
let(:user) { create(:user, name: 'John Smith') }
it { expect(user.is_admin?).to be_falsey }
it { expect(user.require_ssh_key?).to be_truthy }
it { expect(user.can_create_group?).to be_truthy }
it { expect(user.can_create_project?).to be_truthy }
it { expect(user.first_name).to eq('John') }
it { expect(user.external).to be_falsey }
end
describe 'with defaults' do
let(:user) { User.new }
it "applies defaults to user" do
expect(user.projects_limit).to eq(Gitlab.config.gitlab.default_projects_limit)
expect(user.can_create_group).to eq(Gitlab.config.gitlab.default_can_create_group)
expect(user.theme_id).to eq(Gitlab.config.gitlab.default_theme)
expect(user.external).to be_falsey
end
end
describe 'with default overrides' do
let(:user) { User.new(projects_limit: 123, can_create_group: false, can_create_team: true, theme_id: 1) }
it "applies defaults to user" do
expect(user.projects_limit).to eq(123)
expect(user.can_create_group).to be_falsey
expect(user.theme_id).to eq(1)
end
end
context 'when current_application_settings.user_default_external is true' do
before do
stub_application_setting(user_default_external: true)
end
it "creates external user by default" do
user = build(:user)
expect(user.external).to be_truthy
end
describe 'with default overrides' do
it "creates a non-external user" do
user = build(:user, external: false)
expect(user.external).to be_falsey
end
end
end
end
describe '.find_by_any_email' do
it 'finds by primary email' do
user = create(:user, email: 'foo@example.com')
expect(User.find_by_any_email(user.email)).to eq user
end
it 'finds by secondary email' do
email = create(:email, email: 'foo@example.com')
user = email.user
expect(User.find_by_any_email(email.email)).to eq user
end
it 'returns nil when nothing found' do
expect(User.find_by_any_email('')).to be_nil
end
end
describe '.search' do
let(:user) { create(:user) }
it 'returns users with a matching name' do
expect(described_class.search(user.name)).to eq([user])
end
it 'returns users with a partially matching name' do
expect(described_class.search(user.name[0..2])).to eq([user])
end
it 'returns users with a matching name regardless of the casing' do
expect(described_class.search(user.name.upcase)).to eq([user])
end
it 'returns users with a matching Email' do
expect(described_class.search(user.email)).to eq([user])
end
it 'returns users with a partially matching Email' do
expect(described_class.search(user.email[0..2])).to eq([user])
end
it 'returns users with a matching Email regardless of the casing' do
expect(described_class.search(user.email.upcase)).to eq([user])
end
it 'returns users with a matching username' do
expect(described_class.search(user.username)).to eq([user])
end
it 'returns users with a partially matching username' do
expect(described_class.search(user.username[0..2])).to eq([user])
end
it 'returns users with a matching username regardless of the casing' do
expect(described_class.search(user.username.upcase)).to eq([user])
end
end
describe 'by_username_or_id' do
let(:user1) { create(:user, username: 'foo') }
it "gets the correct user" do
expect(User.by_username_or_id(user1.id)).to eq(user1)
expect(User.by_username_or_id('foo')).to eq(user1)
expect(User.by_username_or_id(-1)).to be_nil
expect(User.by_username_or_id('bar')).to be_nil
end
end
describe '.find_by_ssh_key_id' do
context 'using an existing SSH key ID' do
let(:user) { create(:user) }
let(:key) { create(:key, user: user) }
it 'returns the corresponding User' do
expect(described_class.find_by_ssh_key_id(key.id)).to eq(user)
end
end
context 'using an invalid SSH key ID' do
it 'returns nil' do
expect(described_class.find_by_ssh_key_id(-1)).to be_nil
end
end
end
describe '.by_login' do
let(:username) { 'John' }
let!(:user) { create(:user, username: username) }
it 'gets the correct user' do
expect(User.by_login(user.email.upcase)).to eq user
expect(User.by_login(user.email)).to eq user
expect(User.by_login(username.downcase)).to eq user
expect(User.by_login(username)).to eq user
expect(User.by_login(nil)).to be_nil
expect(User.by_login('')).to be_nil
end
end
describe '.find_by_username!' do
it 'raises RecordNotFound' do
expect { described_class.find_by_username!('JohnDoe') }.
to raise_error(ActiveRecord::RecordNotFound)
end
it 'is case-insensitive' do
user = create(:user, username: 'JohnDoe')
expect(described_class.find_by_username!('JOHNDOE')).to eq user
end
end
describe 'all_ssh_keys' do
it { is_expected.to have_many(:keys).dependent(:destroy) }
it "has all ssh keys" do
user = create :user
key = create :key, key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD33bWLBxu48Sev9Fert1yzEO4WGcWglWF7K/AwblIUFselOt/QdOL9DSjpQGxLagO1s9wl53STIO8qGS4Ms0EJZyIXOEFMjFJ5xmjSy+S37By4sG7SsltQEHMxtbtFOaW5LV2wCrX+rUsRNqLMamZjgjcPO0/EgGCXIGMAYW4O7cwGZdXWYIhQ1Vwy+CsVMDdPkPgBXqK7nR/ey8KMs8ho5fMNgB5hBw/AL9fNGhRw3QTD6Q12Nkhl4VZES2EsZqlpNnJttnPdp847DUsT6yuLRlfiQfz5Cn9ysHFdXObMN5VYIiPFwHeYCZp1X2S4fDZooRE8uOLTfxWHPXwrhqSH", user_id: user.id
expect(user.all_ssh_keys).to include(a_string_starting_with(key.key))
end
end
describe '#avatar_type' do
let(:user) { create(:user) }
it "is true if avatar is image" do
user.update_attribute(:avatar, 'uploads/avatar.png')
expect(user.avatar_type).to be_truthy
end
it "is false if avatar is html page" do
user.update_attribute(:avatar, 'uploads/avatar.html')
expect(user.avatar_type).to eq(["only images allowed"])
end
end
describe '#requires_ldap_check?' do
let(:user) { User.new }
it 'is false when LDAP is disabled' do
# Create a condition which would otherwise cause 'true' to be returned
allow(user).to receive(:ldap_user?).and_return(true)
user.last_credential_check_at = nil
expect(user.requires_ldap_check?).to be_falsey
end
context 'when LDAP is enabled' do
before do
allow(Gitlab.config.ldap).to receive(:enabled).and_return(true)
end
it 'is false for non-LDAP users' do
allow(user).to receive(:ldap_user?).and_return(false)
expect(user.requires_ldap_check?).to be_falsey
end
context 'and when the user is an LDAP user' do
before do
allow(user).to receive(:ldap_user?).and_return(true)
end
it 'is true when the user has never had an LDAP check before' do
user.last_credential_check_at = nil
expect(user.requires_ldap_check?).to be_truthy
end
it 'is true when the last LDAP check happened over 1 hour ago' do
user.last_credential_check_at = 2.hours.ago
expect(user.requires_ldap_check?).to be_truthy
end
end
end
end
context 'ldap synchronized user' do
describe '#ldap_user?' do
it 'is true if provider name starts with ldap' do
user = create(:omniauth_user, provider: 'ldapmain')
expect(user.ldap_user?).to be_truthy
end
it 'is false for other providers' do
user = create(:omniauth_user, provider: 'other-provider')
expect(user.ldap_user?).to be_falsey
end
it 'is false if no extern_uid is provided' do
user = create(:omniauth_user, extern_uid: nil)
expect(user.ldap_user?).to be_falsey
end
end
describe '#ldap_identity' do
it 'returns ldap identity' do
user = create :omniauth_user
expect(user.ldap_identity.provider).not_to be_empty
end
end
describe '#ldap_block' do
let(:user) { create(:omniauth_user, provider: 'ldapmain', name: 'John Smith') }
it 'blocks user flaging the action caming from ldap' do
user.ldap_block
expect(user.blocked?).to be_truthy
expect(user.ldap_blocked?).to be_truthy
end
end
end
describe '#full_website_url' do
let(:user) { create(:user) }
it 'begins with http if website url omits it' do
user.website_url = 'test.com'
expect(user.full_website_url).to eq 'http://test.com'
end
it 'begins with http if website url begins with http' do
user.website_url = 'http://test.com'
expect(user.full_website_url).to eq 'http://test.com'
end
it 'begins with https if website url begins with https' do
user.website_url = 'https://test.com'
expect(user.full_website_url).to eq 'https://test.com'
end
end
describe '#short_website_url' do
let(:user) { create(:user) }
it 'does not begin with http if website url omits it' do
user.website_url = 'test.com'
expect(user.short_website_url).to eq 'test.com'
end
it 'does not begin with http if website url begins with http' do
user.website_url = 'http://test.com'
expect(user.short_website_url).to eq 'test.com'
end
it 'does not begin with https if website url begins with https' do
user.website_url = 'https://test.com'
expect(user.short_website_url).to eq 'test.com'
end
end
describe "#starred?" do
it "determines if user starred a project" do
user = create :user
project1 = create :project, :public
project2 = create :project, :public
expect(user.starred?(project1)).to be_falsey
expect(user.starred?(project2)).to be_falsey
star1 = UsersStarProject.create!(project: project1, user: user)
expect(user.starred?(project1)).to be_truthy
expect(user.starred?(project2)).to be_falsey
star2 = UsersStarProject.create!(project: project2, user: user)
expect(user.starred?(project1)).to be_truthy
expect(user.starred?(project2)).to be_truthy
star1.destroy
expect(user.starred?(project1)).to be_falsey
expect(user.starred?(project2)).to be_truthy
star2.destroy
expect(user.starred?(project1)).to be_falsey
expect(user.starred?(project2)).to be_falsey
end
end
describe "#toggle_star" do
it "toggles stars" do
user = create :user
project = create :project, :public
expect(user.starred?(project)).to be_falsey
user.toggle_star(project)
expect(user.starred?(project)).to be_truthy
user.toggle_star(project)
expect(user.starred?(project)).to be_falsey
end
end
describe "#sort" do
before do
User.delete_all
@user = create :user, created_at: Date.today, last_sign_in_at: Date.today, name: 'Alpha'
@user1 = create :user, created_at: Date.today - 1, last_sign_in_at: Date.today - 1, name: 'Omega'
end
it "sorts users by the recent sign-in time" do
expect(User.sort('recent_sign_in').first).to eq(@user)
end
it "sorts users by the oldest sign-in time" do
expect(User.sort('oldest_sign_in').first).to eq(@user1)
end
it "sorts users in descending order by their creation time" do
expect(User.sort('created_desc').first).to eq(@user)
end
it "sorts users in ascending order by their creation time" do
expect(User.sort('created_asc').first).to eq(@user1)
end
it "sorts users by id in descending order when nil is passed" do
expect(User.sort(nil).first).to eq(@user1)
end
end
describe "#contributed_projects" do
subject { create(:user) }
let!(:project1) { create(:project) }
let!(:project2) { create(:project, forked_from_project: project3) }
let!(:project3) { create(:project) }
let!(:merge_request) { create(:merge_request, source_project: project2, target_project: project3, author: subject) }
let!(:push_event) { create(:event, action: Event::PUSHED, project: project1, target: project1, author: subject) }
let!(:merge_event) { create(:event, action: Event::CREATED, project: project3, target: merge_request, author: subject) }
before do
project1.team << [subject, :master]
project2.team << [subject, :master]
end
it "includes IDs for projects the user has pushed to" do
expect(subject.contributed_projects).to include(project1)
end
it "includes IDs for projects the user has had merge requests merged into" do
expect(subject.contributed_projects).to include(project3)
end
it "doesn't include IDs for unrelated projects" do
expect(subject.contributed_projects).not_to include(project2)
end
end
describe '#can_be_removed?' do
subject { create(:user) }
context 'no owned groups' do
it { expect(subject.can_be_removed?).to be_truthy }
end
context 'has owned groups' do
before do
group = create(:group)
group.add_owner(subject)
end
it { expect(subject.can_be_removed?).to be_falsey }
end
end
describe "#recent_push" do
subject { create(:user) }
let!(:project1) { create(:project) }
let!(:project2) { create(:project, forked_from_project: project1) }
let!(:push_data) do
Gitlab::DataBuilder::Push.build_sample(project2, subject)
end
let!(:push_event) { create(:event, action: Event::PUSHED, project: project2, target: project1, author: subject, data: push_data) }
before do
project1.team << [subject, :master]
project2.team << [subject, :master]
end
it "includes push event" do
expect(subject.recent_push).to eq(push_event)
end
it "excludes push event if branch has been deleted" do
allow_any_instance_of(Repository).to receive(:branch_names).and_return(['foo'])
expect(subject.recent_push).to eq(nil)
end
it "excludes push event if MR is opened for it" do
create(:merge_request, source_project: project2, target_project: project1, source_branch: project2.default_branch, target_branch: 'fix', author: subject)
expect(subject.recent_push).to eq(nil)
end
it "includes push events on any of the provided projects" do
expect(subject.recent_push(project1)).to eq(nil)
expect(subject.recent_push(project2)).to eq(push_event)
push_data1 = Gitlab::DataBuilder::Push.build_sample(project1, subject)
push_event1 = create(:event, action: Event::PUSHED, project: project1, target: project1, author: subject, data: push_data1)
expect(subject.recent_push([project1, project2])).to eq(push_event1) # Newest
end
end
describe '#authorized_groups' do
let!(:user) { create(:user) }
let!(:private_group) { create(:group) }
before do
private_group.add_user(user, Gitlab::Access::MASTER)
end
subject { user.authorized_groups }
it { is_expected.to eq([private_group]) }
end
describe '#authorized_projects' do
context 'with a minimum access level' do
it 'includes projects for which the user is an owner' do
user = create(:user)
project = create(:empty_project, :private, namespace: user.namespace)
expect(user.authorized_projects(Gitlab::Access::REPORTER))
.to contain_exactly(project)
end
it 'includes projects for which the user is a master' do
user = create(:user)
project = create(:empty_project, :private)
project.team << [user, Gitlab::Access::MASTER]
expect(user.authorized_projects(Gitlab::Access::REPORTER))
.to contain_exactly(project)
end
end
end
describe '#projects_where_can_admin_issues' do
let(:user) { create(:user) }
it 'includes projects for which the user access level is above or equal to reporter' do
create(:project)
reporter_project = create(:project)
developer_project = create(:project)
master_project = create(:project)
reporter_project.team << [user, :reporter]
developer_project.team << [user, :developer]
master_project.team << [user, :master]
expect(user.projects_where_can_admin_issues.to_a).to eq([master_project, developer_project, reporter_project])
expect(user.can?(:admin_issue, master_project)).to eq(true)
expect(user.can?(:admin_issue, developer_project)).to eq(true)
expect(user.can?(:admin_issue, reporter_project)).to eq(true)
end
it 'does not include for which the user access level is below reporter' do
project = create(:project)
guest_project = create(:project)
guest_project.team << [user, :guest]
expect(user.projects_where_can_admin_issues.to_a).to be_empty
expect(user.can?(:admin_issue, guest_project)).to eq(false)
expect(user.can?(:admin_issue, project)).to eq(false)
end
it 'does not include archived projects' do
project = create(:project)
project.update_attributes(archived: true)
expect(user.projects_where_can_admin_issues.to_a).to be_empty
expect(user.can?(:admin_issue, project)).to eq(false)
end
it 'does not include projects for which issues are disabled' do
project = create(:project, issues_access_level: ProjectFeature::DISABLED)
expect(user.projects_where_can_admin_issues.to_a).to be_empty
expect(user.can?(:admin_issue, project)).to eq(false)
end
end
describe '#ci_authorized_runners' do
let(:user) { create(:user) }
let(:runner) { create(:ci_runner) }
before do
project.runners << runner
end
context 'without any projects' do
let(:project) { create(:project) }
it 'does not load' do
expect(user.ci_authorized_runners).to be_empty
end
end
context 'with personal projects runners' do
let(:namespace) { create(:namespace, owner: user) }
let(:project) { create(:project, namespace: namespace) }
it 'loads' do
expect(user.ci_authorized_runners).to contain_exactly(runner)
end
end
shared_examples :member do
context 'when the user is a master' do
before do
add_user(Gitlab::Access::MASTER)
end
it 'loads' do
expect(user.ci_authorized_runners).to contain_exactly(runner)
end
end
context 'when the user is a developer' do
before do
add_user(Gitlab::Access::DEVELOPER)
end
it 'does not load' do
expect(user.ci_authorized_runners).to be_empty
end
end
end
context 'with groups projects runners' do
let(:group) { create(:group) }
let(:project) { create(:project, group: group) }
def add_user(access)
group.add_user(user, access)
end
it_behaves_like :member
end
context 'with other projects runners' do
let(:project) { create(:project) }
def add_user(access)
project.team << [user, access]
end
it_behaves_like :member
end
end
describe '#viewable_starred_projects' do
let(:user) { create(:user) }
let(:public_project) { create(:empty_project, :public) }
let(:private_project) { create(:empty_project, :private) }
let(:private_viewable_project) { create(:empty_project, :private) }
before do
private_viewable_project.team << [user, Gitlab::Access::MASTER]
[public_project, private_project, private_viewable_project].each do |project|
user.toggle_star(project)
end
end
it 'returns only starred projects the user can view' do
expect(user.viewable_starred_projects).not_to include(private_project)
end
end
end
| {
"content_hash": "7f9d492ccd9f4a76a560f13a420dfe90",
"timestamp": "",
"source": "github",
"line_count": 1120,
"max_line_length": 430,
"avg_line_length": 32.50982142857143,
"alnum_prop": 0.6463980665183598,
"repo_name": "shinexiao/gitlabhq",
"id": "65b2896930a45eb0ce5e4a1ec94f319fa6ff6e89",
"size": "36411",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spec/models/user_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "371037"
},
{
"name": "Cucumber",
"bytes": "163570"
},
{
"name": "HTML",
"bytes": "810995"
},
{
"name": "JavaScript",
"bytes": "656802"
},
{
"name": "Ruby",
"bytes": "6465444"
},
{
"name": "Shell",
"bytes": "21648"
}
],
"symlink_target": ""
} |
# -*- encoding: utf-8 -*-
require 'yaml'
require 'pathname'
require 'rubygems'
require 'i18n'
require 'mustache'
require 'memorack/tilt-mustache'
require 'memorack/mdmenu'
require 'memorack/locals'
require 'memorack/locals/base'
module MemoRack
class Core
attr_reader :themes, :options_chain, :suffix, :root
DEFAULT_APP_OPTIONS = {
root: 'content/',
themes_folder: 'themes/',
tmpdir: 'tmp/',
theme: 'oreilly',
markdown: 'redcarpet',
formats: ['markdown'],
css: nil,
suffix: '',
public: [],
site: {},
requires: [],
directory_watcher: false
}
# テンプレートエンジンのオプション
DEFAULT_TEMPLATE_OPTIONS = {
tables: true
}
# テンプレートで使用するローカル変数の初期値
DEFAULT_LOCALS = {
title: 'memo'
}
DEFAULT_OPTIONS = DEFAULT_APP_OPTIONS.merge(DEFAULT_TEMPLATE_OPTIONS).merge(DEFAULT_LOCALS)
def self.app
@@app
end
def initialize(options={})
@@app = self
options = DEFAULT_OPTIONS.merge(to_sym_keys(options))
@themes_folders = [options[:themes_folder], folder(:themes, :user), folder(:themes)]
@themes_folders.delete nil
@themes_folders.reject! { |folder| ! File.directory?(folder) }
read_config(options[:theme], options)
read_config(DEFAULT_APP_OPTIONS[:theme], options) if @themes.empty?
@options = options
# DEFAULT_APP_OPTIONS に含まれるキーをすべてインスタンス変数に登録する
DEFAULT_APP_OPTIONS.each { |key, item|
instance_variable_set("@#{key}".to_sym, options[key])
# @options からテンプレートで使わないものを削除
@options.delete(key)
}
# プラグインの読込み
load_plugins
# ロケールの読込み
I18n.load_path = @locale_paths
I18n.backend.load_translations
I18n.enforce_available_locales = false
@requires.each { |lib| require lib }
@locals = default_locals(@options)
use_engine(@markdown)
end
# フォルダ(ディレクトリ)を取得する
def folder(name, domain = :app)
@folders ||= {}
@folders[domain] ||= {}
unless @folders[domain][name]
case domain
when :user
dir = File.join(ENV['HOME'], '.etc/memorack')
when :app
dir = File.dirname(__FILE__)
else
return nil
end
end
@folders[domain][name] ||= File.expand_path(name.to_s, dir)
end
# テーマのパスを取得する
def theme_path(theme)
return nil unless theme
@themes_folders.each { |folder|
path = theme && File.join(folder, theme)
return path if File.exists?(path) && File.directory?(path)
}
nil
end
# デフォルトの locals を生成する
def default_locals(locals = {})
locals = BaseLocals.new(self, locals)
locals[:site] ||= @site
locals
end
# json/yaml のデータを読込む
def read_data(name, exts = ['json', 'yml', 'yaml'])
begin
exts.each { |ext|
path = [name, ext].join('.')
if File.readable?(path)
data = File.read(path)
case ext
when 'json'
hash = JSON.parse(data)
when 'yml', 'yaml'
hash = YAML.load(data)
end
data = to_sym_keys(hash) if hash
return data
end
}
rescue
end
nil
end
# 設定ファイルを読込む
def read_config(theme, options = {})
@themes ||= []
@options_chain = []
@locale_paths = []
@macro_chain = []
@macro = {}
@plugins = Set.new
begin
require 'json'
while theme
dir = theme_path(theme)
break unless dir
break if @themes.member?(dir)
# 設定ファイルのデータをチェインに追加
theme = add_config_chain(dir, theme)
end
rescue
end
# デフォルトの設定をチェインに追加
add_config_chain(File.expand_path('../config', __FILE__))
# マクロをマージ
@macro_chain.reverse.each { |macro| @macro.merge!(macro) }
# オプションをマージ
@options_chain.reverse.each { |opts| options.merge!(opts) }
options
end
# 設定ファイルのデータをチェインに追加
def add_config_chain(dir, theme = nil)
# テーマ・チェインに追加
@themes << File.join(dir, '') if theme
# config の読込み
config = read_data(File.join(dir, 'config'))
if config
@options_chain << config
theme = config[:theme]
end
# macro の読込み
macro = read_data(File.join(dir, 'macro'))
@macro_chain << macro if macro && macro.kind_of?(Hash)
# locale の読込み
@locale_paths += Dir[File.expand_path('locales/*.yml', dir)]
theme
end
# locale を env情報で更新する
def update_locale(env = ENV)
locale ||= env['HTTP_ACCEPT_LANGUAGE']
locale ||= env['LANG'] if env['LANG']
locale = locale[0, 2].to_sym if locale
I18n.locale = locale if I18n.available_locales.include?(locale)
end
# プラグイン・フォルダを取得する
def plugins_folders
unless @plugins_folders
@plugins_folders = ['plugins/', folder(:plugins, :user), folder(:plugins)]
@plugins_folders.delete nil
@plugins_folders.reject! { |folder| ! File.directory?(folder) }
@themes.each { |theme|
path = File.join(theme, 'plugins/')
@plugins_folders.unshift path if File.directory?(path)
}
end
@plugins_folders
end
# プラグインを読込む
def load_plugins
plugins_folders.reverse.each { |folder|
Dir.glob(File.join(folder, '*')) { |path|
name = path.gsub(%r[^#{folder}/], '')
load_plugin(name, path)
}
}
end
# プラグインファイルを読込む
def load_plugin(name, path)
loaded = false
if File.directory?(path)
path = File.join(path, File.basename(path) + '.rb')
if File.exists?(path)
require_relative(path)
loaded = true
end
elsif path =~ /\.rb$/
require_relative(File.expand_path(path))
loaded = true
end
if loaded
@plugins << name
end
end
# プラグインを読込む(読込み済みのものは読込まない)
def require_plugin(plugin)
return if @plugins.include?(plugin)
plugins_folders.reverse.each { |folder|
path = File.join(folder, plugin)
load_plugin(folder, path) if File.exist?(path)
load_plugin(folder, path + '.rb') if File.exist?(path + '.rb')
}
end
# テンプレートエンジンを使用できるようにする
def use_engine(engine)
require engine if engine
# Tilt で Redcarpet 2.x を使うためのおまじない
Object.send(:remove_const, :RedcarpetCompat) if defined?(RedcarpetCompat) == 'constant'
end
# css の拡張子リストを作成する
def css_exts
@css_exts ||= Set.new ['css', *@css]
end
# テーマから固定ページのファイルを収集する
def pages
unless @pages
@pages = {}
@themes.each { |theme|
folder = File.join(theme, 'pages/')
if Dir.exists?(folder)
Dir.chdir(folder) { |dir|
Dir.glob(File.join('**/*')) { |path|
path_info, ext = split_extname(path)
path_info = File.join('', path_info)
@pages[path_info] ||= File.expand_path(path)
}
}
end
}
end
@pages
end
# ファイルを探す
def file_search(template, options = {}, exts = enable_exts)
options = {views: @root}.merge(options)
if options[:views].kind_of?(Array)
err = nil
options[:views].each { |views|
options[:views] = views
begin
path = file_search(template, options, exts)
return path if path
rescue Errno::ENOENT => e
err = e
end
}
raise err if err
return nil
end
dir = options[:views]
dir = File.join(dir, options[:folder]) if options[:folder]
if exts
exts.each { |ext|
path = File.join(dir, "#{template}.#{ext}")
return path if File.exists?(path)
}
else
path = File.join(dir, template)
return path if File.exists?(path)
end
return nil
end
# テンプレートエンジンで render する
def render(engine, template, options = {}, locals = {})
options = {views: @root}.merge(options)
if template.kind_of?(Pathname)
path = template
elsif options[:views].kind_of?(Array)
err = nil
options[:views].each { |views|
options[:views] = views
begin
return render(engine, template, options, locals)
rescue Errno::ENOENT => e
err = e
end
}
raise err
else
fname = template.kind_of?(String) ? template : "#{template}.#{engine}"
path = File.join(options[:views], fname)
end
engine = Tilt.new(File.join(File.dirname(path), ".#{engine}"), options) {
method = MemoApp.template_method(template)
if method && respond_to?(method)
data = send(method)
else
data = File.binread(path)
data.force_encoding('UTF-8')
end
data
}
engine.render(options, locals).force_encoding('UTF-8')
end
# レイアウトに mustache を適用してテンプレートエンジンでレンダリングする
def render_with_mustache(template, engine = :markdown, options = {}, locals = {})
begin
mustache_templ = []
mustache_templ << options[:mustache] if options[:mustache]
options = @options.merge(options)
locals = @locals.merge(locals)
locals.define_key(:__content__) { |hash, key|
if engine
render engine, template, options
elsif locals[:directory?]
# ディレクトリ
nil
else
template
end
}
locals[:directory?] = true if template.kind_of?(Pathname) && template.directory?
locals[:content?] = true unless template == :index || locals[:directory?]
locals[:page] = page = Locals[locals[:page] || {}]
if template.kind_of?(Pathname)
path = template.to_s
plugin = PageInfo[path]
locals[:page] = page = plugin.new(path, page, locals) if plugin
end
page.define_key(:name) { |hash, key|
if hash.kind_of?(PageInfo)
hash.value(:title)
elsif template != :index
fname = locals[:path_info]
fname ||= template.to_s.force_encoding('UTF-8')
File.basename(fname)
end
}
# マクロを組込む
embed_macro(locals, @macro)
# HTMLページをレンダリングする
if engine && engine.to_sym == :html
unless template.kind_of?(Pathname)
path = file_search(template, @options, [engine])
return nil unless path
template = Pathname.new(path)
end
locals.define_key(:__content__) { |hash, key| }
return render :mustache, template, {views: @themes}, locals
end
mustache_templ << 'page.html' if locals[:content?]
mustache_templ << 'index.html'
mustache_templ.each { |templ|
path = file_search(templ, {views: @themes}, nil)
next unless path
path = Pathname.new(path)
return render :mustache, path, {views: @themes}, locals
}
raise "Not found template #{mustache_templ}"
rescue => e
e.to_s
end
end
# Localsクラス 変換する
def value_to_locals(value)
case value
when Locals
when Hash
value = Locals[value]
else
value = Locals[]
end
value
end
# マクロを組込む
def embed_macro(hash, macro, options = {}, locals = hash)
macro.each { |key, value|
case value
when Hash
if hash[key].kind_of?(Array)
embed_macro_for_array(hash[key], value, options, locals)
else
hash[key] = value_to_locals(hash[key])
embed_macro(hash[key], value, options, locals)
end
when Array
hash[key] = [] unless hash[key]
a = hash[key]
if a.kind_of?(Array)
value.each_with_index { |item, index|
if item.kind_of?(Hash)
a[index] = value_to_locals(a[index])
embed_macro(a[index], item, options, locals)
else
a[index] = item
end
}
end
else
hash.define_key(key) { |hash, key|
if value
#render :mustache, value, {}, locals
engine = Tilt.new('.mustache', {}) { value }
engine.render({}, locals).force_encoding('UTF-8')
end
}
end
}
end
# マクロを配列に組込む
def embed_macro_for_array(array, macro, options = {}, locals)
array.each_with_index { |item, index|
if item.kind_of?(Array)
embed_macro_for_array(item, macro, options, locals)
else
array[index] = value_to_locals(item)
embed_macro(array[index], macro, options)
end
}
end
# メニューをレンダリングする
def render_menu
@menu = nil unless @directory_watcher # ファイル監視していない場合はメニューを初期化
@menu ||= render :markdown, :menu, @options
end
# 固定ページをレンダリングする
def render_page(path_info, locals = {})
path_info = path_info.gsub(%r[(/|.html)$], '')
path = pages[path_info]
return nil unless path
ext = split_extname(path)[1]
content = render_with_mustache Pathname.new(path), ext, {}, locals
end
# コンテンツをレンダリングする
def render_content(path_info, locals = {}, exts = enable_exts)
path = File.join(@root, path_info)
if File.directory?(path)
return render_with_mustache Pathname.new(path), nil, {}, locals
end
path, ext = split_extname(path_info)
fullpath = file_search(path_info, @options, exts)
if fullpath
path = path_info
ext = split_extname(fullpath)[1]
end
return nil unless ext && Tilt.registered?(ext)
template = fullpath ? Pathname.new(fullpath) : path.to_sym
content = render_with_mustache template, ext, {}, locals
end
# CSSをレンダリングする
def render_css(path_info, locals = {})
return unless @css
path, = split_extname(path_info)
options = {views: @themes}
fullpath = file_search(path, options, css_exts)
return nil unless fullpath
ext = split_extname(fullpath)[1]
case ext
when 'css'
return File.binread(fullpath)
when 'scss', 'sass'
options[:cache_location] = File.expand_path('sass-cache', @tmpdir)
end
render ext, Pathname.new(fullpath), options, locals
end
# 拡張子を取出す
def split_extname(path)
return [$1, $2] if /^(.+)\.([^.]+)/ =~ path
[path]
end
# キーをシンボルに変換する
def to_sym_keys(hash)
hash.inject({}) { |memo, entry|
key, value = entry
value = to_sym_keys(value) if value.kind_of?(Hash)
memo[key.to_sym] = value
memo
}
end
# Tilt に登録されている拡張子を集める
def extnames(extname)
klass = Tilt[extname]
r = []
if Tilt.respond_to?(:mappings)
r |= Tilt.mappings.select { |key, value| value.member?(klass) }.collect { |key, value| key }
end
if Tilt.respond_to?(:default_mapping)
r |= Tilt.default_mapping.template_map.select { |key, value| value == klass }.collect { |key, value| key }
r |= Tilt.default_mapping.lazy_map.select { |key, value| value.assoc(klass.to_s) }.collect { |key, value| key }
end
r
end
# 対応フォーマットを取得する
def collect_formats
unless @collect_formats
@collect_formats = {}
@formats.each { |item|
if item.kind_of?(Array)
@collect_formats[item.first] = item
elsif item.kind_of?(Hash)
@collect_formats.merge!(item)
else
@collect_formats[item] = extnames(item)
end
}
end
@collect_formats
end
# 対応している拡張子
def enable_exts
@enable_exts ||= collect_formats.values.flatten
end
# コンテンツファイルの収集する
def contents(options = {})
default_options = {prefix: '/', suffix: @suffix, uri_escape: true, formats: collect_formats}
options = default_options.merge(options)
mdmenu = MdMenu.new(options)
Dir.chdir(@root) { |path| mdmenu.collection('.') }
mdmenu
end
# パスからコンテント名を取得する
def content_name(path)
plugin = PageInfo[path]
if plugin
plugin.new(File.expand_path(path, @root))[:title]
else
File.basename(path, '.*')
end
end
# テンプレート名
def self.template_method(name)
name.kind_of?(Symbol) && "template_#{name}".to_sym
end
# テンプレートを作成する
def self.template(name, &block)
define_method(self.template_method(name), &block)
end
end
end
| {
"content_hash": "6580f580af1c9b0773d6f715e76a2204",
"timestamp": "",
"source": "github",
"line_count": 674,
"max_line_length": 115,
"avg_line_length": 22.23145400593472,
"alnum_prop": 0.6177923117992525,
"repo_name": "gnue/memorack",
"id": "a72e5e91b4d2204fd5d1d25d8f157ecda94ca9f0",
"size": "16290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/memorack/core.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4665"
},
{
"name": "Ruby",
"bytes": "62982"
}
],
"symlink_target": ""
} |
from domain.container import apply_to_container
| {
"content_hash": "2ee8366dc0acc93ee8815aa8aacb6458",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 47,
"avg_line_length": 48,
"alnum_prop": 0.8541666666666666,
"repo_name": "mcuadros/python-solid-example",
"id": "b43500b277593d1394278c9ebd1345f8822ced28",
"size": "48",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "domain/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8928"
}
],
"symlink_target": ""
} |
<?php defined('SYSPATH') or die('No direct script access.');
class Formo extends Fusion_Formo
{
} | {
"content_hash": "1dc0f2467b2844b4488759f376900d7b",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 60,
"avg_line_length": 16.5,
"alnum_prop": 0.7070707070707071,
"repo_name": "fusionFramework/core",
"id": "a9d9fac07612c73145c67a4ca95d9c6b7833ca62",
"size": "99",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/Formo.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "89079"
}
],
"symlink_target": ""
} |
h4, h5, h6,
h1, h2, h3 {margin-top: 0;}
ul, ol {margin: 0;}
p {margin: 0;}
.main-container label {font-weight: normal;}
.page .label {
color: inherit;
font-size: 100%;
border-radius: 0;
display: inline-block;
text-align: left;
white-space:normal;
line-height: normal;
}
.main-container .data-table .label {display: table-cell;}
.main-container .radio, .main-container .checkbox {display: inline-block; margin-top: 0;}
@media (min-width: 1200px) {
.container {
max-width: 1200px;
width: 1200px;
}
}
@media only screen and (min-width: 768px) {
span.toggle {display: none;}
.footer-col-content,
.block .block-content,
.box-collateral-content {
height: 100% !important;
display: block !important;
opacity: 1!important;
}
}
| {
"content_hash": "309a1585645c5dcab3aaa7b0bef1d417",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 89,
"avg_line_length": 22.941176470588236,
"alnum_prop": 0.65,
"repo_name": "diegomrod95/Impacto",
"id": "3edc50eb0ab6e4daca0bbc9f577f8355b97c6a13",
"size": "780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/css/extra_style.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "229200"
},
{
"name": "JavaScript",
"bytes": "392181"
},
{
"name": "PHP",
"bytes": "32741"
}
],
"symlink_target": ""
} |
import { Vector3 } from '../../../../build/three.module.js';
import { InputNode } from '../core/InputNode.js';
import { NodeUtils } from '../core/NodeUtils.js';
function Vector3Node( x, y, z ) {
InputNode.call( this, 'v3' );
this.value = x instanceof Vector3 ? x : new Vector3( x, y, z );
}
Vector3Node.prototype = Object.create( InputNode.prototype );
Vector3Node.prototype.constructor = Vector3Node;
Vector3Node.prototype.nodeType = "Vector3";
NodeUtils.addShortcuts( Vector3Node.prototype, 'value', [ 'x', 'y', 'z' ] );
Vector3Node.prototype.generateReadonly = function ( builder, output, uuid, type/*, ns, needsUpdate*/ ) {
return builder.format( "vec3( " + this.x + ", " + this.y + ", " + this.z + " )", type, output );
};
Vector3Node.prototype.copy = function ( source ) {
InputNode.prototype.copy.call( this, source );
this.value.copy( source );
return this;
};
Vector3Node.prototype.toJSON = function ( meta ) {
var data = this.getJSONNode( meta );
if ( ! data ) {
data = this.createJSONNode( meta );
data.x = this.x;
data.y = this.y;
data.z = this.z;
if ( this.readonly === true ) data.readonly = true;
}
return data;
};
export { Vector3Node };
| {
"content_hash": "5ee0b0270e3239514a91afed3a1cdaf1",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 104,
"avg_line_length": 21.410714285714285,
"alnum_prop": 0.6480400333611342,
"repo_name": "sinorise/sinorise.github.io",
"id": "4aabf9999bf2fa2da4daa6e012259f630a1c10fc",
"size": "1199",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "three/jsm/nodes/inputs/Vector3Node.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "145625"
},
{
"name": "HTML",
"bytes": "22857"
},
{
"name": "JavaScript",
"bytes": "83157"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Threading;
using NUnit.Framework;
using Shouldly;
namespace Esp.Net.Dispatchers
{
[TestFixture]
public class NewThreadRouterDispatcherTests
{
private NewThreadRouterDispatcher _dispatcher;
[SetUp]
public void SetUp()
{
_dispatcher = new NewThreadRouterDispatcher(ts => new Thread(ts));
}
[Test]
public void CheckAccessReturnsFalseOnOtherThread()
{
_dispatcher.CheckAccess().ShouldBe(false);
}
[Test]
public void CheckAccessReturnsTrueOnDispatcherThread()
{
ManualResetEvent gate = new ManualResetEvent(false);
bool? checkAccess = null;
_dispatcher.Dispatch(() =>
{
checkAccess = _dispatcher.CheckAccess();
gate.Set();
});
gate.WaitOne(100);
checkAccess.ShouldNotBe(null);
checkAccess.Value.ShouldBe(true);
}
[Test]
public void EnsureAccessThrowsOnOtherThread()
{
var exception = Assert.Throws<InvalidOperationException>(() => _dispatcher.EnsureAccess());
exception.Message.ShouldBe("Router accessed on invalid thread");
}
[Test]
public void DispatchThrowsIfActionNull()
{
Assert.Throws<ArgumentNullException>(() => _dispatcher.Dispatch(null));
}
[Test]
public void DispatchThrowsIfDisposed()
{
_dispatcher.Dispose();
Assert.Throws<ObjectDisposedException>(() => _dispatcher.Dispatch(() => { }));
}
[Test]
public void DispatchRunsAction()
{
ManualResetEvent gate = new ManualResetEvent(false);
bool? wasRun = null;
_dispatcher.Dispatch(() =>
{
wasRun = true;
gate.Set();
});
gate.WaitOne(100);
wasRun.ShouldNotBe(null);
wasRun.Value.ShouldBe(true);
}
[Test]
public void DispatchQueuesSubsequentActionPostedOnDispatcherThread()
{
AutoResetEvent gate = new AutoResetEvent(false);
bool? pass = null;
bool? wasRun = null;
_dispatcher.Dispatch(() =>
{
_dispatcher.Dispatch(() =>
{
// we can rely on this thread being the same as the outer
// dispatcher call so we can make assumptions about it being
// the only thread that can set wasRun.
pass = wasRun == true;
gate.Set();
});
wasRun = true;
});
gate.WaitOne();
wasRun.Value.ShouldBe(true);
pass.Value.ShouldBe(true);
}
[Test]
public void DisposingFromDispatcherThreadStopFurtherProcessing()
{
AutoResetEvent gate = new AutoResetEvent(false);
List<int> processed = new List<int>();
_dispatcher.Dispatch(() =>
{
processed.Add(1);
_dispatcher.Dispatch(() =>
{
processed.Add(2);
gate.Set();
});
_dispatcher.Dispose();
});
gate.WaitOne(500).ShouldBe(false);
processed.ShouldBe(new int[] { 1 });
Assert.Throws<ObjectDisposedException>(() => _dispatcher.Dispatch(() => processed.Add(3)));
}
}
} | {
"content_hash": "1b464afd058c999b664cf0e7371f8854",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 103,
"avg_line_length": 30.65546218487395,
"alnum_prop": 0.5134320175438597,
"repo_name": "esp/esp-net",
"id": "4273267cf67451e4514b056f650fb5de4643362c",
"size": "3650",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Esp.Net.Tests/Dispatchers/NewThreadRouterDispatcherTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "266654"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>krb5_c_enctype_compare - Compare two encryption types. — MIT Kerberos Documentation</title>
<link rel="stylesheet" href="../../../_static/agogo.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/kerb.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../../',
VERSION: '1.16',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../../_static/jquery.js"></script>
<script type="text/javascript" src="../../../_static/underscore.js"></script>
<script type="text/javascript" src="../../../_static/doctools.js"></script>
<link rel="author" title="About these documents" href="../../../about.html" />
<link rel="copyright" title="Copyright" href="../../../copyright.html" />
<link rel="top" title="MIT Kerberos Documentation" href="../../../index.html" />
<link rel="up" title="krb5 API" href="index.html" />
<link rel="next" title="krb5_c_free_state - Free a cipher state previously allocated by krb5_c_init_state() ." href="krb5_c_free_state.html" />
<link rel="prev" title="krb5_c_encrypt_length - Compute encrypted data length." href="krb5_c_encrypt_length.html" />
</head>
<body>
<div class="header-wrapper">
<div class="header">
<h1><a href="../../../index.html">MIT Kerberos Documentation</a></h1>
<div class="rel">
<a href="../../../index.html" title="Full Table of Contents"
accesskey="C">Contents</a> |
<a href="krb5_c_encrypt_length.html" title="krb5_c_encrypt_length - Compute encrypted data length."
accesskey="P">previous</a> |
<a href="krb5_c_free_state.html" title="krb5_c_free_state - Free a cipher state previously allocated by krb5_c_init_state() ."
accesskey="N">next</a> |
<a href="../../../genindex.html" title="General Index"
accesskey="I">index</a> |
<a href="../../../search.html" title="Enter search criteria"
accesskey="S">Search</a> |
<a href="mailto:krb5-bugs@mit.edu?subject=Documentation__krb5_c_enctype_compare - Compare two encryption types.">feedback</a>
</div>
</div>
</div>
<div class="content-wrapper">
<div class="content">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="krb5-c-enctype-compare-compare-two-encryption-types">
<h1>krb5_c_enctype_compare - Compare two encryption types.<a class="headerlink" href="#krb5-c-enctype-compare-compare-two-encryption-types" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.krb5_c_enctype_compare">
<a class="reference internal" href="../types/krb5_error_code.html#c.krb5_error_code" title="krb5_error_code">krb5_error_code</a> <tt class="descname">krb5_c_enctype_compare</tt><big>(</big><a class="reference internal" href="../types/krb5_context.html#c.krb5_context" title="krb5_context">krb5_context</a><em> context</em>, <a class="reference internal" href="../types/krb5_enctype.html#c.krb5_enctype" title="krb5_enctype">krb5_enctype</a><em> e1</em>, <a class="reference internal" href="../types/krb5_enctype.html#c.krb5_enctype" title="krb5_enctype">krb5_enctype</a><em> e2</em>, <a class="reference internal" href="../types/krb5_boolean.html#c.krb5_boolean" title="krb5_boolean">krb5_boolean</a> *<em> similar</em><big>)</big><a class="headerlink" href="#c.krb5_c_enctype_compare" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">param:</th><td class="field-body"><p class="first"><strong>[in]</strong> <strong>context</strong> - Library context</p>
<p><strong>[in]</strong> <strong>e1</strong> - First encryption type</p>
<p><strong>[in]</strong> <strong>e2</strong> - Second encryption type</p>
<p class="last"><strong>[out]</strong> <strong>similar</strong> - <strong>TRUE</strong> if types are similar, <strong>FALSE</strong> if not</p>
</td>
</tr>
</tbody>
</table>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">retval:</th><td class="field-body"><ul class="first last simple">
<li>0 Success; otherwise - Kerberos error codes</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>This function determines whether two encryption types use the same kind of keys.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sidebar">
<h2>On this page</h2>
<ul>
<li><a class="reference internal" href="#">krb5_c_enctype_compare - Compare two encryption types.</a></li>
</ul>
<br/>
<h2>Table of contents</h2>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../../user/index.html">For users</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../admin/index.html">For administrators</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../../index.html">For application developers</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../../gssapi.html">Developing with GSSAPI</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../y2038.html">Year 2038 considerations for uses of krb5_timestamp</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../h5l_mit_apidiff.html">Differences between Heimdal and MIT Kerberos API</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../init_creds.html">Initial credentials</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../princ_handle.html">Principal manipulation and parsing</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="../index.html">Complete reference - API and datatypes</a><ul class="current">
<li class="toctree-l3 current"><a class="reference internal" href="index.html">krb5 API</a></li>
<li class="toctree-l3"><a class="reference internal" href="../types/index.html">krb5 types and structures</a></li>
<li class="toctree-l3"><a class="reference internal" href="../macros/index.html">krb5 simple macros</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../../plugindev/index.html">For plugin module developers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../build/index.html">Building Kerberos V5</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../basic/index.html">Kerberos V5 concepts</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../formats/index.html">Protocols and file formats</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../mitK5features.html">MIT Kerberos features</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../build_this.html">How to build this documentation from the source</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../about.html">Contributing to the MIT Kerberos Documentation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../resources.html">Resources</a></li>
</ul>
<br/>
<h4><a href="../../../index.html">Full Table of Contents</a></h4>
<h4>Search</h4>
<form class="search" action="../../../search.html" method="get">
<input type="text" name="q" size="18" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<div class="clearer"></div>
</div>
</div>
<div class="footer-wrapper">
<div class="footer" >
<div class="right" ><i>Release: 1.16</i><br />
© <a href="../../../copyright.html">Copyright</a> 1985-2017, MIT.
</div>
<div class="left">
<a href="../../../index.html" title="Full Table of Contents"
>Contents</a> |
<a href="krb5_c_encrypt_length.html" title="krb5_c_encrypt_length - Compute encrypted data length."
>previous</a> |
<a href="krb5_c_free_state.html" title="krb5_c_free_state - Free a cipher state previously allocated by krb5_c_init_state() ."
>next</a> |
<a href="../../../genindex.html" title="General Index"
>index</a> |
<a href="../../../search.html" title="Enter search criteria"
>Search</a> |
<a href="mailto:krb5-bugs@mit.edu?subject=Documentation__krb5_c_enctype_compare - Compare two encryption types.">feedback</a>
</div>
</div>
</div>
</body>
</html> | {
"content_hash": "90054fe023a7bcbdaf5aedd793430f85",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 853,
"avg_line_length": 54.04545454545455,
"alnum_prop": 0.6257359125315392,
"repo_name": "gerritjvv/cryptoplayground",
"id": "436e2a0d44d9e160758fe6b0aca5fdbf4c4f0ef3",
"size": "9514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kerberos/kdc/src/krb5-1.16/doc/html/appdev/refs/api/krb5_c_enctype_compare.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "40918"
},
{
"name": "Awk",
"bytes": "10967"
},
{
"name": "Batchfile",
"bytes": "2734"
},
{
"name": "C",
"bytes": "14209534"
},
{
"name": "C++",
"bytes": "822611"
},
{
"name": "CMake",
"bytes": "486373"
},
{
"name": "CSS",
"bytes": "72712"
},
{
"name": "Emacs Lisp",
"bytes": "6797"
},
{
"name": "HTML",
"bytes": "10177760"
},
{
"name": "Java",
"bytes": "88477"
},
{
"name": "JavaScript",
"bytes": "91201"
},
{
"name": "Lex",
"bytes": "1395"
},
{
"name": "M4",
"bytes": "25420"
},
{
"name": "Makefile",
"bytes": "4976551"
},
{
"name": "NSIS",
"bytes": "94536"
},
{
"name": "Perl",
"bytes": "138102"
},
{
"name": "Perl 6",
"bytes": "7955"
},
{
"name": "Python",
"bytes": "493201"
},
{
"name": "RPC",
"bytes": "5974"
},
{
"name": "Roff",
"bytes": "340434"
},
{
"name": "Shell",
"bytes": "103572"
},
{
"name": "TeX",
"bytes": "2040204"
},
{
"name": "Yacc",
"bytes": "34752"
},
{
"name": "sed",
"bytes": "613"
}
],
"symlink_target": ""
} |
package network::ruggedcom::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
%{$self->{modes}} = (
'errors' => 'network::ruggedcom::mode::errors',
'hardware' => 'network::ruggedcom::mode::hardware',
'interfaces' => 'snmp_standard::mode::interfaces',
'memory' => 'network::ruggedcom::mode::memory',
'temperature' => 'network::ruggedcom::mode::temperature',
'list-interfaces' => 'snmp_standard::mode::listinterfaces',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Ruggedcom devices in SNMP.
=cut
| {
"content_hash": "425e44dd8f583bba0a91eddabec87830",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 91,
"avg_line_length": 29.181818181818183,
"alnum_prop": 0.48494288681204567,
"repo_name": "bcournaud/centreon-plugins",
"id": "86d953df6ea748e3976addd8ac130b48ba3e9005",
"size": "1723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "network/ruggedcom/plugin.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Perl",
"bytes": "7389420"
}
],
"symlink_target": ""
} |
% This code reproduces the analyses in the paper
% Urai AE, Braun A, Donner THD (2016) Pupil-linked arousal is driven
% by decision uncertainty and alters serial choice bias.
%
% 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.
% If you use the Software for your own research, cite the paper.
%
% 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.
%
% Anne Urai, 2016
% anne.urai@gmail.com
clearvars -except mypath;
global mypath; close all; clc;
mods = {'pupil', 'rt'};
for m = 1:2,
subplot(4,4,m);
grandavg{m} = postPupilBehaviour(mods{m}, 3, []);
plot([1 nbins], [0.5 0.5], 'k:', 'linewidth', 0.5); hold on;
for r = 1:2,
x = [1:3] + (r-1)*0.1;
y = squeeze(grandavg{m}.logisticHistory(:, r, :));
colors = cbrewer('qual', 'Set2', 3);
switch r
case 1
thismarker = '.';
thismarkersize = 14;
thiscolor = colors(1,:);
case 2
thismarker = '.';
thismarkersize = 14;
thiscolor = colors(3,:);
end
h = ploterr(x, squeeze(nanmean(y)), [], ...
squeeze(nanstd(y)) ./sqrt(length(y)), 'k-', 'abshhxy', 0);
set(h(1), 'color', thiscolor, 'markersize', thismarkersize, 'marker',thismarker);
set(h(2), 'color', thiscolor); % line color
end
switch mods{m}
case 'pupil'
xticklabs = repmat({' '}, 1, nbins);
xticklabs{1} = 'low';
xticklabs{end} = 'high';
if nbins == 3, xticklabs{2} = 'med'; end
case 'rt'
xticklabs = repmat({' '}, 1, nbins);
xticklabs{1} = 'fast';
xticklabs{end} = 'slow';
if nbins == 3, xticklabs{2} = 'med'; end
otherwise
xticklabs = repmat({' '}, 1, nbins);
xticklabs{1} = 'low';
xticklabs{end} = 'high';
end
set(gca, 'xlim', [0.5 nbins+0.5], 'xtick', 1:nbins, 'xticklabel', xticklabs, ...
'xcolor', 'k', 'ycolor', 'k', 'linewidth', 0.5, 'box', 'off', 'xminortick', 'off', 'yminortick', 'off');
axis square; xlim([0.5 nbins+0.5]);
ylabel('P(choice = 1');
% do statistics, repeated measures anova across bins
switch mods{m}
case 'pupil'
xlabel('Previous trial pupil');
set(gca, 'ylim', [0.45 0.55], 'ytick', [0.45:0.05:0.55]);
case 'rt'
xlabel('Previous trial RT');
set(gca, 'ylim', [0.45 0.55], 'ytick', [0.45:0.05:0.55]);
otherwise
xlabel(sprintf('Previous trial %s', mods{m}));
end
end
print(gcf, '-dpdf', sprintf('%s/Figures/FigureS5.pdf', mypath));
| {
"content_hash": "04ee90fae717ddd015aa6173d33a3348",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 112,
"avg_line_length": 40.04347826086956,
"alnum_prop": 0.5808903365906624,
"repo_name": "anne-urai/pupilUncertainty",
"id": "a1550ddb5b282c8889c3efdb775f5676057a1fc6",
"size": "3684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Analysis/figureS5.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Matlab",
"bytes": "585870"
},
{
"name": "Python",
"bytes": "120228"
},
{
"name": "R",
"bytes": "4714"
},
{
"name": "Shell",
"bytes": "1229"
}
],
"symlink_target": ""
} |
(function(window, factory) {
if(!window) {return;}
var globalInstall = function(){
factory(window.lazySizes);
window.removeEventListener('lazyunveilread', globalInstall, true);
};
factory = factory.bind(null, window, window.document);
if(typeof module == 'object' && module.exports){
factory(require('lazysizes'));
} else if (typeof define == 'function' && define.amd) {
define(['lazysizes'], factory);
} else if(window.lazySizes) {
globalInstall();
} else {
window.addEventListener('lazyunveilread', globalInstall, true);
}
}(typeof window != 'undefined' ?
window : 0, function(window, document, lazySizes) {
/*jshint eqnull:true */
'use strict';
var polyfill;
var lazySizesCfg = lazySizes.cfg;
var img = document.createElement('img');
var supportSrcset = ('sizes' in img) && ('srcset' in img);
var regHDesc = /\s+\d+h/g;
var fixEdgeHDescriptor = (function(){
var regDescriptors = /\s+(\d+)(w|h)\s+(\d+)(w|h)/;
var forEach = Array.prototype.forEach;
return function(){
var img = document.createElement('img');
var removeHDescriptors = function(source){
var ratio, match;
var srcset = source.getAttribute(lazySizesCfg.srcsetAttr);
if(srcset){
if((match = srcset.match(regDescriptors))){
if(match[2] == 'w'){
ratio = match[1] / match[3];
} else {
ratio = match[3] / match[1];
}
if(ratio){
source.setAttribute('data-aspectratio', ratio);
}
source.setAttribute(lazySizesCfg.srcsetAttr, srcset.replace(regHDesc, ''));
}
}
};
var handler = function(e){
if(e.detail.instance != lazySizes){return;}
var picture = e.target.parentNode;
if(picture && picture.nodeName == 'PICTURE'){
forEach.call(picture.getElementsByTagName('source'), removeHDescriptors);
}
removeHDescriptors(e.target);
};
var test = function(){
if(!!img.currentSrc){
document.removeEventListener('lazybeforeunveil', handler);
}
};
document.addEventListener('lazybeforeunveil', handler);
img.onload = test;
img.onerror = test;
img.srcset = 'data:,a 1w 1h';
if(img.complete){
test();
}
};
})();
if(!lazySizesCfg.supportsType){
lazySizesCfg.supportsType = function(type/*, elem*/){
return !type;
};
}
if (window.HTMLPictureElement && supportSrcset) {
if(!lazySizes.hasHDescriptorFix && document.msElementsFromPoint){
lazySizes.hasHDescriptorFix = true;
fixEdgeHDescriptor();
}
return;
}
if(window.picturefill || lazySizesCfg.pf){return;}
lazySizesCfg.pf = function(options){
var i, len;
if(window.picturefill){return;}
for(i = 0, len = options.elements.length; i < len; i++){
polyfill(options.elements[i]);
}
};
// partial polyfill
polyfill = (function(){
var ascendingSort = function( a, b ) {
return a.w - b.w;
};
var regPxLength = /^\s*\d+\.*\d*px\s*$/;
var reduceCandidate = function (srces) {
var lowerCandidate, bonusFactor;
var len = srces.length;
var candidate = srces[len -1];
var i = 0;
for(i; i < len;i++){
candidate = srces[i];
candidate.d = candidate.w / srces.w;
if(candidate.d >= srces.d){
if(!candidate.cached && (lowerCandidate = srces[i - 1]) &&
lowerCandidate.d > srces.d - (0.13 * Math.pow(srces.d, 2.2))){
bonusFactor = Math.pow(lowerCandidate.d - 0.6, 1.6);
if(lowerCandidate.cached) {
lowerCandidate.d += 0.15 * bonusFactor;
}
if(lowerCandidate.d + ((candidate.d - srces.d) * bonusFactor) > srces.d){
candidate = lowerCandidate;
}
}
break;
}
}
return candidate;
};
var parseWsrcset = (function(){
var candidates;
var regWCandidates = /(([^,\s].[^\s]+)\s+(\d+)w)/g;
var regMultiple = /\s/;
var addCandidate = function(match, candidate, url, wDescriptor){
candidates.push({
c: candidate,
u: url,
w: wDescriptor * 1
});
};
return function(input){
candidates = [];
input = input.trim();
input
.replace(regHDesc, '')
.replace(regWCandidates, addCandidate)
;
if(!candidates.length && input && !regMultiple.test(input)){
candidates.push({
c: input,
u: input,
w: 99
});
}
return candidates;
};
})();
var runMatchMedia = function(){
if(runMatchMedia.init){return;}
runMatchMedia.init = true;
addEventListener('resize', (function(){
var timer;
var matchMediaElems = document.getElementsByClassName('lazymatchmedia');
var run = function(){
var i, len;
for(i = 0, len = matchMediaElems.length; i < len; i++){
polyfill(matchMediaElems[i]);
}
};
return function(){
clearTimeout(timer);
timer = setTimeout(run, 66);
};
})());
};
var createSrcset = function(elem, isImage){
var parsedSet;
var srcSet = elem.getAttribute('srcset') || elem.getAttribute(lazySizesCfg.srcsetAttr);
if(!srcSet && isImage){
srcSet = !elem._lazypolyfill ?
(elem.getAttribute(lazySizesCfg.srcAttr) || elem.getAttribute('src')) :
elem._lazypolyfill._set
;
}
if(!elem._lazypolyfill || elem._lazypolyfill._set != srcSet){
parsedSet = parseWsrcset( srcSet || '' );
if(isImage && elem.parentNode){
parsedSet.isPicture = elem.parentNode.nodeName.toUpperCase() == 'PICTURE';
if(parsedSet.isPicture){
if(window.matchMedia){
lazySizes.aC(elem, 'lazymatchmedia');
runMatchMedia();
}
}
}
parsedSet._set = srcSet;
Object.defineProperty(elem, '_lazypolyfill', {
value: parsedSet,
writable: true
});
}
};
var getX = function(elem){
var dpr = window.devicePixelRatio || 1;
var optimum = lazySizes.getX && lazySizes.getX(elem);
return Math.min(optimum || dpr, 2.5, dpr);
};
var matchesMedia = function(media){
if(window.matchMedia){
matchesMedia = function(media){
return !media || (matchMedia(media) || {}).matches;
};
} else {
return !media;
}
return matchesMedia(media);
};
var getCandidate = function(elem){
var sources, i, len, media, source, srces, src, width;
source = elem;
createSrcset(source, true);
srces = source._lazypolyfill;
if(srces.isPicture){
for(i = 0, sources = elem.parentNode.getElementsByTagName('source'), len = sources.length; i < len; i++){
if( lazySizesCfg.supportsType(sources[i].getAttribute('type'), elem) && matchesMedia( sources[i].getAttribute('media')) ){
source = sources[i];
createSrcset(source);
srces = source._lazypolyfill;
break;
}
}
}
if(srces.length > 1){
width = source.getAttribute('sizes') || '';
width = regPxLength.test(width) && parseInt(width, 10) || lazySizes.gW(elem, elem.parentNode);
srces.d = getX(elem);
if(!srces.src || !srces.w || srces.w < width){
srces.w = width;
src = reduceCandidate(srces.sort(ascendingSort));
srces.src = src;
} else {
src = srces.src;
}
} else {
src = srces[0];
}
return src;
};
var p = function(elem){
if(supportSrcset && elem.parentNode && elem.parentNode.nodeName.toUpperCase() != 'PICTURE'){return;}
var candidate = getCandidate(elem);
if(candidate && candidate.u && elem._lazypolyfill.cur != candidate.u){
elem._lazypolyfill.cur = candidate.u;
candidate.cached = true;
elem.setAttribute(lazySizesCfg.srcAttr, candidate.u);
elem.setAttribute('src', candidate.u);
}
};
p.parse = parseWsrcset;
return p;
})();
if(lazySizesCfg.loadedClass && lazySizesCfg.loadingClass){
(function(){
var sels = [];
['img[sizes$="px"][srcset].', 'picture > img:not([srcset]).'].forEach(function(sel){
sels.push(sel + lazySizesCfg.loadedClass);
sels.push(sel + lazySizesCfg.loadingClass);
});
lazySizesCfg.pf({
elements: document.querySelectorAll(sels.join(', '))
});
})();
}
}));
| {
"content_hash": "ef0715e7565495732e2f9efb466b87c5",
"timestamp": "",
"source": "github",
"line_count": 311,
"max_line_length": 127,
"avg_line_length": 25.437299035369776,
"alnum_prop": 0.6192643155100493,
"repo_name": "cdnjs/cdnjs",
"id": "512dd6132c59bfe8faf58fe154a4d13877f4ff83",
"size": "7911",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "ajax/libs/lazysizes/5.3.0-beta1/plugins/respimg/ls.respimg.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Poltergeist.FrameNotFound = (function (_super) {
__extends(FrameNotFound, _super);
function FrameNotFound(frameName) {
this.frameName = frameName;
}
FrameNotFound.prototype.name = "Poltergeist.FrameNotFound";
FrameNotFound.prototype.args = function () {
return [this.frameName];
};
return FrameNotFound;
})(Poltergeist.Error);
| {
"content_hash": "a215f7d9527c0855c63f0cabe20db26e",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 61,
"avg_line_length": 22.125,
"alnum_prop": 0.711864406779661,
"repo_name": "sweimer/ICFID8",
"id": "d42e87256077c969f315b6661104cfc7dbf20a2f",
"size": "354",
"binary": false,
"copies": "385",
"ref": "refs/heads/master",
"path": "docroot/vendor/jcalderonzumba/gastonjs/src/Client/Errors/frame_not_found.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "974154"
},
{
"name": "Gherkin",
"bytes": "10701"
},
{
"name": "HTML",
"bytes": "813389"
},
{
"name": "JavaScript",
"bytes": "2371726"
},
{
"name": "PHP",
"bytes": "38283693"
},
{
"name": "PLpgSQL",
"bytes": "2020"
},
{
"name": "Shell",
"bytes": "62999"
}
],
"symlink_target": ""
} |
package kafka.server.epoch
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import kafka.cluster.Replica
import kafka.server._
import kafka.utils.{MockTime, TestUtils}
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.metrics.Metrics
import org.apache.kafka.common.protocol.Errors
import org.apache.kafka.common.requests.EpochEndOffset
import org.apache.kafka.common.requests.EpochEndOffset._
import org.easymock.EasyMock._
import org.junit.Assert._
import org.junit.Test
class OffsetsForLeaderEpochTest {
private val config = TestUtils.createBrokerConfigs(1, TestUtils.MockZkConnect).map(KafkaConfig.fromProps).head
private val time = new MockTime
private val metrics = new Metrics
private val tp = new TopicPartition("topic", 1)
@Test
def shouldGetEpochsFromReplica(): Unit = {
//Given
val epochAndOffset = (5, 42L)
val epochRequested: Integer = 5
val request = Map(tp -> epochRequested)
//Stubs
val mockLog = createNiceMock(classOf[kafka.log.Log])
val mockCache = createNiceMock(classOf[kafka.server.epoch.LeaderEpochCache])
val logManager = createNiceMock(classOf[kafka.log.LogManager])
expect(mockCache.endOffsetFor(epochRequested)).andReturn(epochAndOffset)
expect(mockLog.leaderEpochCache).andReturn(mockCache).anyTimes()
expect(logManager.liveLogDirs).andReturn(Array.empty[File]).anyTimes()
replay(mockCache, mockLog, logManager)
// create a replica manager with 1 partition that has 1 replica
val replicaManager = new ReplicaManager(config, metrics, time, null, null, logManager, new AtomicBoolean(false),
QuotaFactory.instantiate(config, metrics, time, ""), new BrokerTopicStats,
new MetadataCache(config.brokerId), new LogDirFailureChannel(config.logDirs.size))
val partition = replicaManager.getOrCreatePartition(tp)
val leaderReplica = new Replica(config.brokerId, partition.topicPartition, time, 0, Some(mockLog))
partition.addReplicaIfNotExists(leaderReplica)
partition.leaderReplicaIdOpt = Some(config.brokerId)
//When
val response = replicaManager.lastOffsetForLeaderEpoch(request)
//Then
assertEquals(new EpochEndOffset(Errors.NONE, epochAndOffset._1, epochAndOffset._2), response(tp))
}
@Test
def shouldReturnNoLeaderForPartitionIfThrown(): Unit = {
val logManager = createNiceMock(classOf[kafka.log.LogManager])
expect(logManager.liveLogDirs).andReturn(Array.empty[File]).anyTimes()
replay(logManager)
//create a replica manager with 1 partition that has 0 replica
val replicaManager = new ReplicaManager(config, metrics, time, null, null, logManager, new AtomicBoolean(false),
QuotaFactory.instantiate(config, metrics, time, ""), new BrokerTopicStats,
new MetadataCache(config.brokerId), new LogDirFailureChannel(config.logDirs.size))
replicaManager.getOrCreatePartition(tp)
//Given
val epochRequested: Integer = 5
val request = Map(tp -> epochRequested)
//When
val response = replicaManager.lastOffsetForLeaderEpoch(request)
//Then
assertEquals(new EpochEndOffset(Errors.NOT_LEADER_FOR_PARTITION, UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), response(tp))
}
@Test
def shouldReturnUnknownTopicOrPartitionIfThrown(): Unit = {
val logManager = createNiceMock(classOf[kafka.log.LogManager])
expect(logManager.liveLogDirs).andReturn(Array.empty[File]).anyTimes()
replay(logManager)
//create a replica manager with 0 partition
val replicaManager = new ReplicaManager(config, metrics, time, null, null, logManager, new AtomicBoolean(false),
QuotaFactory.instantiate(config, metrics, time, ""), new BrokerTopicStats,
new MetadataCache(config.brokerId), new LogDirFailureChannel(config.logDirs.size))
//Given
val epochRequested: Integer = 5
val request = Map(tp -> epochRequested)
//When
val response = replicaManager.lastOffsetForLeaderEpoch(request)
//Then
assertEquals(new EpochEndOffset(Errors.UNKNOWN_TOPIC_OR_PARTITION, UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET), response(tp))
}
}
| {
"content_hash": "0d017052d402d5b0094f292e1fcb6728",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 126,
"avg_line_length": 40.333333333333336,
"alnum_prop": 0.7603305785123967,
"repo_name": "richhaase/kafka",
"id": "5c60c0017db380d21ba436597e47c02d12d73418",
"size": "4927",
"binary": false,
"copies": "4",
"ref": "refs/heads/trunk",
"path": "core/src/test/scala/unit/kafka/server/epoch/OffsetsForLeaderEpochTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "26635"
},
{
"name": "Dockerfile",
"bytes": "6592"
},
{
"name": "HTML",
"bytes": "3739"
},
{
"name": "Java",
"bytes": "14025660"
},
{
"name": "Python",
"bytes": "737819"
},
{
"name": "Scala",
"bytes": "5421222"
},
{
"name": "Shell",
"bytes": "92931"
},
{
"name": "XSLT",
"bytes": "7116"
}
],
"symlink_target": ""
} |
/* French initialisation for the jQuery UI date picker plugin. */
/* Written by Keith Wood (kbwood{at}iinet.com.au),
Stéphane Nahmani (sholby@sholby.net),
Stéphane Raimbault <stephane.raimbault@gmail.com> */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "../datepicker" ], factory );
} else {
// Browser globals
factory( jQuery.datepicker );
}
}(function( datepicker ) {
datepicker.regional['fr'] = {
closeText: 'Fermer',
prevText: 'Précédent',
nextText: 'Suivant',
currentText: 'Aujourd\'hui',
monthNames: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
monthNamesShort: ['janv.', 'févr.', 'mars', 'avril', 'mai', 'juin',
'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'],
dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
dayNamesMin: ['D','L','M','M','J','V','S'],
weekHeader: 'Sem.',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
datepicker.setDefaults(datepicker.regional['fr']);
return datepicker.regional['fr'];
}));
| {
"content_hash": "a83854b5a5c61b583433ddd4b2607ae2",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 85,
"avg_line_length": 33.82051282051282,
"alnum_prop": 0.6065200909780136,
"repo_name": "ghostsphinx/web-evidence",
"id": "6fc2365236f02680e3444becfd56300a7580f92c",
"size": "1329",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "app/bower_components/jquery-ui/ui/i18n/datepicker-fr.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8862"
},
{
"name": "HTML",
"bytes": "20762"
},
{
"name": "JavaScript",
"bytes": "320652"
}
],
"symlink_target": ""
} |
DECLARE_string(test_srcdir);
DECLARE_string(test_tmpdir);
DECLARE_bool(use_history_rewriter);
namespace mozc {
namespace {
string GetComposition(const commands::Command &command) {
if (!command.output().has_preedit()) {
return "";
}
string preedit;
for (size_t i = 0; i < command.output().preedit().segment_size(); ++i) {
preedit.append(command.output().preedit().segment(i).value());
}
return preedit;
}
void InitSessionToPrecomposition(session::Session* session) {
#ifdef OS_WIN
// Session is created with direct mode on Windows
// Direct status
commands::Command command;
session->IMEOn(&command);
#endif // OS_WIN
}
} // namespace
class SessionRegressionTest : public testing::Test {
protected:
virtual void SetUp() {
SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
orig_use_history_rewriter_ = FLAGS_use_history_rewriter;
FLAGS_use_history_rewriter = true;
// Note: engine must be created after setting all the flags, as it
// internally depends on global flags, e.g., for creation of rewriters.
engine_.reset(EngineFactory::Create());
handler_.reset(new SessionHandler(engine_.get()));
ResetSession();
CHECK(session_.get());
}
virtual void TearDown() {
// just in case, reset the config in test_tmpdir
config::Config config;
config::ConfigHandler::GetDefaultConfig(&config);
config::ConfigHandler::SetConfig(config);
FLAGS_use_history_rewriter = orig_use_history_rewriter_;
}
bool SendKey(const string &key, commands::Command *command) {
command->Clear();
command->mutable_input()->set_type(commands::Input::SEND_KEY);
if (!KeyParser::ParseKey(key, command->mutable_input()->mutable_key())) {
return false;
}
return session_->SendKey(command);
}
bool SendKeyWithContext(const string &key,
const commands::Context &context,
commands::Command *command) {
command->Clear();
command->mutable_input()->mutable_context()->CopyFrom(context);
command->mutable_input()->set_type(commands::Input::SEND_KEY);
if (!KeyParser::ParseKey(key, command->mutable_input()->mutable_key())) {
return false;
}
return session_->SendKey(command);
}
void InsertCharacterChars(const string &chars,
commands::Command *command) {
const uint32 kNoModifiers = 0;
for (size_t i = 0; i < chars.size(); ++i) {
command->clear_input();
command->clear_output();
commands::KeyEvent *key_event = command->mutable_input()->mutable_key();
key_event->set_key_code(chars[i]);
key_event->set_modifiers(kNoModifiers);
session_->InsertCharacter(command);
}
}
void ResetSession() {
session_.reset(static_cast<session::Session *>(handler_->NewSession()));
commands::Request request;
table_.reset(new composer::Table());
table_->InitializeWithRequestAndConfig(request, config_);
session_->SetTable(table_.get());
}
bool orig_use_history_rewriter_;
std::unique_ptr<EngineInterface> engine_;
std::unique_ptr<SessionHandler> handler_;
std::unique_ptr<session::Session> session_;
std::unique_ptr<composer::Table> table_;
config::Config config_;
scoped_data_manager_initializer_for_testing
scoped_data_manager_initializer_for_testing_;
};
TEST_F(SessionRegressionTest, ConvertToTransliterationWithMultipleSegments) {
InitSessionToPrecomposition(session_.get());
commands::Command command;
InsertCharacterChars("liie", &command);
// Convert
command.Clear();
session_->Convert(&command);
{ // Check the conversion #1
const commands::Output &output = command.output();
EXPECT_FALSE(output.has_result());
EXPECT_TRUE(output.has_preedit());
EXPECT_FALSE(output.has_candidates());
const commands::Preedit &conversion = output.preedit();
ASSERT_LE(2, conversion.segment_size());
// "ぃ"
EXPECT_EQ("\xE3\x81\x83", conversion.segment(0).value());
}
// TranslateHalfASCII
command.Clear();
session_->TranslateHalfASCII(&command);
{ // Check the conversion #2
const commands::Output &output = command.output();
EXPECT_FALSE(output.has_result());
EXPECT_TRUE(output.has_preedit());
EXPECT_FALSE(output.has_candidates());
const commands::Preedit &conversion = output.preedit();
ASSERT_EQ(2, conversion.segment_size());
EXPECT_EQ("li", conversion.segment(0).value());
}
}
TEST_F(SessionRegressionTest,
ExitTemporaryAlphanumModeAfterCommitingSugesstion) {
// This is a regression test against http://b/2977131.
{
InitSessionToPrecomposition(session_.get());
commands::Command command;
InsertCharacterChars("NFL", &command);
EXPECT_EQ(commands::HALF_ASCII, command.output().status().mode());
EXPECT_EQ(commands::HALF_ASCII, command.output().mode()); // obsolete
EXPECT_TRUE(SendKey("F10", &command));
ASSERT_FALSE(command.output().has_candidates());
EXPECT_FALSE(command.output().has_result());
EXPECT_TRUE(SendKey("a", &command));
#if OS_MACOSX
// The MacOS default short cut of F10 is DisplayAsHalfAlphanumeric.
// It does not start the conversion so output does not have any result.
EXPECT_FALSE(command.output().has_result());
#else
EXPECT_TRUE(command.output().has_result());
#endif
EXPECT_EQ(commands::HIRAGANA, command.output().status().mode());
EXPECT_EQ(commands::HIRAGANA, command.output().mode()); // obsolete
}
}
TEST_F(SessionRegressionTest, HistoryLearning) {
InitSessionToPrecomposition(session_.get());
commands::Command command;
string candidate1;
string candidate2;
{ // First session. Second candidate is commited.
InsertCharacterChars("kanji", &command);
command.Clear();
session_->Convert(&command);
candidate1 = GetComposition(command);
command.Clear();
session_->ConvertNext(&command);
candidate2 = GetComposition(command);
EXPECT_NE(candidate1, candidate2);
command.Clear();
session_->Commit(&command);
EXPECT_FALSE(command.output().has_preedit());
EXPECT_EQ(candidate2, command.output().result().value());
}
{ // Second session. The previous second candidate should be promoted.
command.Clear();
InsertCharacterChars("kanji", &command);
command.Clear();
session_->Convert(&command);
EXPECT_NE(candidate1, GetComposition(command));
EXPECT_EQ(candidate2, GetComposition(command));
}
}
TEST_F(SessionRegressionTest, Undo) {
InitSessionToPrecomposition(session_.get());
commands::Capability capability;
capability.set_text_deletion(commands::Capability::DELETE_PRECEDING_TEXT);
session_->set_client_capability(capability);
commands::Command command;
InsertCharacterChars("kanji", &command);
command.Clear();
session_->Convert(&command);
const string candidate1 = GetComposition(command);
command.Clear();
session_->ConvertNext(&command);
const string candidate2 = GetComposition(command);
EXPECT_NE(candidate1, candidate2);
command.Clear();
session_->Commit(&command);
EXPECT_FALSE(command.output().has_preedit());
EXPECT_EQ(candidate2, command.output().result().value());
command.Clear();
session_->Undo(&command);
EXPECT_NE(candidate1, GetComposition(command));
EXPECT_EQ(candidate2, GetComposition(command));
}
// TODO(hsumita): This test may be moved to session_test.cc.
// New converter mock is required if move this test.
TEST_F(SessionRegressionTest, PredictionAfterUndo) {
// This is a unittest against http://b/3427619
InitSessionToPrecomposition(session_.get());
commands::Capability capability;
capability.set_text_deletion(commands::Capability::DELETE_PRECEDING_TEXT);
session_->set_client_capability(capability);
commands::Command command;
InsertCharacterChars("yoroshi", &command);
// "よろしく"
const string kYoroshikuString =
"\xe3\x82\x88\xe3\x82\x8d\xe3\x81\x97\xe3\x81\x8f";
command.Clear();
session_->PredictAndConvert(&command);
EXPECT_EQ(1, command.output().preedit().segment_size());
// Candidate contain "よろしく" or NOT
int yoroshiku_id = -1;
for (size_t i = 0; i < 10; ++i) {
if (GetComposition(command) == kYoroshikuString) {
yoroshiku_id = i;
break;
}
command.Clear();
session_->ConvertNext(&command);
}
EXPECT_EQ(kYoroshikuString, GetComposition(command));
EXPECT_GE(yoroshiku_id, 0);
command.Clear();
session_->Commit(&command);
EXPECT_FALSE(command.output().has_preedit());
EXPECT_EQ(kYoroshikuString, command.output().result().value());
command.Clear();
session_->Undo(&command);
EXPECT_EQ(kYoroshikuString, GetComposition(command));
}
// This test is to check the consistency between the result of prediction and
// suggestion.
// Following 4 values are expected to be the same.
// - The 1st candidate of prediction.
// - The result of CommitFirstSuggestion for prediction candidate.
// - The 1st candidate of suggestion.
// - The result of CommitFirstSuggestion for suggestion candidate.
//
// BACKGROUND:
// Previously there was a restriction on the result of prediction
// and suggestion.
// Currently the restriction is removed. This test checks that the logic
// works well or not.
TEST_F(SessionRegressionTest, ConsistencyBetweenPredictionAndSuggesion) {
const char kKey[] = "aio";
commands::Request request;
commands::RequestForUnitTest::FillMobileRequest(&request);
session_->SetRequest(&request);
InitSessionToPrecomposition(session_.get());
commands::Command command;
command.Clear();
InsertCharacterChars(kKey, &command);
EXPECT_EQ(1, command.output().preedit().segment_size());
const string suggestion_first_candidate =
command.output().all_candidate_words().candidates(0).value();
command.Clear();
session_->CommitFirstSuggestion(&command);
const string suggestion_commit_result = command.output().result().value();
InitSessionToPrecomposition(session_.get());
command.Clear();
InsertCharacterChars(kKey, &command);
command.Clear();
session_->PredictAndConvert(&command);
const string prediction_first_candidate =
command.output().all_candidate_words().candidates(0).value();
command.Clear();
session_->Commit(&command);
const string prediction_commit_result = command.output().result().value();
EXPECT_EQ(suggestion_first_candidate, suggestion_commit_result);
EXPECT_EQ(suggestion_first_candidate, prediction_first_candidate);
EXPECT_EQ(suggestion_first_candidate, prediction_commit_result);
}
TEST_F(SessionRegressionTest, AutoConversionTest) {
// Default mode
{
ResetSession();
commands::Command command;
InitSessionToPrecomposition(session_.get());
const char kInputKeys[] = "123456.7";
for (size_t i = 0; kInputKeys[i]; ++i) {
command.Clear();
commands::KeyEvent *key_event = command.mutable_input()->mutable_key();
key_event->set_key_code(kInputKeys[i]);
key_event->set_key_string(string(1, kInputKeys[i]));
session_->InsertCharacter(&command);
}
EXPECT_EQ(session::ImeContext::COMPOSITION, session_->context().state());
}
// Auto conversion with KUTEN
{
ResetSession();
commands::Command command;
InitSessionToPrecomposition(session_.get());
config::Config config;
config::ConfigHandler::GetDefaultConfig(&config);
config.set_use_auto_conversion(true);
session_->SetConfig(&config);
const char kInputKeys[] = "aiueo.";
for (size_t i = 0; i < kInputKeys[i]; ++i) {
command.Clear();
commands::KeyEvent *key_event = command.mutable_input()->mutable_key();
key_event->set_key_code(kInputKeys[i]);
key_event->set_key_string(string(1, kInputKeys[i]));
session_->InsertCharacter(&command);
}
EXPECT_EQ(session::ImeContext::CONVERSION, session_->context().state());
}
// Auto conversion with KUTEN, but do not convert in numerical input
{
ResetSession();
commands::Command command;
InitSessionToPrecomposition(session_.get());
config::Config config;
config::ConfigHandler::GetConfig(&config);
config.set_use_auto_conversion(true);
session_->SetConfig(&config);
const char kInputKeys[] = "1234.";
for (size_t i = 0; i < kInputKeys[i]; ++i) {
command.Clear();
commands::KeyEvent *key_event = command.mutable_input()->mutable_key();
key_event->set_key_code(kInputKeys[i]);
key_event->set_key_string(string(1, kInputKeys[i]));
session_->InsertCharacter(&command);
}
EXPECT_EQ(session::ImeContext::COMPOSITION, session_->context().state());
}
}
TEST_F(SessionRegressionTest, Transliteration_Issue2330463) {
{
ResetSession();
commands::Command command;
InsertCharacterChars("[],.", &command);
command.Clear();
SendKey("F8", &command);
// "「」、。"
EXPECT_EQ("\357\275\242\357\275\243\357\275\244\357\275\241",
command.output().preedit().segment(0).value());
}
{
ResetSession();
commands::Command command;
InsertCharacterChars("[g],.", &command);
command.Clear();
SendKey("F8", &command);
// "「g」、。"
EXPECT_EQ("\357\275\242\147\357\275\243\357\275\244\357\275\241",
command.output().preedit().segment(0).value());
}
{
ResetSession();
commands::Command command;
InsertCharacterChars("[a],.", &command);
command.Clear();
SendKey("F8", &command);
// "「ア」、。"
EXPECT_EQ("\357\275\242\357\275\261\357\275\243\357\275\244\357\275\241",
command.output().preedit().segment(0).value());
}
}
TEST_F(SessionRegressionTest, Transliteration_Issue6209563) {
{ // Romaji mode
ResetSession();
commands::Command command;
InsertCharacterChars("tt", &command);
command.Clear();
SendKey("F10", &command);
EXPECT_EQ("tt", command.output().preedit().segment(0).value());
}
{ // Kana mode
ResetSession();
commands::Command command;
InitSessionToPrecomposition(session_.get());
config::Config config;
config::ConfigHandler::GetConfig(&config);
config.set_preedit_method(config::Config::KANA);
// Inserts "ち" 5 times
for (int i = 0; i < 5; ++i) {
command.Clear();
commands::KeyEvent *key_event = command.mutable_input()->mutable_key();
key_event->set_key_code('a');
key_event->set_key_string("\xE3\x81\xA1"); // "ち"
session_->InsertCharacter(&command);
}
command.Clear();
SendKey("F10", &command);
EXPECT_EQ("aaaaa", command.output().preedit().segment(0).value());
}
}
TEST_F(SessionRegressionTest, CommitT13nSuggestion) {
// This is the test for http://b/6934881.
// Pending char chunk remains after committing transliteration.
commands::Request request;
commands::RequestForUnitTest::FillMobileRequest(&request);
session_->SetRequest(&request);
InitSessionToPrecomposition(session_.get());
commands::Command command;
InsertCharacterChars("ssh", &command);
// "っsh"
EXPECT_EQ("\xE3\x81\xA3\xEF\xBD\x93\xEF\xBD\x88", GetComposition(command));
command.Clear();
command.mutable_input()->set_type(commands::Input::SEND_COMMAND);
command.mutable_input()->mutable_command()->set_type(
commands::SessionCommand::SUBMIT_CANDIDATE);
const int kHiraganaId = -1;
command.mutable_input()->mutable_command()->set_id(kHiraganaId);
session_->SendCommand(&command);
EXPECT_TRUE(command.output().has_result());
EXPECT_FALSE(command.output().has_preedit());
// "っsh"
EXPECT_EQ("\xE3\x81\xA3\xEF\xBD\x93\xEF\xBD\x88",
command.output().result().value());
}
} // namespace mozc
| {
"content_hash": "f977f961b44dc463881d49cc79f77285",
"timestamp": "",
"source": "github",
"line_count": 502,
"max_line_length": 78,
"avg_line_length": 31.121513944223107,
"alnum_prop": 0.6795749855981565,
"repo_name": "kbc-developers/Mozc",
"id": "ad5ce58ef3b4877e362f125de9cff5be5c7449d1",
"size": "18199",
"binary": false,
"copies": "1",
"ref": "refs/heads/android_package",
"path": "src/session/session_regression_test.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "114570"
},
{
"name": "C++",
"bytes": "10975036"
},
{
"name": "CSS",
"bytes": "26088"
},
{
"name": "Emacs Lisp",
"bytes": "80169"
},
{
"name": "HTML",
"bytes": "262086"
},
{
"name": "Java",
"bytes": "2755116"
},
{
"name": "JavaScript",
"bytes": "917935"
},
{
"name": "Makefile",
"bytes": "3833"
},
{
"name": "Objective-C",
"bytes": "425897"
},
{
"name": "Objective-C++",
"bytes": "226484"
},
{
"name": "Protocol Buffer",
"bytes": "112432"
},
{
"name": "Python",
"bytes": "1086778"
},
{
"name": "QMake",
"bytes": "861"
},
{
"name": "Shell",
"bytes": "12203"
},
{
"name": "Yacc",
"bytes": "1967"
}
],
"symlink_target": ""
} |
/**
* Created by nono on 16-2-19.
* 作为titleList和contentList的桥接
*
* 使用了百度的编辑器, 简化了富文本编辑方面的开发
* @desc 大概思路;
* 解压和压缩的实现
* 主要的main方法, 整个编辑器的初始化和事件的控制, 以及导出等;
* 左侧的视图, 右侧的可编辑内容;
* 约定标题名不能为"封面";
* */
define(["Construct/TitleList", "Construct/ContentList", "EpubBuilder", "Construct/DublinCore", "Construct/Preview" , "Construct/Lang"], function( TitleList, ContentList, EpubBuilder , DublinCore, Preview, Lang) {
var epub = new EpubBuilder();
var dublinCore = new DublinCore();
var titleView = new TitleList.TitleView({
el : $("#left-nav")
});
var contentListView = new ContentList.ContentListView({
el : $("#content-nav")
});
titleView.bind("create", function( index ) {
contentListView.create("", index);
});
titleView.bind("clone", function( index ) {
contentListView.clone(index);
});
titleView.bind("remove", function( index ) {
contentListView.remove(index);
});
titleView.bind("click", function( index ) {
contentListView.click(index);
});
titleView.create("");
/**
* @desc 获取界面编辑器的数据, 作为titleListView和ContntListView的辅助方法;
* @return {Object} {tocArray:[], contentArray:[]};
* */
function getData() {
var tocArray = titleView.$el.find("ul input").map(function() {
return this.value;
});
var contentArray = contentListView.$el.find(".edui-body-container").map(function() {
return UM.getEditor(this.id).getContent();
});
return {
tocArray : tocArray,
contentArray : contentArray
}
}
/**
* @desc 设置数据到view中, 作为titleListView和ContntListView的辅助方法;
* @param {Array}, {Array}
* [], []
* @example setData( [1,2,3,4], [11,22,33,44] );
* */
function setData( tocArray, contentArray ) {
var _this = this;
titleView.$el.find("ul").html("");
contentListView.$el.html("");
$.each(tocArray, function (i, e) {
//添加左侧nav
titleView.add($.trim(e));
//添加右侧内容;
contentListView.create( contentArray[i] );
});
}
$("input[name*=coverImage]").change(function() {
var _this = this;
if( util.isImage(_this.files[0].type) ) {
var file = _this.files[0];
//判断文件格式是否是image/*
var fileReader = new FileReader();
fileReader.readAsDataURL( file );
fileReader.onload = function () {
$(_this).attr("coverImage", arguments[0].target.result);
};
}
});
$("#build").bind("click", function( ev ) {
var data = getData();
ev.stopPropagation();
ev.preventDefault();
//获取目录结构,并合并到data中;
$.extend(data, dublinCore.getDublinCore());
epub.exportToEpub(data);
});
$("#open").click(function() {
epub.importEpub(setData);
});
//初始化默认语言;
new Lang().init();
new Preview();
}); | {
"content_hash": "60bc7afb5d448c00f6f1bd33337a57b4",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 213,
"avg_line_length": 25.225,
"alnum_prop": 0.5536835150313842,
"repo_name": "sqqihao/EPubBuilder",
"id": "ab37b02918652bdd9e5485fd3e4ba64e8391b8c5",
"size": "3355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "157836"
},
{
"name": "HTML",
"bytes": "90189"
},
{
"name": "JavaScript",
"bytes": "959349"
}
],
"symlink_target": ""
} |
#ifndef XTIPCOMBOBOX_H
#define XTIPCOMBOBOX_H
#include "XTipListBox.h"
/////////////////////////////////////////////////////////////////////////////
// CXTipComboBox window
class CXTipComboBox : public CComboBox
{
// Construction
public:
CXTipComboBox();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CXTipComboBox)
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
// Implementation
protected:
CXTipListBox m_listbox;
HWND m_hWndToolTip;
TOOLINFO m_ToolInfo;
// Generated message map functions
protected:
//{{AFX_MSG(CXTipComboBox)
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg void OnDestroy();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT_PTR nIDEvent);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif //XTIPCOMBOBOX_H
| {
"content_hash": "413ed9125e20fd0a508df5f2780b5514",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 97,
"avg_line_length": 24.244444444444444,
"alnum_prop": 0.6104491292392301,
"repo_name": "RNCan/WeatherBasedSimulationFramework",
"id": "a0640741c9c93367adcd1660217099e6da31f4d0",
"size": "1562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wbs/src/UI/Common/HTMLTree/XTipComboBox.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "25087"
},
{
"name": "C",
"bytes": "304223"
},
{
"name": "C#",
"bytes": "16020"
},
{
"name": "C++",
"bytes": "15327220"
},
{
"name": "HTML",
"bytes": "29355"
},
{
"name": "Python",
"bytes": "2061"
}
],
"symlink_target": ""
} |
/*
* cropit - v0.2.0
* Customizable crop and zoom.
* https://github.com/scottcheng/cropit
*
* Made by Scott Cheng
* Based on https://github.com/yufeiliu/simple_image_uploader
* Under MIT License
*/
(function($) {
var Zoomer;
Zoomer = function() {
function Zoomer() {}
Zoomer.prototype.setup = function(imageSize, previewSize, exportZoom, options) {
var heightRatio, widthRatio;
if (exportZoom == null) {
exportZoom = 1;
}
widthRatio = previewSize.w / imageSize.w;
heightRatio = previewSize.h / imageSize.h;
if ((options != null ? options.minZoom : void 0) === "fit") {
this.minZoom = widthRatio < heightRatio ? widthRatio : heightRatio;
} else {
this.minZoom = widthRatio < heightRatio ? heightRatio : widthRatio;
}
return this.maxZoom = this.minZoom < 1 / exportZoom ? 1 / exportZoom : this.minZoom;
};
Zoomer.prototype.getZoom = function(sliderPos) {
if (!(this.minZoom && this.maxZoom)) {
return null;
}
return sliderPos * (this.maxZoom - this.minZoom) + this.minZoom;
};
Zoomer.prototype.getSliderPos = function(zoom) {
if (!(this.minZoom && this.maxZoom)) {
return null;
}
if (this.minZoom === this.maxZoom) {
return 0;
} else {
return (zoom - this.minZoom) / (this.maxZoom - this.minZoom);
}
};
Zoomer.prototype.isZoomable = function() {
if (!(this.minZoom && this.maxZoom)) {
return null;
}
return this.minZoom !== this.maxZoom;
};
Zoomer.prototype.fixZoom = function(zoom) {
if (zoom < this.minZoom) {
return this.minZoom;
}
if (zoom > this.maxZoom) {
return this.maxZoom;
}
return zoom;
};
return Zoomer;
}();
var Cropit;
Cropit = function() {
Cropit._DEFAULTS = {
exportZoom: 1,
imageBackground: false,
imageBackgroundBorderWidth: 0,
imageState: null,
allowCrossOrigin: false,
allowDragNDrop: true,
freeMove: false,
minZoom: "fill"
};
Cropit.PREVIEW_EVENTS = function() {
return [ "mousedown", "mouseup", "mouseleave", "touchstart", "touchend", "touchcancel", "touchleave" ].map(function(type) {
return "" + type + ".cropit";
}).join(" ");
}();
Cropit.PREVIEW_MOVE_EVENTS = "mousemove.cropit touchmove.cropit";
Cropit.ZOOM_INPUT_EVENTS = function() {
return [ "mousemove", "touchmove", "change" ].map(function(type) {
return "" + type + ".cropit";
}).join(" ");
}();
function Cropit(element, options) {
var dynamicDefaults;
this.element = element;
this.$el = $(this.element);
dynamicDefaults = {
$fileInput: this.$("input.cropit-image-input"),
$preview: this.$(".cropit-image-preview"),
$zoomSlider: this.$("input.cropit-image-zoom-input"),
$previewContainer: this.$(".cropit-image-preview-container")
};
this.options = $.extend({}, Cropit._DEFAULTS, dynamicDefaults, options);
this.init();
}
Cropit.prototype.init = function() {
var $previewContainer, _ref, _ref1, _ref2;
this.image = new Image();
if (this.options.allowCrossOrigin) {
this.image.crossOrigin = "Anonymous";
}
this.$fileInput = this.options.$fileInput.attr({
accept: "image/*"
});
this.$preview = this.options.$preview.css({
backgroundRepeat: "no-repeat"
});
this.$zoomSlider = this.options.$zoomSlider.attr({
min: 0,
max: 1,
step: .01
});
this.previewSize = {
w: this.options.width || this.$preview.width(),
h: this.options.height || this.$preview.height()
};
if (this.options.width) {
this.$preview.width(this.previewSize.w);
}
if (this.options.height) {
this.$preview.height(this.previewSize.h);
}
if (this.options.imageBackground) {
if ($.isArray(this.options.imageBackgroundBorderWidth)) {
this.imageBgBorderWidthArray = this.options.imageBackgroundBorderWidth;
} else {
this.imageBgBorderWidthArray = [];
[ 0, 1, 2, 3 ].forEach(function(_this) {
return function(i) {
return _this.imageBgBorderWidthArray[i] = _this.options.imageBackgroundBorderWidth;
};
}(this));
}
$previewContainer = this.options.$previewContainer;
this.$imageBg = $("<img />").addClass("cropit-image-background").attr("alt", "").css("position", "absolute");
this.$imageBgContainer = $("<div />").addClass("cropit-image-background-container").css({
position: "absolute",
zIndex: 0,
left: -this.imageBgBorderWidthArray[3] + window.parseInt(this.$preview.css("border-left-width")),
top: -this.imageBgBorderWidthArray[0] + window.parseInt(this.$preview.css("border-top-width")),
width: this.previewSize.w + this.imageBgBorderWidthArray[1] + this.imageBgBorderWidthArray[3],
height: this.previewSize.h + this.imageBgBorderWidthArray[0] + this.imageBgBorderWidthArray[2]
}).append(this.$imageBg);
if (this.imageBgBorderWidthArray[0] > 0) {
this.$imageBgContainer.css({
overflow: "hidden"
});
}
$previewContainer.css("position", "relative").prepend(this.$imageBgContainer);
this.$preview.css("position", "relative");
this.$preview.hover(function(_this) {
return function() {
return _this.$imageBg.addClass("cropit-preview-hovered");
};
}(this), function(_this) {
return function() {
return _this.$imageBg.removeClass("cropit-preview-hovered");
};
}(this));
}
this.initialOffset = {
x: 0,
y: 0
};
this.initialZoom = 0;
this.initialZoomSliderPos = 0;
this.imageLoaded = false;
this.moveContinue = false;
this.zoomer = new Zoomer();
if (this.options.allowDragNDrop) {
jQuery.event.props.push("dataTransfer");
}
this.bindListeners();
this.$zoomSlider.val(this.initialZoomSliderPos);
this.setOffset(((_ref = this.options.imageState) != null ? _ref.offset : void 0) || this.initialOffset);
this.zoom = ((_ref1 = this.options.imageState) != null ? _ref1.zoom : void 0) || this.initialZoom;
return this.loadImage(((_ref2 = this.options.imageState) != null ? _ref2.src : void 0) || null);
};
Cropit.prototype.bindListeners = function() {
this.$fileInput.on("change.cropit", this.onFileChange.bind(this));
this.$preview.on(Cropit.PREVIEW_EVENTS, this.onPreviewEvent.bind(this));
this.$zoomSlider.on(Cropit.ZOOM_INPUT_EVENTS, this.onZoomSliderChange.bind(this));
if (this.options.allowDragNDrop) {
this.$preview.on("dragover.cropit dragleave.cropit", this.onDragOver.bind(this));
return this.$preview.on("drop.cropit", this.onDrop.bind(this));
}
};
Cropit.prototype.unbindListeners = function() {
this.$fileInput.off("change.cropit");
this.$preview.off(Cropit.PREVIEW_EVENTS);
this.$preview.off("dragover.cropit dragleave.cropit drop.cropit");
return this.$zoomSlider.off(Cropit.ZOOM_INPUT_EVENTS);
};
Cropit.prototype.reset = function() {
this.zoom = this.initialZoom;
return this.offset = this.initialOffset;
};
Cropit.prototype.onFileChange = function() {
var _base;
if (typeof (_base = this.options).onFileChange === "function") {
_base.onFileChange();
}
return this.loadFileReader(this.$fileInput.get(0).files[0]);
};
Cropit.prototype.loadFileReader = function(file) {
var fileReader;
fileReader = new FileReader();
if (file != null ? file.type.match("image") : void 0) {
this.setImageLoadingClass();
fileReader.readAsDataURL(file);
fileReader.onload = this.onFileReaderLoaded.bind(this);
return fileReader.onerror = this.onFileReaderError.bind(this);
} else if (file != null) {
return this.onFileReaderError();
}
};
Cropit.prototype.onFileReaderLoaded = function(e) {
this.reset();
return this.loadImage(e.target.result);
};
Cropit.prototype.onFileReaderError = function() {
var _base;
return typeof (_base = this.options).onFileReaderError === "function" ? _base.onFileReaderError() : void 0;
};
Cropit.prototype.onDragOver = function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
return this.$preview.toggleClass("cropit-drag-hovered", e.type === "dragover");
};
Cropit.prototype.onDrop = function(e) {
var files;
e.preventDefault();
e.stopPropagation();
files = Array.prototype.slice.call(e.dataTransfer.files, 0);
files.some(function(_this) {
return function(file) {
if (file.type.match("image")) {
_this.loadFileReader(file);
return true;
}
};
}(this));
return this.$preview.removeClass("cropit-drag-hovered");
};
Cropit.prototype.loadImage = function(imageSrc) {
var _base;
this.imageSrc = imageSrc;
if (!this.imageSrc) {
return;
}
if (typeof (_base = this.options).onImageLoading === "function") {
_base.onImageLoading();
}
this.setImageLoadingClass();
this.image.onload = this.onImageLoaded.bind(this);
this.image.onerror = this.onImageError.bind(this);
return this.image.src = this.imageSrc;
};
Cropit.prototype.onImageLoaded = function() {
var _base;
this.setImageLoadedClass();
this.setOffset(this.offset);
this.$preview.css("background-image", "url(" + this.imageSrc + ")");
if (this.options.imageBackground) {
this.$imageBg.attr("src", this.imageSrc);
}
this.imageSize = {
w: this.image.width,
h: this.image.height
};
this.setupZoomer();
this.imageLoaded = true;
return typeof (_base = this.options).onImageLoaded === "function" ? _base.onImageLoaded() : void 0;
};
Cropit.prototype.onImageError = function() {
var _base;
return typeof (_base = this.options).onImageError === "function" ? _base.onImageError() : void 0;
};
Cropit.prototype.setImageLoadingClass = function() {
return this.$preview.removeClass("cropit-image-loaded").addClass("cropit-image-loading");
};
Cropit.prototype.setImageLoadedClass = function() {
return this.$preview.removeClass("cropit-image-loading").addClass("cropit-image-loaded");
};
Cropit.prototype.getEventPosition = function(e) {
var _ref, _ref1, _ref2, _ref3;
if ((_ref = e.originalEvent) != null ? (_ref1 = _ref.touches) != null ? _ref1[0] : void 0 : void 0) {
e = (_ref2 = e.originalEvent) != null ? (_ref3 = _ref2.touches) != null ? _ref3[0] : void 0 : void 0;
}
if (e.clientX && e.clientY) {
return {
x: e.clientX,
y: e.clientY
};
}
};
Cropit.prototype.onPreviewEvent = function(e) {
if (!this.imageLoaded) {
return;
}
this.moveContinue = false;
this.$preview.off(Cropit.PREVIEW_MOVE_EVENTS);
if (e.type === "mousedown" || e.type === "touchstart") {
this.origin = this.getEventPosition(e);
this.moveContinue = true;
this.$preview.on(Cropit.PREVIEW_MOVE_EVENTS, this.onMove.bind(this));
} else {
$(document.body).focus();
}
e.stopPropagation();
return false;
};
Cropit.prototype.onMove = function(e) {
var eventPosition;
eventPosition = this.getEventPosition(e);
if (this.moveContinue && eventPosition) {
this.setOffset({
x: this.offset.x + eventPosition.x - this.origin.x,
y: this.offset.y + eventPosition.y - this.origin.y
});
}
this.origin = eventPosition;
e.stopPropagation();
return false;
};
Cropit.prototype.setOffset = function(position) {
this.offset = this.fixOffset(position);
this.$preview.css("background-position", "" + this.offset.x + "px " + this.offset.y + "px");
if (this.options.imageBackground) {
return this.$imageBg.css({
left: this.offset.x + this.imageBgBorderWidthArray[3],
top: this.offset.y + this.imageBgBorderWidthArray[0]
});
}
};
Cropit.prototype.fixOffset = function(offset) {
var ret;
if (!this.imageLoaded) {
return offset;
}
ret = {
x: offset.x,
y: offset.y
};
if (!this.options.freeMove) {
if (this.imageSize.w * this.zoom >= this.previewSize.w) {
ret.x = Math.min(0, Math.max(ret.x, this.previewSize.w - this.imageSize.w * this.zoom));
} else {
ret.x = Math.max(0, Math.min(ret.x, this.previewSize.w - this.imageSize.w * this.zoom));
}
if (this.imageSize.h * this.zoom >= this.previewSize.h) {
ret.y = Math.min(0, Math.max(ret.y, this.previewSize.h - this.imageSize.h * this.zoom));
} else {
ret.y = Math.max(0, Math.min(ret.y, this.previewSize.h - this.imageSize.h * this.zoom));
}
}
ret.x = this.round(ret.x);
ret.y = this.round(ret.y);
return ret;
};
Cropit.prototype.onZoomSliderChange = function() {
var newZoom;
if (!this.imageLoaded) {
return;
}
this.zoomSliderPos = Number(this.$zoomSlider.val());
newZoom = this.zoomer.getZoom(this.zoomSliderPos);
return this.setZoom(newZoom);
};
Cropit.prototype.enableZoomSlider = function() {
var _base;
this.$zoomSlider.removeAttr("disabled");
return typeof (_base = this.options).onZoomEnabled === "function" ? _base.onZoomEnabled() : void 0;
};
Cropit.prototype.disableZoomSlider = function() {
var _base;
this.$zoomSlider.attr("disabled", true);
return typeof (_base = this.options).onZoomDisabled === "function" ? _base.onZoomDisabled() : void 0;
};
Cropit.prototype.setupZoomer = function() {
this.zoomer.setup(this.imageSize, this.previewSize, this.options.exportZoom, this.options);
this.zoom = this.fixZoom(this.zoom);
this.setZoom(this.zoom);
if (this.isZoomable()) {
return this.enableZoomSlider();
} else {
return this.disableZoomSlider();
}
};
Cropit.prototype.setZoom = function(newZoom) {
var newX, newY, oldZoom, updatedHeight, updatedWidth;
newZoom = this.fixZoom(newZoom);
updatedWidth = this.round(this.imageSize.w * newZoom);
updatedHeight = this.round(this.imageSize.h * newZoom);
oldZoom = this.zoom;
newX = this.previewSize.w / 2 - (this.previewSize.w / 2 - this.offset.x) * newZoom / oldZoom;
newY = this.previewSize.h / 2 - (this.previewSize.h / 2 - this.offset.y) * newZoom / oldZoom;
this.zoom = newZoom;
this.setOffset({
x: newX,
y: newY
});
this.zoomSliderPos = this.zoomer.getSliderPos(this.zoom);
this.$zoomSlider.val(this.zoomSliderPos);
this.$preview.css("background-size", "" + updatedWidth + "px " + updatedHeight + "px");
if (this.options.imageBackground) {
return this.$imageBg.css({
width: updatedWidth,
height: updatedHeight
});
}
};
Cropit.prototype.fixZoom = function(zoom) {
return this.zoomer.fixZoom(zoom);
};
Cropit.prototype.isZoomable = function() {
return this.zoomer.isZoomable();
};
Cropit.prototype.getCroppedImageData = function(exportOptions) {
var canvas, canvasContext, croppedSize, exportDefaults, exportZoom;
if (!this.imageSrc) {
return null;
}
exportDefaults = {
type: "image/png",
quality: .75,
originalSize: false,
fillBg: "#fff"
};
exportOptions = $.extend({}, exportDefaults, exportOptions);
croppedSize = {
w: this.previewSize.w,
h: this.previewSize.h
};
exportZoom = exportOptions.originalSize ? 1 / this.zoom : this.options.exportZoom;
canvas = $("<canvas />").attr({
width: croppedSize.w * exportZoom,
height: croppedSize.h * exportZoom
}).get(0);
canvasContext = canvas.getContext("2d");
if (exportOptions.type === "image/jpeg") {
canvasContext.fillStyle = exportOptions.fillBg;
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
}
canvasContext.drawImage(this.image, this.offset.x * exportZoom, this.offset.y * exportZoom, this.zoom * exportZoom * this.imageSize.w, this.zoom * exportZoom * this.imageSize.h);
return canvas.toDataURL(exportOptions.type, exportOptions.quality);
};
Cropit.prototype.getImageState = function() {
return {
src: this.imageSrc,
offset: this.offset,
zoom: this.zoom
};
};
Cropit.prototype.getImageSrc = function() {
return this.imageSrc;
};
Cropit.prototype.getOffset = function() {
return this.offset;
};
Cropit.prototype.getZoom = function() {
return this.zoom;
};
Cropit.prototype.getImageSize = function() {
if (!this.imageSize) {
return null;
}
return {
width: this.imageSize.w,
height: this.imageSize.h
};
};
Cropit.prototype.getPreviewSize = function() {
return {
width: this.previewSize.w,
height: this.previewSize.h
};
};
Cropit.prototype.setPreviewSize = function(size) {
if (!((size != null ? size.width : void 0) > 0 && (size != null ? size.height : void 0) > 0)) {
return;
}
this.previewSize = {
w: size.width,
h: size.height
};
this.$preview.css({
width: this.previewSize.w,
height: this.previewSize.h
});
if (this.options.imageBackground) {
this.$imageBgContainer.css({
width: this.previewSize.w + this.imageBgBorderWidthArray[1] + this.imageBgBorderWidthArray[3],
height: this.previewSize.h + this.imageBgBorderWidthArray[0] + this.imageBgBorderWidthArray[2]
});
}
if (this.imageLoaded) {
return this.setupZoomer();
}
};
Cropit.prototype.disable = function() {
this.unbindListeners();
this.disableZoomSlider();
return this.$el.addClass("cropit-disabled");
};
Cropit.prototype.reenable = function() {
this.bindListeners();
this.enableZoomSlider();
return this.$el.removeClass("cropit-disabled");
};
Cropit.prototype.round = function(x) {
return +(Math.round(x * 100) + "e-2");
};
Cropit.prototype.$ = function(selector) {
if (!this.$el) {
return null;
}
return this.$el.find(selector);
};
return Cropit;
}();
var dataKey, methods;
dataKey = "cropit";
methods = {
init: function(options) {
return this.each(function() {
var cropit;
if (!$.data(this, dataKey)) {
cropit = new Cropit(this, options);
return $.data(this, dataKey, cropit);
}
});
},
destroy: function() {
return this.each(function() {
return $.removeData(this, dataKey);
});
},
isZoomable: function() {
var cropit;
cropit = this.first().data(dataKey);
return cropit != null ? cropit.isZoomable() : void 0;
},
"export": function(options) {
var cropit;
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getCroppedImageData(options) : void 0;
},
imageState: function() {
var cropit;
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getImageState() : void 0;
},
imageSrc: function(newImageSrc) {
var cropit;
if (newImageSrc != null) {
return this.each(function() {
var cropit;
cropit = $.data(this, dataKey);
if (cropit != null) {
cropit.reset();
}
return cropit != null ? cropit.loadImage(newImageSrc) : void 0;
});
} else {
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getImageSrc() : void 0;
}
},
offset: function(newOffset) {
var cropit;
if (newOffset != null && newOffset.x != null && newOffset.y != null) {
return this.each(function() {
var cropit;
cropit = $.data(this, dataKey);
return cropit != null ? cropit.setOffset(newOffset) : void 0;
});
} else {
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getOffset() : void 0;
}
},
zoom: function(newZoom) {
var cropit;
if (newZoom != null) {
return this.each(function() {
var cropit;
cropit = $.data(this, dataKey);
return cropit != null ? cropit.setZoom(newZoom) : void 0;
});
} else {
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getZoom() : void 0;
}
},
imageSize: function() {
var cropit;
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getImageSize() : void 0;
},
previewSize: function(newSize) {
var cropit;
if (newSize != null) {
return this.each(function() {
var cropit;
cropit = $.data(this, dataKey);
return cropit != null ? cropit.setPreviewSize(newSize) : void 0;
});
} else {
cropit = this.first().data(dataKey);
return cropit != null ? cropit.getPreviewSize() : void 0;
}
},
disable: function() {
return this.each(function() {
var cropit;
cropit = $.data(this, dataKey);
return cropit.disable();
});
},
reenable: function() {
return this.each(function() {
var cropit;
cropit = $.data(this, dataKey);
return cropit.reenable();
});
}
};
$.fn.cropit = function(method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else {
return methods.init.apply(this, arguments);
}
};
})(window.jQuery); | {
"content_hash": "51ef9a99dca5dd2cfc158c5236bf33dd",
"timestamp": "",
"source": "github",
"line_count": 637,
"max_line_length": 190,
"avg_line_length": 42.54945054945055,
"alnum_prop": 0.48734504132231404,
"repo_name": "Baishakhidelgence/testzend",
"id": "eb13777c1e2c917c0cfd7b5f835203e742d13052",
"size": "27104",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "public/files/hmPhotoSfpContest/js/jquery.cropit.js",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "74538"
},
{
"name": "CSS",
"bytes": "3493120"
},
{
"name": "HTML",
"bytes": "2711807"
},
{
"name": "JavaScript",
"bytes": "11465134"
},
{
"name": "PHP",
"bytes": "10958222"
}
],
"symlink_target": ""
} |
import datetime
from os import path
import urllib
import numpy as np
import ocw.data_source.local as local
import ocw.dataset_processor as dsp
import ocw.evaluation as evaluation
import ocw.metrics as metrics
import ocw.plotter as plotter
# File URL leader
FILE_LEADER = "http://zipper.jpl.nasa.gov/dist/"
# Two Local Model Files
FILE_1 = "AFRICA_KNMI-RACMO2.2b_CTL_ERAINT_MM_50km_1989-2008_tasmax.nc"
FILE_2 = "AFRICA_UC-WRF311_CTL_ERAINT_MM_50km-rg_1989-2008_tasmax.nc"
# Filename for the output image/plot (without file extension)
OUTPUT_PLOT = "wrf_bias_compared_to_knmi"
FILE_1_PATH = path.join('/tmp', FILE_1)
FILE_2_PATH = path.join('/tmp', FILE_2)
if not path.exists(FILE_1_PATH):
urllib.urlretrieve(FILE_LEADER + FILE_1, FILE_1_PATH)
if not path.exists(FILE_2_PATH):
urllib.urlretrieve(FILE_LEADER + FILE_2, FILE_2_PATH)
""" Step 1: Load Local NetCDF Files into OCW Dataset Objects """
print("Loading %s into an OCW Dataset Object" % (FILE_1_PATH,))
knmi_dataset = local.load_file(FILE_1_PATH, "tasmax")
print("KNMI_Dataset.values shape: (times, lats, lons) - %s \n" %
(knmi_dataset.values.shape,))
print("Loading %s into an OCW Dataset Object" % (FILE_2_PATH,))
wrf_dataset = local.load_file(FILE_2_PATH, "tasmax")
print("WRF_Dataset.values shape: (times, lats, lons) - %s \n" %
(wrf_dataset.values.shape,))
""" Step 2: Temporally Rebin the Data into an Annual Timestep """
print("Temporally Rebinning the Datasets to an Annual Timestep")
knmi_dataset = dsp.temporal_rebin(knmi_dataset, temporal_resolution='annual')
wrf_dataset = dsp.temporal_rebin(wrf_dataset, temporal_resolution='annual')
print("KNMI_Dataset.values shape: %s" % (knmi_dataset.values.shape,))
print("WRF_Dataset.values shape: %s \n\n" % (wrf_dataset.values.shape,))
""" Step 3: Spatially Regrid the Dataset Objects to a 1 degree grid """
# The spatial_boundaries() function returns the spatial extent of the dataset
print("The KNMI_Dataset spatial bounds (min_lat, max_lat, min_lon, max_lon) are: \n"
"%s\n" % (knmi_dataset.spatial_boundaries(), ))
print("The KNMI_Dataset spatial resolution (lat_resolution, lon_resolution) is: \n"
"%s\n\n" % (knmi_dataset.spatial_resolution(), ))
min_lat, max_lat, min_lon, max_lon = knmi_dataset.spatial_boundaries()
# Using the bounds we will create a new set of lats and lons on 1 degree step
new_lons = np.arange(min_lon, max_lon, 1)
new_lats = np.arange(min_lat, max_lat, 1)
# Spatially regrid datasets using the new_lats, new_lons numpy arrays
print("Spatially Regridding the KNMI_Dataset...")
knmi_dataset = dsp.spatial_regrid(knmi_dataset, new_lats, new_lons)
print("Final shape of the KNMI_Dataset: \n"
"%s\n" % (knmi_dataset.values.shape, ))
print("Spatially Regridding the WRF_Dataset...")
wrf_dataset = dsp.spatial_regrid(wrf_dataset, new_lats, new_lons)
print("Final shape of the WRF_Dataset: \n"
"%s\n" % (wrf_dataset.values.shape, ))
""" Step 4: Build a Metric to use for Evaluation - Bias for this example """
# You can build your own metrics, but OCW also ships with some common metrics
print("Setting up a Bias metric to use for evaluation")
bias = metrics.Bias()
""" Step 5: Create an Evaluation Object using Datasets and our Metric """
# The Evaluation Class Signature is:
# Evaluation(reference, targets, metrics, subregions=None)
# Evaluation can take in multiple targets and metrics, so we need to convert
# our examples into Python lists. Evaluation will iterate over the lists
print("Making the Evaluation definition")
bias_evaluation = evaluation.Evaluation(knmi_dataset, [wrf_dataset], [bias])
print("Executing the Evaluation using the object's run() method")
bias_evaluation.run()
""" Step 6: Make a Plot from the Evaluation.results """
# The Evaluation.results are a set of nested lists to support many different
# possible Evaluation scenarios.
#
# The Evaluation results docs say:
# The shape of results is (num_metrics, num_target_datasets) if no subregion
# Accessing the actual results when we have used 1 metric and 1 dataset is
# done this way:
print("Accessing the Results of the Evaluation run")
results = bias_evaluation.results[0][0]
print("The results are of type: %s" % type(results))
# From the bias output I want to make a Contour Map of the region
print("Generating a contour map using ocw.plotter.draw_contour_map()")
lats = new_lats
lons = new_lons
fname = OUTPUT_PLOT
gridshape = (4, 5) # 20 Years worth of plots. 20 rows in 1 column
plot_title = "TASMAX Bias of WRF Compared to KNMI (1989 - 2008)"
sub_titles = range(1989, 2009, 1)
plotter.draw_contour_map(results, lats, lons, fname,
gridshape=gridshape, ptitle=plot_title,
subtitles=sub_titles)
| {
"content_hash": "1a7ef6cf1d3fbcaba00b3fa17f2a22a9",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 84,
"avg_line_length": 43.37614678899082,
"alnum_prop": 0.7235617597292724,
"repo_name": "jarifibrahim/climate",
"id": "ffa5cda9173abef6e170b651a5382583e45b4d5b",
"size": "5515",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/simple_model_to_model_bias.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "2587"
},
{
"name": "HTML",
"bytes": "38243"
},
{
"name": "JavaScript",
"bytes": "124509"
},
{
"name": "OpenEdge ABL",
"bytes": "14713"
},
{
"name": "Python",
"bytes": "901332"
},
{
"name": "Ruby",
"bytes": "537"
},
{
"name": "Shell",
"bytes": "4808"
}
],
"symlink_target": ""
} |
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>thymeleaf</groupId>
<artifactId>thymeleaf-notes</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>Thymeleaf Notes</name>
<description>XML/XHTML/HTML5 template engine for Java</description>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>yang</id>
<name>Yang Dongdong</name>
<email>ydd1226@126.com</email>
<roles>
<role>developer</role>
</roles>
<timezone>+8</timezone>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<thymeleaf.version>2.1.4.RELEASE</thymeleaf.version>
</properties>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.html</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<descriptors>
<descriptor>src/assembly/sources.xml</descriptor>
</descriptors>
<appendAssemblyId>true</appendAssemblyId>
<finalName>${project.artifactId}-${project.version}</finalName>
</configuration>
<executions>
<execution>
<id>make-assembly-dist</id>
<phase>package</phase>
<goals>
<goal>attached</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- http://www.eclipse.org/jetty/documentation/current/jetty-maven-plugin.html -->
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.6.v20151106</version>
<configuration>
<webApp>
<contextPath>/thymeleaf-notes</contextPath>
</webApp>
<!-- mvn jetty:run -->
<httpConnector>
<port>8080</port>
<idleTimeout>60000</idleTimeout>
</httpConnector>
<!-- The pause in seconds between sweeps of the webapp to check for
changes and automatically hot redeploy if any are detected. -->
<scanIntervalSeconds>2</scanIntervalSeconds>
<reload>manual</reload>
<!-- mvn jetty:stop -->
<stopKey>exit</stopKey>
<stopPort>9090</stopPort>
<!-- request log -->
<requestLog implementation="org.eclipse.jetty.server.NCSARequestLog">
<filename>target/access-yyyy_mm_dd.log</filename>
<filenameDateFormat>yyyy-MM-dd</filenameDateFormat>
<logDateFormat>yyyy-MM-dd HH:mm:ss</logDateFormat>
<logTimeZone>GMT+8:00</logTimeZone>
<retainDays>90</retainDays>
<append>true</append>
</requestLog>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${thymeleaf.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
| {
"content_hash": "d6e2220ff368f7ec95847b4c16723f3d",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 104,
"avg_line_length": 28.26875,
"alnum_prop": 0.6652664160955118,
"repo_name": "yddgit/thymeleaf-notes",
"id": "e989c89286a9de9ba6a4820752ca36e0c088b184",
"size": "4523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1658"
},
{
"name": "HTML",
"bytes": "42660"
},
{
"name": "Java",
"bytes": "5859"
}
],
"symlink_target": ""
} |
```
npm install
npm start
```
Navigate to localhost:3000
| {
"content_hash": "26f574c3cd8c395a7a39d0a77a965eb9",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 26,
"avg_line_length": 11.4,
"alnum_prop": 0.7192982456140351,
"repo_name": "SwordSoul/testpage",
"id": "cc4c6d685a80962f95eb89acc9238413398eb84b",
"size": "67",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1732"
},
{
"name": "HTML",
"bytes": "239"
},
{
"name": "JavaScript",
"bytes": "6932"
}
],
"symlink_target": ""
} |
(function () {
return {
events: {
'app.activated': 'showDefect'
},
requests: {
getStory: function (type, id) {
return {
url: this.setting('baseURL') + '/rest-1.v1/Data/' + type + "?Accept=application/json&sel=Number,Name,Status,Team,AssetState,Timebox,AssetState,Scope,ChangeDate,CreateDate,Custom_ClientSeverity&where=Number='" + id + "'",
type: 'GET',
dataType: 'json',
headers: { 'Authorization': "Bearer " + this.setting('apiToken') },
proxy_v2: true
};
},
updateTicket: function (data) {
return {
url: '/api/v2/tickets/' + this.ticket().id() + '.json',
type: 'PUT',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
proxy_v2: true
};
},
},
showDefect: function () {
this.hideFields();
var v1Number = this.ticket().customField('custom_field_' + this.setting('defectFeild') + '');
var type = null;
if (!v1Number) {
// do nothing!
} else if (v1Number.indexOf('D-') > -1) {
type = "Defect";
} else if (v1Number.indexOf('B-') > -1) {
type = "Story";
}
if (!type) {
this.switchTo('defect-info', {});
} else {
this.ajax("getStory", type, v1Number)
.then(function (resp) {
var userStory = resp.Assets[0].Attributes;
var translatedUS = this.translateValues(userStory);
this.updateTicketWithV1(translatedUS);
this.switchTo('defect-info', { userStory: translatedUS });
});
}
},
//function to hide feilds from ticket view
hideFields: function () {
var fields = this.getStoryFields();
for (var index in fields) {
if (this.ticketFields('custom_field_' + fields[index] + '')) {
this.ticketFields('custom_field_' + fields[index] + '').hide();
}
}
},
getStoryFields: function () {
return [this.settings.statusFeild, this.settings.releaseFeild, this.settings.clientSeverity];
},
// function to update fields on ticket
updateTicketWithV1: function (userStory) {
var updateInfo = {
ticket: {
custom_fields: []
}
};
var fields = this.getStoryFields();
for (var index in fields) {
var tempObj = { id: fields[index] };
if (index < 1) {
tempObj.value = userStory['Status.Name'].value;
updateInfo.ticket.custom_fields.push(tempObj);
}
if (index == 1) {
tempObj.value = userStory['Timebox.Name'].value;
updateInfo.ticket.custom_fields.push(tempObj);
}
if (index == 2) {
tempObj.value = userStory['Custom_ClientSeverity.Name'].value;
updateInfo.ticket.custom_fields.push(tempObj);
}
}
if(updateInfo.ticket.custom_fields.length>0){
this.ajax('updateTicket', updateInfo).done(function (data) {
});
}
},
// function to translate values for V1 and apply proper CSS.
translateValues: function (userStory) {
var assetKeys = {
0: 'Future',
64: 'Active',
128: 'Closed',
200: 'Template(Dead)',
208: 'Broken Down(Dead)',
255: 'Deleted(Dead)'
};
var statusKeys = {
'In Progress': 'pending',
'Defined': 'pending',
'Queued': 'pending',
'Invistigating': 'pending',
};
if (userStory['Custom_ClientSeverity.Name'].value == 3) {
userStory.sevCss = 'open';
}
if (userStory['Custom_ClientSeverity.Name'].value == 2) {
userStory.sevCss = 'new';
}
if (userStory['Custom_ClientSeverity.Name'].value == 1) {
userStory.sevCss = 'pending';
}
if (!userStory['Status.Name'].value) {
userStory['Status.Name'].value = "Queued";
}
userStory.css = statusKeys[userStory['Status.Name'].value];
if (!userStory.css) {
userStory.css = 'new';
}
userStory.AssetState.value = assetKeys[userStory.AssetState.value];
if (userStory.AssetState.value == 'Closed' && userStory['Status.Name'].value != "Declined") {
userStory.css = 'Open';
userStory['Status.Name'].value = 'Released';
}
return userStory;
}
};
} ());
| {
"content_hash": "38e2e616c2f1459f0272dc65c751ed93",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 240,
"avg_line_length": 37.30612244897959,
"alnum_prop": 0.43854850474106494,
"repo_name": "mzelmanovich/Zendesk-VersionOne-Defect-App",
"id": "1ef2c4ef7c12b9e1313e606d8a6890fa4436e6b2",
"size": "5484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5484"
}
],
"symlink_target": ""
} |
/*************************************************************************/
/* world_2d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/*************************************************************************/
#include "world_2d.h"
#include "servers/visual_server.h"
#include "servers/physics_2d_server.h"
#include "servers/spatial_sound_2d_server.h"
#include "globals.h"
#include "scene/2d/visibility_notifier_2d.h"
#include "scene/main/viewport.h"
#include "scene/2d/camera_2d.h"
#include "globals.h"
struct SpatialIndexer2D {
struct CellRef {
int ref;
_FORCE_INLINE_ int inc() {
ref++;
return ref;
}
_FORCE_INLINE_ int dec() {
ref--;
return ref;
}
_FORCE_INLINE_ CellRef() {
ref=0;
}
};
struct CellKey {
union {
struct {
int32_t x;
int32_t y;
};
uint64_t key;
};
bool operator==(const CellKey& p_key) const { return key==p_key.key; }
_FORCE_INLINE_ bool operator<(const CellKey& p_key) const {
return key < p_key.key;
}
};
struct CellData {
Map<VisibilityNotifier2D*,CellRef> notifiers;
};
Map<CellKey,CellData> cells;
int cell_size;
Map<VisibilityNotifier2D*,Rect2> notifiers;
struct ViewportData {
Map<VisibilityNotifier2D*,uint64_t> notifiers;
Rect2 rect;
};
Map<Viewport*,ViewportData> viewports;
bool changed;
uint64_t pass;
void _notifier_update_cells(VisibilityNotifier2D *p_notifier,const Rect2& p_rect,bool p_add) {
Point2i begin = p_rect.pos;
begin/=cell_size;
Point2i end = p_rect.pos+p_rect.size;
end/=cell_size;
for(int i=begin.x;i<=end.x;i++) {
for(int j=begin.y;j<=end.y;j++) {
CellKey ck;
ck.x=i;
ck.y=j;
Map<CellKey,CellData>::Element *E=cells.find(ck);
if (p_add) {
if (!E)
E=cells.insert(ck,CellData());
E->get().notifiers[p_notifier].inc();
} else {
ERR_CONTINUE(!E);
if (E->get().notifiers[p_notifier].dec()==0) {
E->get().notifiers.erase(p_notifier);
if (E->get().notifiers.empty()) {
cells.erase(E);
}
}
}
}
}
}
void _notifier_add(VisibilityNotifier2D* p_notifier,const Rect2& p_rect) {
ERR_FAIL_COND(notifiers.has(p_notifier));
notifiers[p_notifier]=p_rect;
_notifier_update_cells(p_notifier,p_rect,true);
changed=true;
}
void _notifier_update(VisibilityNotifier2D* p_notifier,const Rect2& p_rect) {
Map<VisibilityNotifier2D*,Rect2>::Element *E=notifiers.find(p_notifier);
ERR_FAIL_COND(!E);
if (E->get()==p_rect)
return;
_notifier_update_cells(p_notifier,p_rect,true);
_notifier_update_cells(p_notifier,E->get(),false);
E->get()=p_rect;
changed=true;
}
void _notifier_remove(VisibilityNotifier2D* p_notifier) {
Map<VisibilityNotifier2D*,Rect2>::Element *E=notifiers.find(p_notifier);
ERR_FAIL_COND(!E);
_notifier_update_cells(p_notifier,E->get(),false);
notifiers.erase(p_notifier);
List<Viewport*> removed;
for (Map<Viewport*,ViewportData>::Element*F=viewports.front();F;F=F->next()) {
Map<VisibilityNotifier2D*,uint64_t>::Element*G=F->get().notifiers.find(p_notifier);
if (G) {
F->get().notifiers.erase(G);
removed.push_back(F->key());
}
}
while(!removed.empty()) {
p_notifier->_exit_viewport(removed.front()->get());
removed.pop_front();
}
changed=true;
}
void _add_viewport(Viewport* p_viewport,const Rect2& p_rect) {
ERR_FAIL_COND(viewports.has(p_viewport));
ViewportData vd;
vd.rect=p_rect;
viewports[p_viewport]=vd;
changed=true;
}
void _update_viewport(Viewport* p_viewport, const Rect2& p_rect) {
Map<Viewport*,ViewportData>::Element *E= viewports.find(p_viewport);
ERR_FAIL_COND(!E);
if (E->get().rect==p_rect)
return;
E->get().rect=p_rect;
changed=true;
}
void _remove_viewport(Viewport* p_viewport) {
ERR_FAIL_COND(!viewports.has(p_viewport));
List<VisibilityNotifier2D*> removed;
for(Map<VisibilityNotifier2D*,uint64_t>::Element *E=viewports[p_viewport].notifiers.front();E;E=E->next()) {
removed.push_back(E->key());
}
while(!removed.empty()) {
removed.front()->get()->_exit_viewport(p_viewport);
removed.pop_front();
}
viewports.erase(p_viewport);
}
void _update() {
if (!changed)
return;
for (Map<Viewport*,ViewportData>::Element *E=viewports.front();E;E=E->next()) {
Point2i begin = E->get().rect.pos;
begin/=cell_size;
Point2i end = E->get().rect.pos+E->get().rect.size;
end/=cell_size;
pass++;
List<VisibilityNotifier2D*> added;
List<VisibilityNotifier2D*> removed;
for(int i=begin.x;i<=end.x;i++) {
for(int j=begin.y;j<=end.y;j++) {
CellKey ck;
ck.x=i;
ck.y=j;
Map<CellKey,CellData>::Element *F=cells.find(ck);
if (!F) {
continue;
}
//notifiers in cell
for (Map<VisibilityNotifier2D*,CellRef>::Element *G=F->get().notifiers.front();G;G=G->next()) {
Map<VisibilityNotifier2D*,uint64_t>::Element *H=E->get().notifiers.find(G->key());
if (!H) {
H=E->get().notifiers.insert(G->key(),pass);
added.push_back(G->key());
} else {
H->get()=pass;
}
}
}
}
for (Map<VisibilityNotifier2D*,uint64_t>::Element *F=E->get().notifiers.front();F;F=F->next()) {
if (F->get()!=pass)
removed.push_back(F->key());
}
while(!added.empty()) {
added.front()->get()->_enter_viewport(E->key());
added.pop_front();
}
while(!removed.empty()) {
E->get().notifiers.erase(removed.front()->get());
removed.front()->get()->_exit_viewport(E->key());
removed.pop_front();
}
}
changed=false;
}
SpatialIndexer2D() {
pass=0;
changed=false;
cell_size=100; //should be configurable with GLOBAL_DEF("") i guess
}
};
void World2D::_register_viewport(Viewport* p_viewport,const Rect2& p_rect) {
indexer->_add_viewport(p_viewport,p_rect);
}
void World2D::_update_viewport(Viewport* p_viewport,const Rect2& p_rect){
indexer->_update_viewport(p_viewport,p_rect);
}
void World2D::_remove_viewport(Viewport* p_viewport){
indexer->_remove_viewport(p_viewport);
}
void World2D::_register_notifier(VisibilityNotifier2D* p_notifier, const Rect2 &p_rect){
indexer->_notifier_add(p_notifier,p_rect);
}
void World2D::_update_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect){
indexer->_notifier_update(p_notifier,p_rect);
}
void World2D::_remove_notifier(VisibilityNotifier2D* p_notifier){
indexer->_notifier_remove(p_notifier);
}
void World2D::_update() {
indexer->_update();
}
RID World2D::get_canvas() {
return canvas;
}
RID World2D::get_space() {
return space;
}
RID World2D::get_sound_space() {
return sound_space;
}
void World2D::_bind_methods() {
ObjectTypeDB::bind_method(_MD("get_canvas"),&World2D::get_canvas);
ObjectTypeDB::bind_method(_MD("get_space"),&World2D::get_space);
ObjectTypeDB::bind_method(_MD("get_sound_space"),&World2D::get_sound_space);
ObjectTypeDB::bind_method(_MD("get_direct_space_state:Physics2DDirectSpaceState"),&World2D::get_direct_space_state);
}
Physics2DDirectSpaceState *World2D::get_direct_space_state() {
return Physics2DServer::get_singleton()->space_get_direct_state(space);
}
World2D::World2D() {
canvas = VisualServer::get_singleton()->canvas_create();
space = Physics2DServer::get_singleton()->space_create();
sound_space = SpatialSound2DServer::get_singleton()->space_create();
//set space2D to be more friendly with pixels than meters, by adjusting some constants
Physics2DServer::get_singleton()->space_set_active(space,true);
Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY,GLOBAL_DEF("physics_2d/default_gravity",98));
Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,GLOBAL_DEF("physics_2d/default_gravity_vector",Vector2(0,1)));
Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_LINEAR_DAMP,GLOBAL_DEF("physics_2d/default_density",0.1));
Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_ANGULAR_DAMP,GLOBAL_DEF("physics_2d/default_angular_damp",1));
Physics2DServer::get_singleton()->space_set_param(space,Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS,1.0);
Physics2DServer::get_singleton()->space_set_param(space,Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION,1.5);
Physics2DServer::get_singleton()->space_set_param(space,Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION,0.3);
Physics2DServer::get_singleton()->space_set_param(space,Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD,2);
Physics2DServer::get_singleton()->space_set_param(space,Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS,0.2);
indexer = memnew( SpatialIndexer2D );
}
World2D::~World2D() {
VisualServer::get_singleton()->free(canvas);
Physics2DServer::get_singleton()->free(space);
SpatialSound2DServer::get_singleton()->free(sound_space);
memdelete(indexer);
}
| {
"content_hash": "cfcf1e6c069fb69574d909c6e1946aa1",
"timestamp": "",
"source": "github",
"line_count": 395,
"max_line_length": 161,
"avg_line_length": 27.48860759493671,
"alnum_prop": 0.6260821514090993,
"repo_name": "blackwc/godot",
"id": "3b1f1d23461a8a4ee931cf5ee9d67438a883c522",
"size": "10858",
"binary": false,
"copies": "7",
"ref": "refs/heads/dev",
"path": "scene/resources/world_2d.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "6955"
},
{
"name": "Assembly",
"bytes": "384031"
},
{
"name": "Batchfile",
"bytes": "2488"
},
{
"name": "C",
"bytes": "20880841"
},
{
"name": "C++",
"bytes": "13284202"
},
{
"name": "DIGITAL Command Language",
"bytes": "95419"
},
{
"name": "GAP",
"bytes": "3350"
},
{
"name": "GDScript",
"bytes": "86258"
},
{
"name": "GLSL",
"bytes": "56765"
},
{
"name": "HTML",
"bytes": "9365"
},
{
"name": "Java",
"bytes": "651868"
},
{
"name": "JavaScript",
"bytes": "5802"
},
{
"name": "Matlab",
"bytes": "2076"
},
{
"name": "Objective-C",
"bytes": "40272"
},
{
"name": "Objective-C++",
"bytes": "135003"
},
{
"name": "PHP",
"bytes": "1095905"
},
{
"name": "Perl",
"bytes": "1930126"
},
{
"name": "Python",
"bytes": "120885"
},
{
"name": "Shell",
"bytes": "1054"
},
{
"name": "XS",
"bytes": "4319"
},
{
"name": "eC",
"bytes": "3710"
}
],
"symlink_target": ""
} |
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.NodejsTools.Profiling
{
/// <summary>
/// Works around an issue w/ DialogWindow and targetting multiple versions of VS.
///
/// Because the Microsoft.VisualStudio.Shell.version.0 assembly changes names
/// we cannot refer to both v10 and v11 versions from within the same XAML file.
/// Instead we use this subclass defined in our assembly.
/// </summary>
public class DialogWindowVersioningWorkaround : DialogWindow
{
}
}
| {
"content_hash": "b62b854e322ae3ab44979079230a8fb2",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 85,
"avg_line_length": 32.9375,
"alnum_prop": 0.713472485768501,
"repo_name": "lukedgr/nodejstools",
"id": "1f895b69b3753e96989021b277d84b98896abf87",
"size": "689",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Nodejs/Product/Profiling/DialogWindowVersioningWorkaround.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "112"
},
{
"name": "Batchfile",
"bytes": "4018"
},
{
"name": "C#",
"bytes": "5436690"
},
{
"name": "CSS",
"bytes": "504"
},
{
"name": "HTML",
"bytes": "7741"
},
{
"name": "JavaScript",
"bytes": "75807"
},
{
"name": "PowerShell",
"bytes": "9002"
},
{
"name": "Python",
"bytes": "2458"
},
{
"name": "TypeScript",
"bytes": "8313"
},
{
"name": "Vue",
"bytes": "1791"
}
],
"symlink_target": ""
} |
import React, { PropTypes, Component } from 'react';
import Radio from './Radio';
import css from './Radio.css';
/*
* Example usage:
* <RadioGroup name="example"
* onChange={this.handleRadio}
* selectedValue={this.state.radioVal}>
* {radio => (
* <span>
* {radio({value: 'Apple'})}
* <br/>
* {radio({value: 'Orange'})}
* <br/>
* {radio({value: 'Banana'})}
* </span>
* )}
* </RadioGroup>
*/
export default class RadioGroup extends Component {
render() {
const {
className,
onChange,
children,
selectedValue,
name,
} = this.props;
return (
<div className={[css.group, className].join(' ')}>
{children && children(props =>
<Radio
name={name}
onChange={onChange}
selectedValue={selectedValue}
{...props}
/>
)}
</div>
);
}
}
RadioGroup.propTypes = {
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
children: PropTypes.func.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
className: PropTypes.string,
giant: PropTypes.bool,
selectedValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
| {
"content_hash": "cf26f8b6d7dbf80f00f82192ea30415e",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 75,
"avg_line_length": 23.125,
"alnum_prop": 0.5667953667953668,
"repo_name": "tomgatzgates/loggins",
"id": "52c85ce48614b5277893393d7a66c5d8aff2b89e",
"size": "1295",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "components/RadioGroup/RadioGroup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "45295"
},
{
"name": "HTML",
"bytes": "343"
},
{
"name": "JavaScript",
"bytes": "105480"
}
],
"symlink_target": ""
} |
package com.auth0.android.provider;
import android.support.annotation.NonNull;
import android.util.Base64;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
class AlgorithmHelper {
private static final String TAG = AlgorithmHelper.class.getSimpleName();
private static final String US_ASCII = "US-ASCII";
private static final String SHA_256 = "SHA-256";
private String getBase64String(byte[] source) {
return Base64.encodeToString(source, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
}
byte[] getASCIIBytes(String value) {
byte[] input;
try {
input = value.getBytes(US_ASCII);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Could not convert string to an ASCII byte array", e);
throw new IllegalStateException("Could not convert string to an ASCII byte array", e);
}
return input;
}
byte[] getSHA256(byte[] input) {
byte[] signature;
try {
MessageDigest md = MessageDigest.getInstance(SHA_256);
md.update(input, 0, input.length);
signature = md.digest();
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "Failed to get SHA-256 signature", e);
throw new IllegalStateException("Failed to get SHA-256 signature", e);
}
return signature;
}
String generateCodeVerifier() {
SecureRandom sr = new SecureRandom();
byte[] code = new byte[32];
sr.nextBytes(code);
return Base64.encodeToString(code, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
}
String generateCodeChallenge(@NonNull String codeVerifier) {
byte[] input = getASCIIBytes(codeVerifier);
byte[] signature = getSHA256(input);
return getBase64String(signature);
}
}
| {
"content_hash": "c364e20fe5faa56127f5207797c037d8",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 99,
"avg_line_length": 33.66101694915254,
"alnum_prop": 0.6560926485397784,
"repo_name": "thirteen23/Auth0.Android",
"id": "b468ebf4fa91596a4bc7e9f3a62009f593101739",
"size": "1986",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "auth0/src/main/java/com/auth0/android/provider/AlgorithmHelper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "578560"
}
],
"symlink_target": ""
} |
"""Compatibility tests for dulwich repositories."""
from cStringIO import StringIO
import itertools
import os
from dulwich.objects import (
hex_to_sha,
)
from dulwich.repo import (
check_ref_format,
)
from dulwich.tests.utils import (
tear_down_repo,
)
from dulwich.tests.compat.utils import (
run_git_or_fail,
import_repo,
CompatTestCase,
)
class ObjectStoreTestCase(CompatTestCase):
"""Tests for git repository compatibility."""
def setUp(self):
super(ObjectStoreTestCase, self).setUp()
self._repo = import_repo('server_new.export')
self.addCleanup(tear_down_repo, self._repo)
def _run_git(self, args):
return run_git_or_fail(args, cwd=self._repo.path)
def _parse_refs(self, output):
refs = {}
for line in StringIO(output):
fields = line.rstrip('\n').split(' ')
self.assertEqual(3, len(fields))
refname, type_name, sha = fields
check_ref_format(refname[5:])
hex_to_sha(sha)
refs[refname] = (type_name, sha)
return refs
def _parse_objects(self, output):
return set(s.rstrip('\n').split(' ')[0] for s in StringIO(output))
def test_bare(self):
self.assertTrue(self._repo.bare)
self.assertFalse(os.path.exists(os.path.join(self._repo.path, '.git')))
def test_head(self):
output = self._run_git(['rev-parse', 'HEAD'])
head_sha = output.rstrip('\n')
hex_to_sha(head_sha)
self.assertEqual(head_sha, self._repo.refs['HEAD'])
def test_refs(self):
output = self._run_git(
['for-each-ref', '--format=%(refname) %(objecttype) %(objectname)'])
expected_refs = self._parse_refs(output)
actual_refs = {}
for refname, sha in self._repo.refs.as_dict().iteritems():
if refname == 'HEAD':
continue # handled in test_head
obj = self._repo[sha]
self.assertEqual(sha, obj.id)
actual_refs[refname] = (obj.type_name, obj.id)
self.assertEqual(expected_refs, actual_refs)
# TODO(dborowitz): peeled ref tests
def _get_loose_shas(self):
output = self._run_git(['rev-list', '--all', '--objects', '--unpacked'])
return self._parse_objects(output)
def _get_all_shas(self):
output = self._run_git(['rev-list', '--all', '--objects'])
return self._parse_objects(output)
def assertShasMatch(self, expected_shas, actual_shas_iter):
actual_shas = set()
for sha in actual_shas_iter:
obj = self._repo[sha]
self.assertEqual(sha, obj.id)
actual_shas.add(sha)
self.assertEqual(expected_shas, actual_shas)
def test_loose_objects(self):
# TODO(dborowitz): This is currently not very useful since fast-imported
# repos only contained packed objects.
expected_shas = self._get_loose_shas()
self.assertShasMatch(expected_shas,
self._repo.object_store._iter_loose_objects())
def test_packed_objects(self):
expected_shas = self._get_all_shas() - self._get_loose_shas()
self.assertShasMatch(expected_shas,
itertools.chain(*self._repo.object_store.packs))
def test_all_objects(self):
expected_shas = self._get_all_shas()
self.assertShasMatch(expected_shas, iter(self._repo.object_store))
| {
"content_hash": "350b5d42790cbda7f5514567d65e565d",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 80,
"avg_line_length": 32.764150943396224,
"alnum_prop": 0.5974661675784624,
"repo_name": "johndbritton/gitviz",
"id": "ceebf51408dcaba26a530869242efc3e76d0c28f",
"size": "4274",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dulwich/dulwich/tests/compat/test_repository.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1916"
},
{
"name": "Batchfile",
"bytes": "3268"
},
{
"name": "C",
"bytes": "48666"
},
{
"name": "CSS",
"bytes": "5054"
},
{
"name": "Groff",
"bytes": "82"
},
{
"name": "HTML",
"bytes": "4369"
},
{
"name": "Handlebars",
"bytes": "2883"
},
{
"name": "JavaScript",
"bytes": "168931"
},
{
"name": "Makefile",
"bytes": "8587"
},
{
"name": "PHP",
"bytes": "4954"
},
{
"name": "Python",
"bytes": "1603823"
},
{
"name": "Shell",
"bytes": "1455"
}
],
"symlink_target": ""
} |
package org.uddi.api_v2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for discoveryURL complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="discoveryURL">
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="useType" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "discoveryURL", propOrder = {
"value"
})
public class DiscoveryURL {
@XmlValue
protected String value;
@XmlAttribute(name = "useType", required = true)
protected String useType;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the useType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUseType() {
return useType;
}
/**
* Sets the value of the useType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUseType(String value) {
this.useType = value;
}
}
| {
"content_hash": "31a24412421d4a18d1f814888004df73",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 103,
"avg_line_length": 23.022988505747126,
"alnum_prop": 0.5616575137294059,
"repo_name": "apache/juddi",
"id": "1841aed0dd76cea6c1c454ee2c498af7dae10a5b",
"size": "2644",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "uddi-ws/src/main/java/org/uddi/api_v2/DiscoveryURL.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29697"
},
{
"name": "C#",
"bytes": "1911429"
},
{
"name": "CSS",
"bytes": "5931"
},
{
"name": "HTML",
"bytes": "41415"
},
{
"name": "Java",
"bytes": "9127186"
},
{
"name": "JavaScript",
"bytes": "212687"
},
{
"name": "Shell",
"bytes": "24241"
}
],
"symlink_target": ""
} |
<?php
namespace spec\Sylius\Bundle\AddressingBundle\Model;
use Doctrine\Common\Collections\Collection;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\AddressingBundle\Model\ProvinceInterface;
/**
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
class CountrySpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Sylius\Bundle\AddressingBundle\Model\Country');
}
function it_implements_Sylius_country_interface()
{
$this->shouldImplement('Sylius\Bundle\AddressingBundle\Model\CountryInterface');
}
function it_has_no_id_by_default()
{
$this->getId()->shouldReturn(null);
}
function it_has_no_name_by_default()
{
$this->getName()->shouldReturn(null);
}
function its_name_is_mutable()
{
$this->setName('United States');
$this->getName()->shouldReturn('United States');
}
function it_has_no_iso_name_by_default()
{
$this->getIsoName()->shouldReturn(null);
}
function its_iso_name_is_mutable()
{
$this->setIsoName('MX');
$this->getIsoName()->shouldReturn('MX');
}
function it_initializes_provinces_collection_by_default()
{
$this->getProvinces()->shouldHaveType('Doctrine\Common\Collections\Collection');
}
function it_has_no_provinces_by_default()
{
$this->hasProvinces()->shouldReturn(false);
}
function its_provinces_are_mutable(Collection $provinces)
{
$this->setProvinces($provinces);
$this->getProvinces()->shouldReturn($provinces);
}
function it_adds_province(ProvinceInterface $province)
{
$this->addProvince($province);
$this->hasProvince($province)->shouldReturn(true);
}
function it_removes_province(ProvinceInterface $province)
{
$this->addProvince($province);
$this->hasProvince($province)->shouldReturn(true);
$this->removeProvince($province);
$this->hasProvince($province)->shouldReturn(false);
}
function it_sets_country_on_added_province(ProvinceInterface $province)
{
$province->setCountry($this)->shouldBeCalled();
$this->addProvince($province);
}
function it_unsets_country_on_removed_province(ProvinceInterface $province)
{
$this->addProvince($province);
$this->hasProvince($province)->shouldReturn(true);
$province->setCountry(null)->shouldBeCalled();
$this->removeProvince($province);
}
function it_has_fluent_interface(
ProvinceInterface $province,
Collection $provinces
)
{
$this->setName('Poland')->shouldReturn($this);
$this->setIsoName('PL')->shouldReturn($this);
$this->setProvinces($provinces)->shouldReturn($this);
$this->addProvince($province)->shouldReturn($this);
$this->removeProvince($province)->shouldReturn($this);
}
}
| {
"content_hash": "027b374f206e25fa0b35602387af0685",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 88,
"avg_line_length": 26.168141592920353,
"alnum_prop": 0.6435576597903281,
"repo_name": "chuandadexiaoyu/UniversitySylius",
"id": "938cfdfac3e67b085b849730b18b13849a12ab93",
"size": "3170",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Sylius/Bundle/AddressingBundle (copy)/spec/Sylius/Bundle/AddressingBundle/Model/CountrySpec.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "146950"
},
{
"name": "JavaScript",
"bytes": "209221"
},
{
"name": "PHP",
"bytes": "2371236"
},
{
"name": "Perl",
"bytes": "519"
},
{
"name": "Puppet",
"bytes": "2943"
},
{
"name": "Ruby",
"bytes": "907"
},
{
"name": "Shell",
"bytes": "642"
}
],
"symlink_target": ""
} |
import logging
from urllib.parse import urljoin, urlencode
from werkzeug.local import LocalProxy
from werkzeug.middleware.profiler import ProfilerMiddleware
from flask import Flask, request
from flask import url_for as flask_url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_cors import CORS
from flask_babel import Babel
from flask_talisman import Talisman
from followthemoney import set_model_locale
from elasticsearch import Elasticsearch, TransportError
from servicelayer.cache import get_redis
from servicelayer.archive import init_archive
from servicelayer.extensions import get_extensions
from servicelayer.util import service_retries, backoff
from servicelayer.logs import configure_logging, LOG_FORMAT_JSON
from servicelayer import settings as sls
from aleph import settings
from aleph.cache import Cache
from aleph.oauth import configure_oauth
from aleph.util import LoggingTransport
NONE = "'none'"
log = logging.getLogger(__name__)
db = SQLAlchemy()
migrate = Migrate()
mail = Mail()
babel = Babel()
talisman = Talisman()
def create_app(config={}):
configure_logging(level=logging.DEBUG)
app = Flask("aleph")
app.config.from_object(settings)
app.config.update(config)
if "postgres" not in settings.DATABASE_URI:
raise RuntimeError("aleph database must be PostgreSQL!")
app.config.update(
{
"SQLALCHEMY_DATABASE_URI": settings.DATABASE_URI,
"FLASK_SKIP_DOTENV": True,
"FLASK_DEBUG": settings.DEBUG,
"BABEL_DOMAIN": "aleph",
"PROFILE": settings.PROFILE,
}
)
if settings.PROFILE:
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
migrate.init_app(app, db, directory=settings.ALEMBIC_DIR)
configure_oauth(app, cache=get_cache())
mail.init_app(app)
db.init_app(app)
babel.init_app(app)
CORS(
app,
resources=r"/api/*",
origins=settings.CORS_ORIGINS,
supports_credentials=True,
)
feature_policy = {
"accelerometer": NONE,
"camera": NONE,
"geolocation": NONE,
"gyroscope": NONE,
"magnetometer": NONE,
"microphone": NONE,
"payment": NONE,
"usb": NONE,
}
talisman.init_app(
app,
force_https=settings.FORCE_HTTPS,
strict_transport_security=settings.FORCE_HTTPS,
feature_policy=feature_policy,
content_security_policy=settings.CONTENT_POLICY,
)
from aleph.views import mount_app_blueprints
mount_app_blueprints(app)
# This executes all registered init-time plugins so that other
# applications can register their behaviour.
for plugin in get_extensions("aleph.init"):
plugin(app=app)
return app
@babel.localeselector
def determine_locale():
try:
options = settings.UI_LANGUAGES
locale = request.accept_languages.best_match(options)
locale = locale or str(babel.default_locale)
except RuntimeError:
locale = str(babel.default_locale)
set_model_locale(locale)
return locale
@migrate.configure
def configure_alembic(config):
config.set_main_option("sqlalchemy.url", settings.DATABASE_URI)
return config
def get_es():
url = settings.ELASTICSEARCH_URL
timeout = settings.ELASTICSEARCH_TIMEOUT
for attempt in service_retries():
try:
if not hasattr(settings, "_es_instance"):
# When logging structured logs, use a custom transport to log
# all es queries and their response time
if sls.LOG_FORMAT == LOG_FORMAT_JSON:
es = Elasticsearch(
url, transport_class=LoggingTransport, timeout=timeout
)
else:
es = Elasticsearch(url, timeout=timeout)
es.info()
settings._es_instance = es
return settings._es_instance
except TransportError as exc:
log.exception("ElasticSearch error: %s", exc.error)
backoff(failures=attempt)
raise RuntimeError("Could not connect to ElasticSearch")
def get_archive():
if not hasattr(settings, "_archive"):
settings._archive = init_archive()
return settings._archive
def get_cache():
if not hasattr(settings, "_cache") or settings._cache is None:
settings._cache = Cache(get_redis(), prefix=settings.APP_NAME)
return settings._cache
es = LocalProxy(get_es)
kv = LocalProxy(get_redis)
cache = LocalProxy(get_cache)
archive = LocalProxy(get_archive)
def url_for(*a, **kw):
"""Overwrite Flask url_for to force external paths."""
try:
kw["_external"] = False
query = kw.pop("_query", None)
relative = kw.pop("_relative", False)
path = flask_url_for(*a, **kw)
return url_external(path, query, relative=relative)
except RuntimeError:
return None
def url_external(path, query, relative=False):
"""Generate external URLs with HTTPS (if configured)."""
if query is not None:
path = "%s?%s" % (path, urlencode(query))
if relative:
return path
return urljoin(settings.APP_UI_URL, path)
| {
"content_hash": "c8151fa690aabbe1bb4dca07d01c608d",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 78,
"avg_line_length": 29.847457627118644,
"alnum_prop": 0.6596630702252508,
"repo_name": "pudo/aleph",
"id": "ade523cbc86005cab4548b4a687a0722132fa21d",
"size": "5283",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/pip/develop/jsonschema-4.1.2",
"path": "aleph/core.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15949"
},
{
"name": "HTML",
"bytes": "170476"
},
{
"name": "JavaScript",
"bytes": "111287"
},
{
"name": "Makefile",
"bytes": "1319"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "492593"
}
],
"symlink_target": ""
} |
package dk.statsbiblioteket.medieplatform.ticketsystem;
import dk.statsbiblioteket.medieplatform.ticketsystem.authorization.AuthorizationRequest;
import dk.statsbiblioteket.medieplatform.ticketsystem.authorization.AuthorizationResponse;
import dk.statsbiblioteket.medieplatform.ticketsystem.authorization.UserAttribute;
import javax.ws.rs.core.MediaType;
import org.apache.cxf.jaxrs.client.WebClient;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Authorization handles calling the license-Module webservice to determine which resources are allowed for the user
*/
public class Authorization {
private String service;
/**
* Create a new authorization client
* @param service the address of the license module webservice rest interface - http://devel06:9612/licensemodule/services/
*/
public Authorization(String service) {
this.service = service;
}
/**
* Get the list, hopefully a real subset of the resources, that the user is allowed to access
* @param resources the list of UUIDs that we want to examine
* @param userAttributes the user attributes
* @param type the type of the resources
* @return a List of UUIDs that the user is allowed to see
*/
public List<String> authorizeUser(Map<String, List<String>> userAttributes,
String type,
List<String> resources){
AuthorizationRequest authorizationRequest = new AuthorizationRequest(resources, type, transform(userAttributes));
WebClient client = WebClient.create(service);
AuthorizationResponse authorizationResponse = client.path("/checkAccessForIds")
.type(MediaType.TEXT_XML)
.post(authorizationRequest, AuthorizationResponse.class);
return authorizationResponse.getResources();
}
/**
* Transform the user attributes
* @param userAttributes the user attributes
* @return the user attributes
*/
private List<UserAttribute> transform(Map<String, List<String>> userAttributes) {
ArrayList<UserAttribute> result = new ArrayList<UserAttribute>();
for (Map.Entry<String, List<String>> entry : userAttributes.entrySet()) {
result.add(new UserAttribute(entry.getKey(), entry.getValue()));
}
return result;
}
}
| {
"content_hash": "3ddb974e5c4a1c32b9940e3b85967e75",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 127,
"avg_line_length": 36.43939393939394,
"alnum_prop": 0.7010395010395011,
"repo_name": "statsbiblioteket/ticket-system",
"id": "591eb2e81f91868b5d0c1859bb0eb8f9f8a7efc4",
"size": "2405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ticket-system-libs/src/main/java/dk/statsbiblioteket/medieplatform/ticketsystem/Authorization.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "31076"
}
],
"symlink_target": ""
} |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/cast_mirroring_service_host.h"
#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_enums.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model_observer.h"
#include "chrome/browser/ui/tabs/tab_utils.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/mirroring/mojom/cast_message_channel.mojom.h"
#include "components/mirroring/mojom/session_observer.mojom.h"
#include "components/mirroring/mojom/session_parameters.mojom.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "media/capture/mojom/video_capture.mojom.h"
#include "media/capture/mojom/video_capture_buffer.mojom.h"
#include "media/capture/mojom/video_capture_types.mojom.h"
#include "media/capture/video_capture_types.h"
#include "media/mojo/mojom/audio_data_pipe.mojom.h"
#include "media/mojo/mojom/audio_input_stream.mojom.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::_;
using testing::InvokeWithoutArgs;
using testing::Return;
namespace mirroring {
namespace {
media::VideoCaptureParams DefaultVideoCaptureParams() {
constexpr gfx::Size kMaxCaptureSize = gfx::Size(320, 320);
constexpr int kMaxFramesPerSecond = 60;
gfx::Size capture_size = kMaxCaptureSize;
media::VideoCaptureParams params;
params.requested_format = media::VideoCaptureFormat(
capture_size, kMaxFramesPerSecond, media::PIXEL_FORMAT_I420);
params.resolution_change_policy =
media::ResolutionChangePolicy::FIXED_ASPECT_RATIO;
return params;
}
content::DesktopMediaID BuildMediaIdForTabMirroring(
content::WebContents* target_web_contents) {
DCHECK(target_web_contents);
content::DesktopMediaID media_id;
content::RenderFrameHost* const main_frame =
target_web_contents->GetPrimaryMainFrame();
const int process_id = main_frame->GetProcess()->GetID();
const int frame_id = main_frame->GetRoutingID();
media_id.type = content::DesktopMediaID::TYPE_WEB_CONTENTS;
media_id.web_contents_id = content::WebContentsMediaCaptureId(
process_id, frame_id, true /* disable_local_echo */);
return media_id;
}
class MockVideoCaptureObserver final
: public media::mojom::VideoCaptureObserver {
public:
explicit MockVideoCaptureObserver(
mojo::PendingRemote<media::mojom::VideoCaptureHost> host)
: host_(std::move(host)) {}
MockVideoCaptureObserver(const MockVideoCaptureObserver&) = delete;
MockVideoCaptureObserver& operator=(const MockVideoCaptureObserver&) = delete;
MOCK_METHOD1(OnBufferCreatedCall, void(int buffer_id));
MOCK_METHOD1(OnBufferReadyCall, void(int buffer_id));
MOCK_METHOD1(OnBufferDestroyedCall, void(int buffer_id));
MOCK_METHOD1(OnStateChangedCall, void(media::mojom::VideoCaptureState state));
MOCK_METHOD1(OnVideoCaptureErrorCall, void(media::VideoCaptureError error));
// media::mojom::VideoCaptureObserver implementation.
void OnNewBuffer(int32_t buffer_id,
media::mojom::VideoBufferHandlePtr buffer_handle) override {
EXPECT_EQ(buffers_.find(buffer_id), buffers_.end());
EXPECT_EQ(frame_infos_.find(buffer_id), frame_infos_.end());
buffers_[buffer_id] = std::move(buffer_handle);
OnBufferCreatedCall(buffer_id);
}
void OnBufferReady(
media::mojom::ReadyBufferPtr buffer,
std::vector<media::mojom::ReadyBufferPtr> scaled_buffer) override {
EXPECT_TRUE(buffers_.find(buffer->buffer_id) != buffers_.end());
EXPECT_EQ(frame_infos_.find(buffer->buffer_id), frame_infos_.end());
frame_infos_[buffer->buffer_id] = std::move(buffer->info);
OnBufferReadyCall(buffer->buffer_id);
}
void OnBufferDestroyed(int32_t buffer_id) override {
// The consumer should have finished consuming the buffer before it is being
// destroyed.
EXPECT_TRUE(frame_infos_.find(buffer_id) == frame_infos_.end());
const auto iter = buffers_.find(buffer_id);
EXPECT_TRUE(iter != buffers_.end());
buffers_.erase(iter);
OnBufferDestroyedCall(buffer_id);
}
void OnNewCropVersion(uint32_t crop_version) override {}
void OnStateChanged(media::mojom::VideoCaptureResultPtr result) override {
if (result->which() == media::mojom::VideoCaptureResult::Tag::kState)
OnStateChangedCall(result->get_state());
else
OnVideoCaptureErrorCall(result->get_error_code());
}
void Start() {
host_->Start(device_id_, session_id_, DefaultVideoCaptureParams(),
receiver_.BindNewPipeAndPassRemote());
}
void Stop() { host_->Stop(device_id_); }
void RequestRefreshFrame() { host_->RequestRefreshFrame(device_id_); }
private:
mojo::Remote<media::mojom::VideoCaptureHost> host_;
mojo::Receiver<media::mojom::VideoCaptureObserver> receiver_{this};
base::flat_map<int, media::mojom::VideoBufferHandlePtr> buffers_;
base::flat_map<int, media::mojom::VideoFrameInfoPtr> frame_infos_;
const base::UnguessableToken device_id_ = base::UnguessableToken::Create();
const base::UnguessableToken session_id_ = base::UnguessableToken::Create();
};
} // namespace
class CastMirroringServiceHostBrowserTest
: public InProcessBrowserTest,
public mojom::SessionObserver,
public mojom::CastMessageChannel,
public mojom::AudioStreamCreatorClient {
public:
CastMirroringServiceHostBrowserTest() = default;
CastMirroringServiceHostBrowserTest(
const CastMirroringServiceHostBrowserTest&) = delete;
CastMirroringServiceHostBrowserTest& operator=(
const CastMirroringServiceHostBrowserTest&) = delete;
~CastMirroringServiceHostBrowserTest() override = default;
protected:
// Starts a tab mirroring session.
void StartTabMirroring() {
content::WebContents* web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
host_ = std::make_unique<CastMirroringServiceHost>(
BuildMediaIdForTabMirroring(web_contents));
mojo::PendingRemote<mojom::SessionObserver> observer;
observer_receiver_.Bind(observer.InitWithNewPipeAndPassReceiver());
mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel;
outbound_channel_receiver_.Bind(
outbound_channel.InitWithNewPipeAndPassReceiver());
host_->Start(mojom::SessionParameters::New(), std::move(observer),
std::move(outbound_channel),
inbound_channel_.BindNewPipeAndPassReceiver());
}
void GetVideoCaptureHost() {
mojo::PendingRemote<media::mojom::VideoCaptureHost> video_capture_host;
static_cast<mojom::ResourceProvider*>(host_.get())
->GetVideoCaptureHost(
video_capture_host.InitWithNewPipeAndPassReceiver());
video_frame_receiver_ = std::make_unique<MockVideoCaptureObserver>(
std::move(video_capture_host));
}
void StartVideoCapturing() {
base::RunLoop run_loop;
EXPECT_CALL(*video_frame_receiver_,
OnStateChangedCall(media::mojom::VideoCaptureState::STARTED))
.WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
video_frame_receiver_->Start();
run_loop.Run();
}
void StopMirroring() {
if (video_frame_receiver_) {
base::RunLoop run_loop;
EXPECT_CALL(*video_frame_receiver_,
OnStateChangedCall(media::mojom::VideoCaptureState::ENDED))
.WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
video_frame_receiver_->Stop();
run_loop.Run();
}
host_.reset();
}
void RequestRefreshFrame() {
base::RunLoop run_loop;
EXPECT_CALL(*video_frame_receiver_, OnBufferReadyCall(_))
.WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit))
.WillRepeatedly(Return());
video_frame_receiver_->RequestRefreshFrame();
run_loop.Run();
}
void CreateAudioLoopbackStream() {
constexpr int kTotalSegments = 1;
constexpr int kAudioTimebase = 48000;
media::AudioParameters params(media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
media::ChannelLayoutConfig::Stereo(),
kAudioTimebase, kAudioTimebase / 100);
base::RunLoop run_loop;
EXPECT_CALL(*this, OnAudioStreamCreated())
.WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
host_->CreateAudioStream(audio_client_receiver_.BindNewPipeAndPassRemote(),
params, kTotalSegments);
run_loop.Run();
}
// InProcessBrowserTest override.
void SetUp() override { InProcessBrowserTest::SetUp(); }
private:
// mojom::SessionObserver mocks.
MOCK_METHOD1(OnError, void(mojom::SessionError));
MOCK_METHOD0(DidStart, void());
MOCK_METHOD0(DidStop, void());
MOCK_METHOD1(LogInfoMessage, void(const std::string&));
MOCK_METHOD1(LogErrorMessage, void(const std::string&));
// mojom::CastMessageChannel mocks.
MOCK_METHOD1(Send, void(mojom::CastMessagePtr));
// mojom::AudioStreamCreatorClient mocks.
MOCK_METHOD0(OnAudioStreamCreated, void());
void StreamCreated(
mojo::PendingRemote<media::mojom::AudioInputStream> stream,
mojo::PendingReceiver<media::mojom::AudioInputStreamClient>
client_receiver,
media::mojom::ReadOnlyAudioDataPipePtr data_pipe) override {
EXPECT_TRUE(stream);
EXPECT_TRUE(client_receiver);
EXPECT_TRUE(data_pipe);
OnAudioStreamCreated();
}
mojo::Receiver<mojom::SessionObserver> observer_receiver_{this};
mojo::Receiver<mojom::CastMessageChannel> outbound_channel_receiver_{this};
mojo::Receiver<mojom::AudioStreamCreatorClient> audio_client_receiver_{this};
mojo::Remote<mojom::CastMessageChannel> inbound_channel_;
std::unique_ptr<CastMirroringServiceHost> host_;
std::unique_ptr<MockVideoCaptureObserver> video_frame_receiver_;
};
IN_PROC_BROWSER_TEST_F(CastMirroringServiceHostBrowserTest, CaptureTabVideo) {
StartTabMirroring();
GetVideoCaptureHost();
StartVideoCapturing();
RequestRefreshFrame();
StopMirroring();
}
IN_PROC_BROWSER_TEST_F(CastMirroringServiceHostBrowserTest, CaptureTabAudio) {
StartTabMirroring();
CreateAudioLoopbackStream();
StopMirroring();
}
IN_PROC_BROWSER_TEST_F(CastMirroringServiceHostBrowserTest, TabIndicator) {
content::WebContents* const contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_THAT(chrome::GetTabAlertStatesForContents(contents),
::testing::IsEmpty());
// A TabStripModelObserver that quits the MessageLoop whenever the
// UI's model is sent an event that might change the indicator status.
class IndicatorChangeObserver : public TabStripModelObserver {
public:
explicit IndicatorChangeObserver(Browser* browser) : browser_(browser) {
browser_->tab_strip_model()->AddObserver(this);
}
void TabChangedAt(content::WebContents* contents,
int index,
TabChangeType change_type) override {
std::move(on_tab_changed_).Run();
}
void WaitForTabChange() {
base::RunLoop run_loop;
on_tab_changed_ = run_loop.QuitClosure();
run_loop.Run();
}
private:
const raw_ptr<Browser> browser_;
base::OnceClosure on_tab_changed_;
};
IndicatorChangeObserver observer(browser());
ASSERT_THAT(chrome::GetTabAlertStatesForContents(contents),
::testing::IsEmpty());
StartTabMirroring();
// Run the browser until the indicator turns on.
const base::TimeTicks start_time = base::TimeTicks::Now();
while (!base::Contains(chrome::GetTabAlertStatesForContents(contents),
TabAlertState::TAB_CAPTURING)) {
if (base::TimeTicks::Now() - start_time >
TestTimeouts::action_max_timeout()) {
EXPECT_THAT(chrome::GetTabAlertStatesForContents(contents),
::testing::Contains(TabAlertState::TAB_CAPTURING));
return;
}
observer.WaitForTabChange();
}
StopMirroring();
}
} // namespace mirroring
| {
"content_hash": "76adf5519220c1fba8afd78ce2b785b0",
"timestamp": "",
"source": "github",
"line_count": 332,
"max_line_length": 80,
"avg_line_length": 37.99698795180723,
"alnum_prop": 0.7158937772493064,
"repo_name": "nwjs/chromium.src",
"id": "71db15c7e41716fd149e5a4867a4abbc79c29471",
"size": "12615",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw70",
"path": "chrome/browser/media/cast_mirroring_service_host_browsertest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
class BuildingsController < ApplicationController
active_scaffold do |conf|
end
end
| {
"content_hash": "57ff42c3c312b386e3bd042e0212643a",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 49,
"avg_line_length": 22,
"alnum_prop": 0.8068181818181818,
"repo_name": "System13Inc/active_scaffold",
"id": "1ee36c0ad0020a203c7c7fbf98ff4da793f462d8",
"size": "88",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/mock_app/app/controllers/buildings_controller.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System;
using MunicipalityTaxes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TaxingTests
{
[TestClass]
public class TaxScheduleApplicableTests
{
[TestMethod]
public void TestApplicable ()
{
var schedule = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Daily, begin: new DateTime(2017, 06, 02));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(1)));
schedule = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Weekly, begin: new DateTime(2017, 06, 05));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(-1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(2)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(3)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(4)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(5)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(6)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(7)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(1)));
schedule = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Monthly, begin: new DateTime(2017, 06, 01));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(-1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(1).AddDays(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(1)));
schedule = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Yearly, begin: new DateTime(2017, 01, 01));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(-1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddDays(1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddMonths(1).AddDays(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(-1)));
Assert.IsFalse(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(1)));
Assert.IsTrue(schedule.IsApplicable(schedule.ScheduleBeginDate.AddYears(1).AddDays(-1)));
}
[TestMethod]
public void TestMostApplicable ()
{
var daily = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Daily, begin: new DateTime(2017, 06, 05));
var weekly = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Weekly, begin: new DateTime(2017, 06, 05));
var monthly = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Monthly, begin: new DateTime(2017, 06, 01));
var yearly = new MunicipalityTaxSchedule(municipality: "Kaunas", frequency: ScheduleFrequency.Yearly, begin: new DateTime(2017, 01, 01));
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { yearly, monthly, weekly, daily }, new DateTime(2017, 06, 05)), daily);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { daily, weekly, monthly, yearly }, new DateTime(2017, 06, 05)), daily);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { yearly, monthly, weekly, daily }, new DateTime(2017, 06, 06)), weekly);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { monthly, weekly, daily, yearly }, new DateTime(2017, 06, 06)), weekly);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { yearly, monthly, weekly, daily }, new DateTime(2017, 06, 01)), monthly);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { monthly, yearly, daily, weekly }, new DateTime(2017, 06, 01)), monthly);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { yearly, monthly, weekly, daily }, new DateTime(2017, 04, 05)), yearly);
Assert.AreEqual(MunicipalityTaxSchedule.MostApplicable(new[] { weekly, daily, yearly, monthly }, new DateTime(2017, 04, 05)), yearly);
}
}
}
| {
"content_hash": "66d0763575b9b020c4cbee4fee282450",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 151,
"avg_line_length": 75.56410256410257,
"alnum_prop": 0.7164913471326773,
"repo_name": "keith-hall/Showcase_CSharp_MunicipalityTaxSchedule",
"id": "85daafc3ba6df9b5960e97395df476efbf32b23d",
"size": "5896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MunicipalityTaxes/TaxingTests/TaxScheduleApplicableTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "73933"
}
],
"symlink_target": ""
} |
//
// QBAlphabetView.m
// Demo
//
// Created by Qiaokai on 2017/2/28.
// Copyright © 2017年 Matías Martínez. All rights reserved.
//
#import "QBAlphabetView.h"
#import "UIButton+QBConvenient.h"
#import "QBKeyBoardButton.h"
@interface QBAlphabetView ()
@property (nonatomic, strong) NSArray *lettersArr;
@property (nonatomic, strong) NSArray *uppersArr;
/** 小写字母按钮 */
@property (nonatomic, strong) NSMutableArray *charBtnsArrM;
/** 其他按钮 */
@property (nonatomic, strong) NSMutableArray *tempArrM;
/** 其他按钮 切换大小写 */
@property (nonatomic, strong) UIButton *switchA;
/** 其他按钮 删除按钮 */
@property (nonatomic, strong) UIButton *deleteBtn;
/** 其他按钮 切换至数字键盘 */
@property (nonatomic, strong) UIButton *switchB;
/** 其他按钮 切换至符号按钮 */
@property (nonatomic, strong) UIButton *spaceBtn;
/** 其他按钮 登录 */
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, assign) BOOL isUpper;
@end
@implementation QBAlphabetView
- (NSArray *)lettersArr {
if (!_lettersArr) {
_lettersArr = @[@"q",@"w",@"e",@"r",@"t",@"y",@"u",@"i",@"o",@"p",@"a",@"s",@"d",@"f",@"g",@"h",@"j",@"k",@"l",@"z",@"x",@"c",@"v",@"b",@"n",@"m"];
}
return _lettersArr;
}
- (NSArray *)uppersArr {
if (!_uppersArr) {
_uppersArr = @[@"Q",@"W",@"E",@"R",@"T",@"Y",@"U",@"I",@"O",@"P",@"A",@"S",@"D",@"F",@"G",@"H",@"J",@"K",@"L",@"Z",@"X",@"C",@"V",@"B",@"N",@"M"];
}
return _uppersArr;
}
- (NSMutableArray *)charBtnsArrM {
if (!_charBtnsArrM) {
_charBtnsArrM = [NSMutableArray array];
}
return _charBtnsArrM;
}
- (NSMutableArray *)tempArrM {
if (!_tempArrM) {
_tempArrM = [NSMutableArray array];
}
return _tempArrM;
}
- (void)setIsShowTopAlert:(BOOL)isShowTopAlert {
if (_isShowTopAlert != isShowTopAlert) {
_isShowTopAlert = isShowTopAlert;
for (int i = 0; i < self.charBtnsArrM.count; i++) {
QBAlertKeyBoardButton *charBtn = self.charBtnsArrM[i];
charBtn.isShowTopAlert = isShowTopAlert;
}
}
}
- (void)setAllowsABC:(BOOL)allowsABC {
if (_allowsABC != allowsABC) {
_allowsABC = allowsABC;
self.switchB.tag = ButtonTypeNum;
[self.loginBtn setTitle:@"#+=" forState:UIControlStateNormal];
[self.loginBtn setBackgroundImage:[self.class _keyboardImageNamed:@"c_chaKeyboardBgButton"] forState:UIControlStateNormal];
[self.loginBtn setBackgroundImage:[self.class _keyboardImageNamed:@"c_chaKeyboardBgButton"] forState:UIControlStateHighlighted];
[self.loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
self.loginBtn.tag = ButtonTypeSymbol;
}
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = PWUIColorFromHex(0xf1f5f9);
self.isUpper = YES;
[self setupControls];
}
return self;
}
- (void)setupControls {
// 添加26个字母按钮
UIImage *image = [self.class _keyboardImageNamed:@"c_charKeyboardButton"];
image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:image.size.height * 0.5];
NSUInteger count = self.lettersArr.count;
for (NSUInteger i = 0 ; i < count; i++) {
QBAlertKeyBoardButton *charBtn = [QBAlertKeyBoardButton buttonWithType:UIButtonTypeCustom];
charBtn.titleLabel.font = [UIFont systemFontOfSize:20];
[charBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[charBtn setBackgroundImage:image forState:UIControlStateNormal];
[charBtn setBackgroundImage:image forState:UIControlStateHighlighted];
[charBtn addTarget:self action:@selector(charbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:charBtn];
[self.charBtnsArrM addObject:charBtn];
}
// 添加其他按钮 切换大小写、删除回退、确定(登录)、 数字、符号
self.switchA = [UIButton setupFunctionButtonWithTitle:nil image:[self.class _keyboardImageNamed:@"c_chaKeyboardShiftButton"] highImage:[self.class _keyboardImageNamed:@"c_chaKeyboardShiftButton"]];
[self.switchA setBackgroundImage:[self.class _keyboardImageNamed:@"c_chaKeyboardShiftButtonSel"] forState:UIControlStateSelected];
self.deleteBtn = [UIButton setupFunctionButtonWithTitle:nil image:[self.class _keyboardImageNamed:@"c_character_keyboardDeleteButton"] highImage:nil];
self.loginBtn = [UIButton setupFunctionButtonWithTitle:@"完成" image:[self.class _keyboardImageNamed:@"login_c_character_keyboardLoginButton"] highImage:[self.class _keyboardImageNamed:@"login_c_character_keyboardLoginButton"]];
[self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.switchB = [UIButton setupFunctionButtonWithTitle:@"123" image:[self.class _keyboardImageNamed:@"c_chaKeyboardBgButton"] highImage:[self.class _keyboardImageNamed:@"c_chaKeyboardBgButton"]];
self.spaceBtn = [UIButton setupFunctionButtonWithTitle:@" " image:[self.class _keyboardImageNamed:@"c_character_keyboardSwitchButton"] highImage:[self.class _keyboardImageNamed:@"c_character_keyboardSwitchButton"]];
[self.switchA addTarget:self action:@selector(changeCharacteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.deleteBtn addTarget:self action:@selector(functionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.loginBtn addTarget:self action:@selector(functionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.switchB addTarget:self action:@selector(functionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.spaceBtn addTarget:self action:@selector(charbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
self.deleteBtn.tag = ButtonTypeDelete;
self.loginBtn.tag = ButtonTypeDone;
self.switchB.tag = ButtonTypeNumandSymbol;
self.spaceBtn.tag = ButtonTypeSpace;
[self addSubview:self.switchA];
[self addSubview:self.deleteBtn];
[self addSubview:self.loginBtn];
[self addSubview:self.switchB];
[self addSubview:self.spaceBtn];
[self changeCharacteBtnClick:nil];
}
- (void)charbuttonClick:(UIButton *)charButton {
if ([self.delegate respondsToSelector:@selector(alphabetKeyboard:didClickButton:)]) {
[self.delegate alphabetKeyboard:self didClickButton:charButton];
}
}
- (void)changeCharacteBtnClick:(UIButton *)switchA {
switchA.selected = !switchA.isSelected;
[self.tempArrM removeAllObjects];
NSUInteger count = self.charBtnsArrM.count;
if (self.isUpper) {
self.tempArrM = [NSMutableArray arrayWithArray:self.lettersArr];
self.isUpper = NO;
} else {
self.tempArrM = [NSMutableArray arrayWithArray:self.uppersArr];
self.isUpper = YES;
}
for (int i = 0; i < count; i++) {
UIButton *charBtn = (UIButton *)self.charBtnsArrM[i];
NSString *upperTitle = self.tempArrM[i];
[charBtn setTitle:upperTitle forState:UIControlStateNormal];
[charBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
}
}
- (void)functionBtnClick:(UIButton *)switchBtn {
if (switchBtn.tag == ButtonTypeNum) {
if (self.isUpper) {
[self changeCharacteBtnClick:self.switchA];
}
}
if ([self.delegate respondsToSelector:@selector(alphabetKeyboardKeyboardDidClickButton:)]) {
[self.delegate alphabetKeyboardKeyboardDidClickButton:switchBtn];
}
}
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat topMargin = 5;
CGFloat bottomMargin = 5;
CGFloat leftMargin = 5;
CGFloat colMargin = 5;
CGFloat rowMargin = 10;
if (PW_IS_IPHONE_5) {
topMargin = 8;
bottomMargin = 8;
rowMargin = 15;
}
// 布局字母按钮
CGFloat buttonW = (CGRectGetWidth(self.bounds) - 2 * leftMargin - 9 * colMargin) / 10;
CGFloat buttonH = (CGRectGetHeight(self.bounds) - topMargin - bottomMargin - 3 * rowMargin) / 4;
NSUInteger count = self.charBtnsArrM.count;
for (NSUInteger i = 0; i < count; i++) {
UIButton *button = (UIButton *)self.charBtnsArrM[i];
CGRect buttonRect = button.frame;
buttonRect.size.width = buttonW;
buttonRect.size.height = buttonH;
if (i < 10) { // 第一行
buttonRect.origin.x = (colMargin + buttonW) * i + leftMargin;
buttonRect.origin.y = topMargin;
} else if (i < 19) { // 第二行
buttonRect.origin.x = (colMargin + buttonW) * (i - 10) + leftMargin + buttonW / 2 + colMargin/2;
buttonRect.origin.y = topMargin + rowMargin + buttonH;
} else if (i < count) {
buttonRect.origin.y = topMargin + 2 * rowMargin + 2 * buttonH;
buttonRect.origin.x = (colMargin + buttonW) * (i - 19) + leftMargin + buttonW / 2 + colMargin + buttonW + colMargin/2;
}
button.frame = buttonRect;
}
// 布局其他功能按钮 切换大小写、删除回退、确定(登录)、 数字、符号
CGFloat switchAW = buttonH;
CGFloat switchAY = topMargin + 2 * rowMargin + 2 * buttonH;
self.switchA.frame = CGRectMake(leftMargin, switchAY, switchAW, buttonH);
CGFloat deleteBtnW = buttonH;
self.deleteBtn.frame = CGRectMake(CGRectGetWidth(self.bounds) - leftMargin - deleteBtnW, switchAY, deleteBtnW, buttonH);
CGFloat loginBtnW = 2 * buttonW + colMargin;
CGFloat loginBtnY = CGRectGetHeight(self.bounds) - bottomMargin - buttonH;
CGFloat loginBtnX = CGRectGetWidth(self.bounds) - leftMargin - loginBtnW;
self.loginBtn.frame = CGRectMake(loginBtnX, loginBtnY, loginBtnW, buttonH);
CGFloat switchBtnW = buttonH;
self.switchB.frame = CGRectMake(leftMargin, loginBtnY, switchBtnW, buttonH);
CGFloat spaceBtnOffsetx = (CGRectGetWidth(self.bounds) - buttonH * 2 - leftMargin * 2 - 7 * buttonW - 6*colMargin) / 2;
CGFloat spaceBtnW = CGRectGetWidth(self.bounds) - (spaceBtnOffsetx * 2 + loginBtnW + leftMargin + leftMargin + switchBtnW);
self.spaceBtn.frame = CGRectMake(spaceBtnOffsetx + leftMargin + switchBtnW, loginBtnY, spaceBtnW, buttonH);
}
+ (UIImage *)_keyboardImageNamed:(NSString *)name
{
NSString *resource = [name stringByDeletingPathExtension];
NSString *extension = [name pathExtension];
extension = [extension isEqualToString:@""] ? @"png":extension;
if (resource) {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
// NSURL *url = [bundle URLForResource:@"QBPwdModule" withExtension:@"bundle"];
// bundle = [NSBundle bundleWithURL:url];
if (bundle) {
NSString *resourcePath = [bundle pathForResource:resource ofType:extension];
return [UIImage imageNamed:resourcePath];
} else {
return [UIImage imageNamed:name];
}
}
return nil;
}
@end
| {
"content_hash": "486278a06f916c3c37e90e7126a9fb35",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 230,
"avg_line_length": 38.825,
"alnum_prop": 0.6739950326556895,
"repo_name": "BlackBigWhite/QKKeyboard",
"id": "6e858383366a1a315856b0b3f392f0aed82bfd9b",
"size": "11148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "QBPwdModule/Classes/QBAlphabetView.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "667"
},
{
"name": "Makefile",
"bytes": "178454"
},
{
"name": "Objective-C",
"bytes": "87141"
},
{
"name": "Ruby",
"bytes": "739"
},
{
"name": "Shell",
"bytes": "9294"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Posts Tagged “regression” – Alexej Gossmann</title>
<meta charset="utf-8" />
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>
<meta name="description" content="PhD student with focus on statistics, machine learning, and programming, among other things">
<meta property="og:description" content="PhD student with focus on statistics, machine learning, and programming, among other things" />
<meta name="author" content="Alexej Gossmann" />
<meta property="og:title" content="Posts Tagged “regression”" />
<meta property="twitter:title" content="Posts Tagged “regression”" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="/style.css" />
<link rel="alternate" type="application/rss+xml" title="Alexej Gossmann - PhD student with focus on statistics, machine learning, and programming, among other things" href="/feed.xml" />
<!-- Created with Jekyll Now - http://github.com/barryclark/jekyll-now -->
<!-- MathJax integration and configuration-->
<!-- Use standard LaTeX delimiters and turn on equation numbering -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ["$","$"] ],
displayMath: [ ["$$","$$"] ],
processEscapes: true
},
TeX: {
equationNumbers: { autoNumber: "AMS" },
Macros: {
subscript: ['_{#1}', 1],
superscript: ['^{#1}', 1]
}
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML-full">
</script>
</head>
<body>
<div class="wrapper-masthead">
<header class="masthead clearfix">
<a href="/" class="site-avatar"><img src="/images/avatar.png" /></a>
<div class="site-info">
<h1 class="site-name"><a href="/">Alexej Gossmann</a></h1>
<p class="site-description">PhD student with focus on statistics, machine learning, and programming, among other things</p>
</div>
<nav>
<a href="/">/blog/</a>
<a href="/publications">/publications/</a>
<a href="/code">/code/</a>
<a href="/about">/about/</a>
</nav>
</header>
</div>
<div id="main" role="main" class="container">
<h2 class="post_title">Posts Tagged “regression”</h2>
<ul>
<article class="post">
<h1><a href="/categorical_data_glm_in_ruby/">Logistic regression with categorical data in Ruby</a></h1>
<div class="entry">
<p>I had some fun analysing the <a href="https://www.kaggle.com/c/shelter-animal-outcomes">shelter animal data</a> from <a href="https://www.kaggle.com/competitions">kaggle</a> using the Ruby gems <code class="highlighter-rouge">daru</code> for data wrangling and <code class="highlighter-rouge">statsample-glm</code> for model fitting. In this blog post, I want to demonstrate that data wrangling and statistical modeling is not an area of absolute predominance of Python and R, but that it is possible in Ruby too (though, currently to a much lesser extent).</p>
</div>
<a href="/categorical_data_glm_in_ruby/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/grpSLOPE_on_CRAN/">My first R package on CRAN</a></h1>
<div class="entry">
<p>A couple of weeks ago I have released my first R package on CRAN. For me it turned out to be a far less painful process than many people on the internet portray it to be (even though the package uses quite a lot of C++ code via Rcpp and RcppEigen, and even though R CMD check returns two NOTEs). Some of the most helpful resources for publishing the package were:</p>
</div>
<a href="/grpSLOPE_on_CRAN/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/TSH_and_TPE_observations/">"Testing Statistical Hypotheses" and "Theory of Point Estimation" impressions</a></h1>
<div class="entry">
<p>I spent much of the last two months reading Lehmann & Romano “Testing Statistical Hypotheses” (3rd ed.) and Lehmann & Casella “Theory of Point Estimation” (2nd ed.), abbr. TSH and TPE. The following is a collection of <del>random facts</del> observations I made while reading TSH and TPE. The choice of topics is biased towards application in regression models.</p>
</div>
<a href="/TSH_and_TPE_observations/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/gsoc-2015-mixed_models/">Statistical linear mixed models in Ruby with mixed_models (GSoC2015)</a></h1>
<div class="entry">
<p>Google Summer of Code 2015 is coming to an end. During this summer, I have learned too many things to list here about statistical modeling, Ruby and software development in general, and I had a lot of fun in the process!</p>
</div>
<a href="/gsoc-2015-mixed_models/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/bootstap_confidence_intervals/">Bootstrapping and bootstrap confidence intervals for linear mixed models</a></h1>
<div class="entry">
<p>(<strong>EDIT:</strong> I have also written <a href="http://www.alexejgossmann.com/Lehmanns_TSH_and_TPE/bootstrap_intervals_for_LMM/">a more theoretical blog post</a> on the topic.)</p>
</div>
<a href="/bootstap_confidence_intervals/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/mixed_models_applied_to_family_SNP_data/">A (naive) application of linear mixed models to genetics</a></h1>
<div class="entry">
<p>The following shows an application of class <code class="highlighter-rouge">LMM</code> from the Ruby gem <a href="https://github.com/agisga/mixed_models.git"><code class="highlighter-rouge">mixed_models</code></a> to SNP data (<a href="https://en.wikipedia.org/wiki/Single-nucleotide_polymorphism">single-nucleotide polymorphism</a>) with known pedigree structures. The family information is prior knowledge that we can model in the random effects of a linear mixed effects model.</p>
</div>
<a href="/mixed_models_applied_to_family_SNP_data/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/MixedModels_p_values_and_CI/">P-values and confidence intervals</a></h1>
<div class="entry">
<p>A few days ago I started working on hypotheses tests and confidence intervals for my project <a href="https://github.com/agisga/mixed_models"><code class="highlighter-rouge">mixed_models</code></a>, and I got pretty surprised by certain things.</p>
</div>
<a href="/MixedModels_p_values_and_CI/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/MixedModels_from_formula/">MixedModels Formula Interface and Categorical Variables</a></h1>
<div class="entry">
<p>I made some more progress on my <a href="https://github.com/agisga/MixedModels">Google Summer of Code project MixedModels</a>. The linear mixed models fitting method is now capable of handling non-numeric (i.e., categorical) predictor variables, as well as interaction effects. Moreover, I gave the method a user friendly R-formula-like interface. I will present these new capabilities of the Ruby gem with an example. Then I will briefly describe their implementation.</p>
</div>
<a href="/MixedModels_from_formula/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/LMM-model-specification/">Model specification for linear mixed model</a></h1>
<div class="entry">
<p>Last week I wrote about my implementation of an algorithm that fits a linear mixed model in Ruby using the gem <a href="https://github.com/agisga/MixedModels">MixedModels</a>, that I am working on right now. See, <a href="http://agisga.github.io/First-linear-mixed-model-fit/">first rudimentary LMM fit</a>.</p>
</div>
<a href="/LMM-model-specification/" class="read-more">Read More</a>
</article>
<article class="post">
<h1><a href="/First-linear-mixed-model-fit/">A rudimentary first linear mixed model fit</a></h1>
<div class="entry">
<p>During the last two weeks I made some progress on my <a href="https://github.com/agisga/MixedModels">Google Summer of Code project</a>.
The Ruby gem is now capable of fitting linear mixed models. In this short blog post I want to give an example, and compare the results I get in Ruby to those obtained by <code class="highlighter-rouge">lme4</code> in R.</p>
</div>
<a href="/First-linear-mixed-model-fit/" class="read-more">Read More</a>
</article>
</ul>
<!-- based on http://charliepark.org/tags-in-jekyll/, and https://github.com/charliepark/charliepark.github.com/blob/master/_layouts/tag_index.html -->
</div>
<div class="wrapper-footer">
<div class="container">
<footer class="footer">
<a href="mailto:alexej.go@gmail.com"><i class="svg-icon email"></i></a>
<a href="https://www.facebook.com/alexej.yexela"><i class="svg-icon facebook"></i></a>
<a href="https://github.com/agisga"><i class="svg-icon github"></i></a>
<a href="https://www.linkedin.com/in/alexejgossmann"><i class="svg-icon linkedin"></i></a>
<a href="/feed.xml"><i class="svg-icon rss"></i></a>
</footer>
</div>
</div>
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-94080131-1', 'auto');
ga('send', 'pageview', {
'page': '/tag/regression/',
'title': 'Posts Tagged “regression”'
});
</script>
<!-- End Google Analytics -->
</body>
</html>
| {
"content_hash": "92bdf21d6ade5e55f46c244668f45c37",
"timestamp": "",
"source": "github",
"line_count": 554,
"max_line_length": 572,
"avg_line_length": 20.588447653429604,
"alnum_prop": 0.60713659477468,
"repo_name": "agisga/agisga.github.io",
"id": "3d7d36dd4dc65730422afd566a9b2fa697e59b00",
"size": "11416",
"binary": false,
"copies": "1",
"ref": "refs/heads/source",
"path": "_site/tag/regression/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49881"
},
{
"name": "HTML",
"bytes": "1065447"
},
{
"name": "R",
"bytes": "7152"
},
{
"name": "Ruby",
"bytes": "2720"
},
{
"name": "TeX",
"bytes": "10061"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template format_named_scope</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../../expressions.html#header.boost.log.expressions.formatters.named_scope_hpp" title="Header <boost/log/expressions/formatters/named_scope.hpp>">
<link rel="prev" href="format_named_s_idp52595712.html" title="Function template format_named_scope">
<link rel="next" href="format_named_s_idp52606768.html" title="Function template format_named_scope">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="format_named_s_idp52595712.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../expressions.html#header.boost.log.expressions.formatters.named_scope_hpp"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="format_named_s_idp52606768.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.log.expressions.format_named_s_idp52601232"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function template format_named_scope</span></h2>
<p>boost::log::expressions::format_named_scope</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../expressions.html#header.boost.log.expressions.formatters.named_scope_hpp" title="Header <boost/log/expressions/formatters/named_scope.hpp>">boost/log/expressions/formatters/named_scope.hpp</a>>
</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> CharT<span class="special">></span>
<a class="link" href="format_named_scope_actor.html" title="Class template format_named_scope_actor">format_named_scope_actor</a><span class="special"><</span> <span class="identifier">fallback_to_none</span><span class="special">,</span> <span class="identifier">CharT</span> <span class="special">></span>
<span class="identifier">format_named_scope</span><span class="special">(</span><span class="identifier">attribute_name</span> <span class="keyword">const</span> <span class="special">&</span> name<span class="special">,</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_string</span><span class="special"><</span> <span class="identifier">CharT</span> <span class="special">></span> <span class="keyword">const</span> <span class="special">&</span> element_format<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp127494640"></a><h2>Description</h2>
<p>The function generates a manipulator node in a template expression. The manipulator must participate in a formatting expression (stream output or <code class="computeroutput">format</code> placeholder filler).</p>
<p>
</p>
<div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody><tr>
<td><p><span class="term">Parameters:</span></p></td>
<td><div class="variablelist"><table border="0" class="variablelist compact">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><code class="computeroutput">element_format</code></span></p></td>
<td><p>Format string for a single named scope </p></td>
</tr>
<tr>
<td><p><span class="term"><code class="computeroutput">name</code></span></p></td>
<td><p>Attribute name </p></td>
</tr>
</tbody>
</table></div></td>
</tr></tbody>
</table></div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007-2015 Andrey
Semashev<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>).
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="format_named_s_idp52595712.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../expressions.html#header.boost.log.expressions.formatters.named_scope_hpp"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="format_named_s_idp52606768.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "5b24ae1836f69c79e46c9c3380a6e187",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 542,
"avg_line_length": 71.38461538461539,
"alnum_prop": 0.6698994252873564,
"repo_name": "Franky666/programmiersprachen-raytracer",
"id": "660cdcc9f3791b4dd05f25b5aa6398b29ef01e7f",
"size": "5568",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "external/boost_1_59_0/libs/log/doc/html/boost/log/expressions/format_named_s_idp52601232.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "905071"
},
{
"name": "C++",
"bytes": "46207"
},
{
"name": "CMake",
"bytes": "4419"
}
],
"symlink_target": ""
} |
namespace StudentsFetcher
{
partial class frmLists
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(122, 55);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// frmLists
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(702, 470);
this.Controls.Add(this.button1);
this.Name = "frmLists";
this.Text = "frmLists";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
}
} | {
"content_hash": "1ba5bd6aa36ea1375cc24b983a2e4ff4",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 107,
"avg_line_length": 33.166666666666664,
"alnum_prop": 0.549748743718593,
"repo_name": "CBenghi/UnnItBooster",
"id": "b81bc37ff9dc0801ec14c1777b3777ee2cd3185d",
"size": "1992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UnnITBooster/frmLists.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "251748"
},
{
"name": "Smalltalk",
"bytes": "3"
}
],
"symlink_target": ""
} |
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'tr',
isEditing: false,
actions: {
openTarget() {
window.open(Routing.generate('post_preview', {slug: this.get('mediaFile.post.url')}), '_blank');
},
edit: function () {
this.set('isEditing', true);
},
save: function () {
this.get('mediaFile').save().then(() => {
this.set('isEditing', false);
});
},
reset: function () {
this.get('mediaFile').rollbackAttributes();
this.set('isEditing', false);
},
remove: function () {
var modal = $('#confirmation-modal');
modal.attr('data-object-id', this.get('mediaFile.id'));
modal.find('#confirmation-object-name').html(this.get('mediaFile.originalFilename'));
modal.modal('show');
}
}
});
| {
"content_hash": "b99aaac2663c4cf14cbda38494f6f3c4",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 108,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.5074468085106383,
"repo_name": "morontt/zend-blog-3-backend",
"id": "add3e474027970e787db2355d8cd99c0b26e6191",
"size": "940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spa/app/components/tr-media.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12050"
},
{
"name": "Dockerfile",
"bytes": "3615"
},
{
"name": "Gherkin",
"bytes": "2678"
},
{
"name": "HTML",
"bytes": "1575"
},
{
"name": "Handlebars",
"bytes": "36570"
},
{
"name": "JavaScript",
"bytes": "56091"
},
{
"name": "PHP",
"bytes": "430417"
},
{
"name": "Shell",
"bytes": "3956"
},
{
"name": "Twig",
"bytes": "7601"
}
],
"symlink_target": ""
} |
/* Metadata API.
*/
/*
Copyright (C) 1991-2005 The National Gallery
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
#ifndef IM_META_H
#define IM_META_H
#ifdef __cplusplus
extern "C" {
#endif /*__cplusplus*/
/**
* IM_META_EXIF_NAME:
*
* The name that JPEG read and write operations use for the image's EXIF data.
*/
#define IM_META_EXIF_NAME "exif-data"
/**
* IM_META_ICC_NAME:
*
* The name we use to attach an ICC profile. The file read and write
* operations for TIFF, JPEG, PNG and others use this item of metadata to
* attach and save ICC profiles. The profile is updated by the
* im_icc_transform() operations.
*/
#define IM_META_ICC_NAME "icc-profile-data"
/**
* IM_META_XML:
*
* The original XML that was used to code the metadata after reading a VIPS
* format file.
*/
#define IM_META_XML "xml-header"
/**
* IM_META_RESOLUTION_UNIT:
*
* The JPEG and TIFF read and write operations use this to record the
* file's preferred unit for resolution.
*/
#define IM_META_RESOLUTION_UNIT "resolution-unit"
/**
* IM_TYPE_SAVE_STRING:
*
* The #GType for an "im_save_string".
*/
#define IM_TYPE_SAVE_STRING (im_save_string_get_type())
GType im_save_string_get_type( void );
const char *im_save_string_get( const GValue *value );
void im_save_string_set( GValue *value, const char *str );
void im_save_string_setf( GValue *value, const char *fmt, ... )
__attribute__((format(printf, 2, 3)));
/**
* IM_TYPE_AREA:
*
* The #GType for an #im_area.
*/
#define IM_TYPE_AREA (im_area_get_type())
GType im_area_get_type( void );
/**
* IM_TYPE_REF_STRING:
*
* The #GType for an #im_refstring.
*/
#define IM_TYPE_REF_STRING (im_ref_string_get_type())
GType im_ref_string_get_type( void );
int im_ref_string_set( GValue *value, const char *str );
const char *im_ref_string_get( const GValue *value );
size_t im_ref_string_get_length( const GValue *value );
/**
* IM_TYPE_BLOB:
*
* The #GType for an #im_blob.
*/
#define IM_TYPE_BLOB (im_blob_get_type())
GType im_blob_get_type( void );
void *im_blob_get( const GValue *value, size_t *data_length );
int im_blob_set( GValue *value, im_callback_fn free_fn,
void *data, size_t length );
int im_meta_set( IMAGE *, const char *field, GValue * );
gboolean im_meta_remove( IMAGE *im, const char *field );
int im_meta_get( IMAGE *, const char *field, GValue * );
GType im_meta_get_typeof( IMAGE *im, const char *field );
int im_meta_set_int( IMAGE *, const char *field, int i );
int im_meta_get_int( IMAGE *, const char *field, int *i );
int im_meta_set_double( IMAGE *, const char *field, double d );
int im_meta_get_double( IMAGE *, const char *field, double *d );
int im_meta_set_area( IMAGE *, const char *field, im_callback_fn, void * );
int im_meta_get_area( IMAGE *, const char *field, void **data );
int im_meta_set_string( IMAGE *, const char *field, const char *str );
int im_meta_get_string( IMAGE *, const char *field, char **str );
int im_meta_set_blob( IMAGE *im, const char *field,
im_callback_fn free_fn, void *blob, size_t blob_length );
int im_meta_get_blob( IMAGE *im, const char *field,
void **blob, size_t *blob_length );
#ifdef __cplusplus
}
#endif /*__cplusplus*/
#endif /*!IM_META_H*/
| {
"content_hash": "e23c5e9eb86fce514a9e3d3e89b319c5",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 78,
"avg_line_length": 30.236641221374047,
"alnum_prop": 0.6834132794748801,
"repo_name": "bamos/parsec-benchmark",
"id": "74cce5dc6121dcebe68bb46bbc386cd0f5e17023",
"size": "3961",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pkgs/apps/vips/src/libvips/include/vips/meta.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "89144"
},
{
"name": "Assembly",
"bytes": "3019403"
},
{
"name": "C",
"bytes": "82541944"
},
{
"name": "C#",
"bytes": "55726"
},
{
"name": "C++",
"bytes": "18212152"
},
{
"name": "Delphi",
"bytes": "40318"
},
{
"name": "Eiffel",
"bytes": "133"
},
{
"name": "Emacs Lisp",
"bytes": "9437"
},
{
"name": "FORTRAN",
"bytes": "6058"
},
{
"name": "Java",
"bytes": "291"
},
{
"name": "JavaScript",
"bytes": "38451"
},
{
"name": "Lua",
"bytes": "9"
},
{
"name": "Objective-C",
"bytes": "1283615"
},
{
"name": "PHP",
"bytes": "20640"
},
{
"name": "Perl",
"bytes": "3419959"
},
{
"name": "Prolog",
"bytes": "155090"
},
{
"name": "Python",
"bytes": "915970"
},
{
"name": "Ruby",
"bytes": "1237"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Shell",
"bytes": "2011986"
},
{
"name": "Smalltalk",
"bytes": "10092"
},
{
"name": "Tcl",
"bytes": "2809"
},
{
"name": "VimL",
"bytes": "7566"
},
{
"name": "eC",
"bytes": "5079"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>FST - Bruno Pesca</title>
<meta name="description" content="Keep track of the statistics from Bruno Pesca. Average heat score, heat wins, heat wins percentage, epic heats road to the final">
<meta name="author" content="">
<link rel="apple-touch-icon" sizes="57x57" href="/favicon/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<meta property="og:title" content="Fantasy Surfing tips"/>
<meta property="og:image" content="https://fantasysurfingtips.com/img/just_waves.png"/>
<meta property="og:description" content="See how great Bruno Pesca is surfing this year"/>
<!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: https://bootswatch.com/flatly/ -->
<link href="https://fantasysurfingtips.com/css/bootstrap.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="https://fantasysurfingtips.com/css/freelancer.css" rel="stylesheet">
<link href="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" />
<!-- Custom Fonts -->
<link href="https://fantasysurfingtips.com/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://code.jquery.com/jquery-2.x-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ujs/1.2.1/rails.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://www.w3schools.com/lib/w3data.js"></script>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-2675412311042802",
enable_page_level_ads: true
});
</script>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<!-- Navigation -->
<div w3-include-html="https://fantasysurfingtips.com/layout/header.html"></div>
<!-- Header -->
<div w3-include-html="https://fantasysurfingtips.com/layout/sponsor.html"></div>
<section >
<div class="container">
<div class="row">
<div class="col-sm-3 ">
<div class="col-sm-2 ">
</div>
<div class="col-sm-8 ">
<!-- <img src="http://fantasysurfingtips.com/img/surfers/bpes.png" class="img-responsive" alt=""> -->
<h3 style="text-align:center;">Bruno Pesca</h3>
<a href="https://twitter.com/share" class="" data-via="fansurfingtips"><i class="fa fa-twitter"></i> Share on Twitter</i></a> <br/>
<a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Ffantasysurfingtips.com%2Fsurfers%2Fbpes&src=sdkpreparse"><i class="fa fa-facebook"></i> Share on Facebook</a>
</div>
<div class="col-sm-2 ">
</div>
</div>
<div class="col-sm-3 portfolio-item">
</div>
<div class="col-sm-3 portfolio-item">
<h6 style="text-align:center;">Avg Heat Score (FST DATA)</h6>
<h1 style="text-align:center;">4.11</h1>
</div>
</div>
<hr/>
<h4 style="text-align:center;" >Heat Stats (FST data)</h4>
<div class="row">
<div class="col-sm-4 portfolio-item">
<h6 style="text-align:center;">Heats</h6>
<h2 style="text-align:center;">2</h2>
</div>
<div class="col-sm-4 portfolio-item">
<h6 style="text-align:center;">Heat wins</h6>
<h2 style="text-align:center;">0</h2>
</div>
<div class="col-sm-4 portfolio-item">
<h6 style="text-align:center;">HEAT WINS PERCENTAGE</h6>
<h2 style="text-align:center;">0.0%</h2>
</div>
</div>
<hr/>
<h4 style="text-align:center;">Avg Heat Score progression</h4>
<div id="avg_chart" style="height: 250px;"></div>
<hr/>
<h4 style="text-align:center;">Heat stats progression</h4>
<div id="heat_chart" style="height: 250px;"></div>
<hr/>
<style type="text/css">
.heats-all{
z-index: 3;
margin-left: 5px;
cursor: pointer;
}
</style>
<div class="container">
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
var disqus_config = function () {
this.page.url = "http://fantasysurfingtips.com/surfers/bpes"; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = '3373'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//fantasysurfingtips.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</section>
<script type="text/javascript">
$('.heats-all').click(function(){
$('.heats-all-stat').css('display', 'none')
$('#'+$(this).attr('id')+'-stat').css('display', 'block')
});
$('.heats-2016').click(function(){
$('.heats-2016-stat').css('display', 'none')
$('#'+$(this).attr('id')+'-stat').css('display', 'block')
});
$('document').ready(function(){
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'avg_chart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['avg', 'avg_all'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Avg score in year', 'Avg score FST DATA']
});
new Morris.Bar({
// ID of the element in which to draw the chart.
element: 'heat_chart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['heats', 'wins', 'percs'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Heats surfed', 'Heats won', 'Winning percentage']
});
});
</script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<!-- Footer -->
<div w3-include-html="https://fantasysurfingtips.com/layout/footer.html"></div>
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-74337819-1', 'auto'); // Replace with your property ID.
ga('send', 'pageview');
</script>
<script>
w3IncludeHTML();
</script>
<!-- jQuery -->
<script src="https://fantasysurfingtips.com/js/jquery.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="https://fantasysurfingtips.com/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="https://fantasysurfingtips.com/js/classie.js"></script>
<script src="https://fantasysurfingtips.com/js/cbpAnimatedHeader.js"></script>
<!-- Contact Form JavaScript -->
<script src="https://fantasysurfingtips.com/js/jqBootstrapValidation.js"></script>
<script src="https://fantasysurfingtips.com/js/contact_me.js"></script>
<!-- Custom Theme JavaScript -->
<script src="https://fantasysurfingtips.com/js/freelancer.js"></script>
<script type="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "1088dc22023127627354b8003452e122",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 295,
"avg_line_length": 39.30281690140845,
"alnum_prop": 0.6311592904497402,
"repo_name": "chicofilho/fst",
"id": "ec294767ffc48868a6aabf5e9a4a07c6ffcdf8e4",
"size": "11162",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "surfers/mqs/bpes.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25157"
},
{
"name": "HTML",
"bytes": "114679577"
},
{
"name": "JavaScript",
"bytes": "43263"
},
{
"name": "PHP",
"bytes": "1097"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.regression.linear_model.OLSResults.HC2_se — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/_sphinx_javascript_frameworks_compat.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/sphinx_highlight.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.regression.linear_model.OLSResults.HC3_se" href="statsmodels.regression.linear_model.OLSResults.HC3_se.html" />
<link rel="prev" title="statsmodels.regression.linear_model.OLSResults.HC1_se" href="statsmodels.regression.linear_model.OLSResults.HC1_se.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.regression.linear_model.OLSResults.HC2_se" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.13.3</span>
<span class="md-header-nav__topic"> statsmodels.regression.linear_model.OLSResults.HC2_se </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../regression.html" class="md-tabs__link">Linear Regression</a></li>
<li class="md-tabs__item"><a href="statsmodels.regression.linear_model.OLSResults.html" class="md-tabs__link">statsmodels.regression.linear_model.OLSResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.13.3</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li>
<li class="md-nav__item">
<a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Contents</label>
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a href="#generated-statsmodels-regression-linear-model-olsresults-hc2-se--page-root" class="md-nav__link">statsmodels.regression.linear_model.OLSResults.HC2_se</a><nav class="md-nav">
<ul class="md-nav__list">
<li class="md-nav__item"><a href="#statsmodels.regression.linear_model.OLSResults.HC2_se" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">OLSResults.HC2_se</span></code></a>
</li></ul>
</nav>
</li>
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.linear_model.OLSResults.HC2_se.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<section id="statsmodels-regression-linear-model-olsresults-hc2-se">
<h1 id="generated-statsmodels-regression-linear-model-olsresults-hc2-se--page-root">statsmodels.regression.linear_model.OLSResults.HC2_se<a class="headerlink" href="#generated-statsmodels-regression-linear-model-olsresults-hc2-se--page-root" title="Permalink to this heading">¶</a></h1>
<dl class="py attribute">
<dt class="sig sig-object py" id="statsmodels.regression.linear_model.OLSResults.HC2_se">
<span class="sig-prename descclassname"><span class="pre">OLSResults.</span></span><span class="sig-name descname"><span class="pre">HC2_se</span></span><a class="headerlink" href="#statsmodels.regression.linear_model.OLSResults.HC2_se" title="Permalink to this definition">¶</a></dt>
<dd><p>MacKinnon and White’s (1985) heteroskedasticity robust standard errors.</p>
<p class="rubric">Notes</p>
<p>Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)) X(X.T X)^(-1)
where h_ii = x_i(X.T X)^(-1)x_i.T</p>
<p>When HC2_se or cov_HC2 is called the RegressionResults instance will
then have another attribute <cite>het_scale</cite>, which is in this case is
resid^(2)/(1-h_ii).</p>
</dd></dl>
</section>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.regression.linear_model.OLSResults.HC1_se.html" title="statsmodels.regression.linear_model.OLSResults.HC1_se"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.regression.linear_model.OLSResults.HC1_se </span>
</div>
</a>
<a href="statsmodels.regression.linear_model.OLSResults.HC3_se.html" title="statsmodels.regression.linear_model.OLSResults.HC3_se"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.regression.linear_model.OLSResults.HC3_se </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Nov 01, 2022.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "733e6facd77b1d9389440713dcbb9930",
"timestamp": "",
"source": "github",
"line_count": 512,
"max_line_length": 999,
"avg_line_length": 37.931640625,
"alnum_prop": 0.5966222130683281,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "2c986d69093b225d46a89da596c5546d2b0c0a21",
"size": "19427",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.13.3/generated/statsmodels.regression.linear_model.OLSResults.HC2_se.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
echo "---------------------update-----------------------" ;
rm -rf /var/lib/apt/lists/*;
sudo dpkg --configure -a;
sudo apt-get install -f;
sudo apt-get dist-upgrade -y ;
sudo apt-get update -y;
sudo apt-get upgrade -y ;
echo "------------------------soft--------------------" ;
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --force-yes python-software-properties software-properties-common;
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --force-yes --no-install-recommends firefox flashplugin-installer flashplugin-downloader firefox-locale-zh-hant firefox-locale-zh-hans dosbox putty visualboyadvance visualboyadvance-gtk libreoffice libreoffice-l10n-zh-cn pinta x11vnc;
echo "------------------------Clean--------------------" ;
sudo apt-get autoremove -y ;
sudo apt-get clean -y ;
sudo apt-get autoclean -y ;
echo "--------------------------------------------" ; | {
"content_hash": "30ee4f968417a193a6b4b499bd8b4bb9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 289,
"avg_line_length": 59.4,
"alnum_prop": 0.6139169472502806,
"repo_name": "x3193/ubt1404",
"id": "1a622dd8a2d2b3f699de8d94acca681effb78148",
"size": "904",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "shell/conf/install/u7soft.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "27629"
},
{
"name": "Dockerfile",
"bytes": "4616"
},
{
"name": "HTML",
"bytes": "3144"
},
{
"name": "JavaScript",
"bytes": "1596"
},
{
"name": "Makefile",
"bytes": "428"
},
{
"name": "PHP",
"bytes": "6684540"
},
{
"name": "Python",
"bytes": "2847"
},
{
"name": "Roff",
"bytes": "1539126"
},
{
"name": "Shell",
"bytes": "319932"
}
],
"symlink_target": ""
} |
%
% Copyright 2016, General Dynamics C4 Systems
%
% This software may be distributed and modified according to the terms of
% the GNU General Public License version 2. Note that NO WARRANTY is provided.
% See "LICENSE_GPLv2.txt" for details.
%
% @TAG(GD_GPL)
%
\apidoc
{arm_page_invalidatedata}
{ARM Page - Invalidate Data}
{Invalidates the cache range within the given page. The start and end are relative to the page being serviced
and should be aligned to a cache line boundary where possible.
An additional clean is performed on the outer cache lines if the start and end are
not aligned, to clean out the bytes between the requested and the cache line boundary.}
{static inline int seL4\_ARM\_Page\_Invalidate\_Data}
{
\param{seL4\_ARM\_Page}{\_service}{The page whose contents will be flushed.}
\param{seL4\_Word}{start\_offset}{The offset, relative to the start of the page inclusive.}
\param{seL4\_Word}{end\_offset}{The offset, relative to the start of the page exclusive.}
}
{\errorenumdesc}
{See \autoref{ch:vspace}}
| {
"content_hash": "590acb6b699980dd975a35c66d9ecac9",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 110,
"avg_line_length": 39.73076923076923,
"alnum_prop": 0.7579864472410455,
"repo_name": "cmr/seL4",
"id": "6c623515d057c932ae1e93b04f84a496d9cc5cb6",
"size": "1033",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "manual/parts/api/arm_page_invalidatedata.tex",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "79182"
},
{
"name": "Brainfuck",
"bytes": "3357"
},
{
"name": "C",
"bytes": "1783638"
},
{
"name": "C++",
"bytes": "147133"
},
{
"name": "HyPhy",
"bytes": "75654"
},
{
"name": "Makefile",
"bytes": "76977"
},
{
"name": "Objective-C",
"bytes": "4319"
},
{
"name": "Python",
"bytes": "47292"
},
{
"name": "TeX",
"bytes": "173044"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.block.Block;
import com.facebook.presto.block.BlockBuilder;
import com.facebook.presto.tuple.TupleInfo;
import io.airlift.slice.Slices;
import java.util.List;
import static com.facebook.presto.operator.HashAggregationOperator.HashMemoryManager;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_BOOLEAN;
public class MarkDistinctHash
{
private final GroupByHash groupByHash;
private long nextDistinctId;
public MarkDistinctHash(List<TupleInfo.Type> types, int[] channels, HashMemoryManager memoryManager)
{
this(types, channels, memoryManager, 10_000);
}
public MarkDistinctHash(List<TupleInfo.Type> types, int[] channels, HashMemoryManager memoryManager, int expectedDistinctValues)
{
this.groupByHash = new GroupByHash(types, channels, expectedDistinctValues, memoryManager);
}
public long getEstimatedSize()
{
return groupByHash.getEstimatedSize();
}
public Block markDistinctRows(Page page)
{
int positionCount = page.getPositionCount();
int blockSize = SINGLE_BOOLEAN.getFixedSize() * positionCount;
BlockBuilder blockBuilder = new BlockBuilder(SINGLE_BOOLEAN, blockSize, Slices.allocate(blockSize).getOutput());
GroupByIdBlock ids = groupByHash.getGroupIds(page);
for (int i = 0; i < ids.getPositionCount(); i++) {
if (ids.getGroupId(i) == nextDistinctId) {
blockBuilder.append(true);
nextDistinctId++;
}
else {
blockBuilder.append(false);
}
}
return blockBuilder.build();
}
}
| {
"content_hash": "971c7ef5798505a871af821f3e049f37",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 132,
"avg_line_length": 35.28125,
"alnum_prop": 0.7037201062887511,
"repo_name": "HackShare/Presto",
"id": "b352c91c8e633614d1b4b6f1090a0b8f46092af4",
"size": "2258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "presto-main/src/main/java/com/facebook/presto/operator/MarkDistinctHash.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "41747"
},
{
"name": "HTML",
"bytes": "25433"
},
{
"name": "Java",
"bytes": "6562972"
},
{
"name": "Makefile",
"bytes": "6819"
},
{
"name": "PLSQL",
"bytes": "8346"
},
{
"name": "Python",
"bytes": "4319"
}
],
"symlink_target": ""
} |
<?php
namespace Login\Controller;
use Login\Form\LoginForm;
use Login\Controller\LoginAuthAdapter;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session;
use Zend\Session\Storage\SessionStorage as SessionStorage;
use Zend\Session\Container;
class LoginController extends AbstractActionController
{
private $adapter;
public function getForm()
{
return new LoginForm(array(
'action' => '/login/process',
'method' => 'post',
));
}
public function getAuthAdapter(array $params) {
if(!isset($this->adapter)) {
$adapter = new LoginAuthAdapter($params['username'], $params['password']);
}
$this->adapter = $adapter;
return $this->adapter;
}
public function indexAction() {
$form = $this->getForm();
$session = new Container('FredLoyaAdmin');
if($session->offsetExists('systemMessage')) {
$message = $session->offsetGet('systemMessage');
$session->offsetUnset('systemMessage');
} else {
$message = '';
}
return array('form' => $form, 'displayMessage' => $message );
}
public function invalidAction() {
$form = $this->getForm();
$form->setAuthenticationMessage('Invalid Login Credentials');
return array('form' => $form);
}
public function processAction()
{
$request = $this->getRequest();
// Check if we have a POST request
if (!$request->isPost()) {
return $this->_helper->redirector('index');
}
// Get our form and validate it
$form = new LoginForm();
if($request->isPost()) {
$form->setData($request->getPost());
if (!$form->isValid()) {
// Invalid entries
$this->view->form = $form;
return $this->redirect()->toRoute('login'); // re-render the login form
}
}
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getData());
$auth = new AuthenticationService();
$storage = new Session();
$auth->setStorage($storage);
$auth->setAdapter($adapter);
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$this->view->form = $form;
$form->setAuthenticationMessage('Invalid credentials provided');
return $this->redirect()->toRoute('login', array('controller' => 'login', 'action' => 'invalid'));
} else {
$session = new Container('FredLoyaAdmin');
$session->offsetSet('userIsLoggedIn', true);
$session->offsetSet('authAdapter', $adapter);
//}
// We're authenticated! Redirect to the home page
return $this->redirect()->toRoute('country');
}
}
public function logoutAction() {
$session = new Container('FredLoyaAdmin');
$session->offsetUnset('userIsLoggedIn');
$session->offsetUnset('authAdapter');
return $this->redirect()->toRoute('login');
}
}
?> | {
"content_hash": "ab47b04e36c03fb41fb9e93271460ccc",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 110,
"avg_line_length": 26.6,
"alnum_prop": 0.5288220551378446,
"repo_name": "Aresinho/flt-zend",
"id": "6889f6f78698a27e5896e7bf8d52a94a692e6d02",
"size": "3591",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Login/src/Login/Controller/LoginController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "2550"
},
{
"name": "PHP",
"bytes": "64152"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Formatting;
namespace System.Drawing.Graphics
{
public static class Jpg
{
//add jpg specific method later
public static Image Load(string filePath)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException(string.Format(Strings.MalformedFilePath, filePath));
}
else if (DLLImports.gdSupportsFileType(filePath, false))
{
Image img = new Image(DLLImports.gdImageCreateFromFile(filePath));
if (!img.TrueColor)
{
DLLImports.gdImagePaletteToTrueColor(img.gdImageStructPtr);
}
return img;
}
else
{
throw new FileLoadException(string.Format(Strings.FileTypeNotSupported, filePath));
}
}
//add jpg specific method later
public static void Write(Image img, string filePath)
{
DLLImports.gdImageSaveAlpha(img.gdImageStructPtr, 1);
if (!DLLImports.gdSupportsFileType(filePath, true))
{
throw new InvalidOperationException(string.Format(Strings.FileTypeNotSupported, filePath));
}
else
{
if (!DLLImports.gdImageFile(img.gdImageStructPtr, filePath))
{
throw new FileLoadException(string.Format(Strings.WriteToFileFailed, filePath));
}
}
}
public static Image Load(Stream stream)
{
if (stream != null)
{
unsafe
{
IntPtr pNativeImage = IntPtr.Zero;
var wrapper = new gdStreamWrapper(stream);
pNativeImage = DLLImports.gdImageCreateFromJpegCtx(ref wrapper.IOCallbacks);
DLLImports.gdImageStruct* pStruct = (DLLImports.gdImageStruct*)pNativeImage;
Image toRet = Image.Create(pStruct->sx, pStruct->sx);
DLLImports.gdImageDestroy(toRet.gdImageStructPtr);
toRet.gdImageStructPtr = pNativeImage;
return toRet;
}
}
else
{
throw new InvalidOperationException(Strings.NullStreamReferenced);
}
}
public static void Write(Image bmp, Stream stream)
{
DLLImports.gdImageSaveAlpha(bmp.gdImageStructPtr, 1);
//MARSHALLING?
DLLImports.gdImageStruct gdImageStruct = Marshal.PtrToStructure<DLLImports.gdImageStruct>(bmp.gdImageStructPtr);
var wrapper = new gdStreamWrapper(stream);
DLLImports.gdImageJpegCtx(ref gdImageStruct, ref wrapper.IOCallbacks);
}
}
}
| {
"content_hash": "745b7771187300c1243a20efe29c69fa",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 124,
"avg_line_length": 34.505494505494504,
"alnum_prop": 0.5646496815286625,
"repo_name": "stephentoub/corefxlab",
"id": "a7ec16c26c9201401f85dadc26cdbda5174980ea",
"size": "3142",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "archived_projects/src/System.Drawing.Graphics/System/Drawing/Graphics/Jpg.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "221"
},
{
"name": "C",
"bytes": "11150"
},
{
"name": "C#",
"bytes": "5349352"
},
{
"name": "Common Lisp",
"bytes": "3721"
},
{
"name": "Groovy",
"bytes": "2527"
},
{
"name": "HTML",
"bytes": "24603"
},
{
"name": "JavaScript",
"bytes": "13818"
},
{
"name": "PowerShell",
"bytes": "25909"
},
{
"name": "Roff",
"bytes": "4227"
},
{
"name": "Shell",
"bytes": "24675"
}
],
"symlink_target": ""
} |
package api
import (
api "k8s.io/kubernetes/pkg/api"
unversioned "k8s.io/kubernetes/pkg/api/unversioned"
conversion "k8s.io/kubernetes/pkg/conversion"
)
func init() {
if err := api.Scheme.AddGeneratedDeepCopyFuncs(
DeepCopy_api_BinaryBuildRequestOptions,
DeepCopy_api_BinaryBuildSource,
DeepCopy_api_Build,
DeepCopy_api_BuildConfig,
DeepCopy_api_BuildConfigList,
DeepCopy_api_BuildConfigSpec,
DeepCopy_api_BuildConfigStatus,
DeepCopy_api_BuildList,
DeepCopy_api_BuildLog,
DeepCopy_api_BuildLogOptions,
DeepCopy_api_BuildOutput,
DeepCopy_api_BuildPostCommitSpec,
DeepCopy_api_BuildRequest,
DeepCopy_api_BuildSource,
DeepCopy_api_BuildSpec,
DeepCopy_api_BuildStatus,
DeepCopy_api_BuildStrategy,
DeepCopy_api_BuildTriggerCause,
DeepCopy_api_BuildTriggerPolicy,
DeepCopy_api_CommonSpec,
DeepCopy_api_CustomBuildStrategy,
DeepCopy_api_DockerBuildStrategy,
DeepCopy_api_GenericWebHookCause,
DeepCopy_api_GenericWebHookEvent,
DeepCopy_api_GitBuildSource,
DeepCopy_api_GitHubWebHookCause,
DeepCopy_api_GitInfo,
DeepCopy_api_GitRefInfo,
DeepCopy_api_GitSourceRevision,
DeepCopy_api_ImageChangeCause,
DeepCopy_api_ImageChangeTrigger,
DeepCopy_api_ImageSource,
DeepCopy_api_ImageSourcePath,
DeepCopy_api_JenkinsPipelineBuildStrategy,
DeepCopy_api_SecretBuildSource,
DeepCopy_api_SecretSpec,
DeepCopy_api_SourceBuildStrategy,
DeepCopy_api_SourceControlUser,
DeepCopy_api_SourceRevision,
DeepCopy_api_WebHookTrigger,
); err != nil {
// if one of the deep copy functions is malformed, detect it immediately.
panic(err)
}
}
func DeepCopy_api_BinaryBuildRequestOptions(in BinaryBuildRequestOptions, out *BinaryBuildRequestOptions, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil {
return err
}
out.AsFile = in.AsFile
out.Commit = in.Commit
out.Message = in.Message
out.AuthorName = in.AuthorName
out.AuthorEmail = in.AuthorEmail
out.CommitterName = in.CommitterName
out.CommitterEmail = in.CommitterEmail
return nil
}
func DeepCopy_api_BinaryBuildSource(in BinaryBuildSource, out *BinaryBuildSource, c *conversion.Cloner) error {
out.AsFile = in.AsFile
return nil
}
func DeepCopy_api_Build(in Build, out *Build, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil {
return err
}
if err := DeepCopy_api_BuildSpec(in.Spec, &out.Spec, c); err != nil {
return err
}
if err := DeepCopy_api_BuildStatus(in.Status, &out.Status, c); err != nil {
return err
}
return nil
}
func DeepCopy_api_BuildConfig(in BuildConfig, out *BuildConfig, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil {
return err
}
if err := DeepCopy_api_BuildConfigSpec(in.Spec, &out.Spec, c); err != nil {
return err
}
if err := DeepCopy_api_BuildConfigStatus(in.Status, &out.Status, c); err != nil {
return err
}
return nil
}
func DeepCopy_api_BuildConfigList(in BuildConfigList, out *BuildConfigList, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil {
return err
}
if in.Items != nil {
in, out := in.Items, &out.Items
*out = make([]BuildConfig, len(in))
for i := range in {
if err := DeepCopy_api_BuildConfig(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func DeepCopy_api_BuildConfigSpec(in BuildConfigSpec, out *BuildConfigSpec, c *conversion.Cloner) error {
if in.Triggers != nil {
in, out := in.Triggers, &out.Triggers
*out = make([]BuildTriggerPolicy, len(in))
for i := range in {
if err := DeepCopy_api_BuildTriggerPolicy(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Triggers = nil
}
out.RunPolicy = in.RunPolicy
if err := DeepCopy_api_CommonSpec(in.CommonSpec, &out.CommonSpec, c); err != nil {
return err
}
return nil
}
func DeepCopy_api_BuildConfigStatus(in BuildConfigStatus, out *BuildConfigStatus, c *conversion.Cloner) error {
out.LastVersion = in.LastVersion
return nil
}
func DeepCopy_api_BuildList(in BuildList, out *BuildList, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
if err := unversioned.DeepCopy_unversioned_ListMeta(in.ListMeta, &out.ListMeta, c); err != nil {
return err
}
if in.Items != nil {
in, out := in.Items, &out.Items
*out = make([]Build, len(in))
for i := range in {
if err := DeepCopy_api_Build(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
func DeepCopy_api_BuildLog(in BuildLog, out *BuildLog, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
return nil
}
func DeepCopy_api_BuildLogOptions(in BuildLogOptions, out *BuildLogOptions, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
out.Container = in.Container
out.Follow = in.Follow
out.Previous = in.Previous
if in.SinceSeconds != nil {
in, out := in.SinceSeconds, &out.SinceSeconds
*out = new(int64)
**out = *in
} else {
out.SinceSeconds = nil
}
if in.SinceTime != nil {
in, out := in.SinceTime, &out.SinceTime
*out = new(unversioned.Time)
if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil {
return err
}
} else {
out.SinceTime = nil
}
out.Timestamps = in.Timestamps
if in.TailLines != nil {
in, out := in.TailLines, &out.TailLines
*out = new(int64)
**out = *in
} else {
out.TailLines = nil
}
if in.LimitBytes != nil {
in, out := in.LimitBytes, &out.LimitBytes
*out = new(int64)
**out = *in
} else {
out.LimitBytes = nil
}
out.NoWait = in.NoWait
if in.Version != nil {
in, out := in.Version, &out.Version
*out = new(int64)
**out = *in
} else {
out.Version = nil
}
return nil
}
func DeepCopy_api_BuildOutput(in BuildOutput, out *BuildOutput, c *conversion.Cloner) error {
if in.To != nil {
in, out := in.To, &out.To
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.To = nil
}
if in.PushSecret != nil {
in, out := in.PushSecret, &out.PushSecret
*out = new(api.LocalObjectReference)
if err := api.DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.PushSecret = nil
}
return nil
}
func DeepCopy_api_BuildPostCommitSpec(in BuildPostCommitSpec, out *BuildPostCommitSpec, c *conversion.Cloner) error {
if in.Command != nil {
in, out := in.Command, &out.Command
*out = make([]string, len(in))
copy(*out, in)
} else {
out.Command = nil
}
if in.Args != nil {
in, out := in.Args, &out.Args
*out = make([]string, len(in))
copy(*out, in)
} else {
out.Args = nil
}
out.Script = in.Script
return nil
}
func DeepCopy_api_BuildRequest(in BuildRequest, out *BuildRequest, c *conversion.Cloner) error {
if err := unversioned.DeepCopy_unversioned_TypeMeta(in.TypeMeta, &out.TypeMeta, c); err != nil {
return err
}
if err := api.DeepCopy_api_ObjectMeta(in.ObjectMeta, &out.ObjectMeta, c); err != nil {
return err
}
if in.Revision != nil {
in, out := in.Revision, &out.Revision
*out = new(SourceRevision)
if err := DeepCopy_api_SourceRevision(*in, *out, c); err != nil {
return err
}
} else {
out.Revision = nil
}
if in.TriggeredByImage != nil {
in, out := in.TriggeredByImage, &out.TriggeredByImage
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.TriggeredByImage = nil
}
if in.From != nil {
in, out := in.From, &out.From
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.From = nil
}
if in.Binary != nil {
in, out := in.Binary, &out.Binary
*out = new(BinaryBuildSource)
if err := DeepCopy_api_BinaryBuildSource(*in, *out, c); err != nil {
return err
}
} else {
out.Binary = nil
}
if in.LastVersion != nil {
in, out := in.LastVersion, &out.LastVersion
*out = new(int64)
**out = *in
} else {
out.LastVersion = nil
}
if in.Env != nil {
in, out := in.Env, &out.Env
*out = make([]api.EnvVar, len(in))
for i := range in {
if err := api.DeepCopy_api_EnvVar(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Env = nil
}
if in.TriggeredBy != nil {
in, out := in.TriggeredBy, &out.TriggeredBy
*out = make([]BuildTriggerCause, len(in))
for i := range in {
if err := DeepCopy_api_BuildTriggerCause(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.TriggeredBy = nil
}
return nil
}
func DeepCopy_api_BuildSource(in BuildSource, out *BuildSource, c *conversion.Cloner) error {
if in.Binary != nil {
in, out := in.Binary, &out.Binary
*out = new(BinaryBuildSource)
if err := DeepCopy_api_BinaryBuildSource(*in, *out, c); err != nil {
return err
}
} else {
out.Binary = nil
}
if in.Dockerfile != nil {
in, out := in.Dockerfile, &out.Dockerfile
*out = new(string)
**out = *in
} else {
out.Dockerfile = nil
}
if in.Git != nil {
in, out := in.Git, &out.Git
*out = new(GitBuildSource)
if err := DeepCopy_api_GitBuildSource(*in, *out, c); err != nil {
return err
}
} else {
out.Git = nil
}
if in.Images != nil {
in, out := in.Images, &out.Images
*out = make([]ImageSource, len(in))
for i := range in {
if err := DeepCopy_api_ImageSource(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Images = nil
}
out.ContextDir = in.ContextDir
if in.SourceSecret != nil {
in, out := in.SourceSecret, &out.SourceSecret
*out = new(api.LocalObjectReference)
if err := api.DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.SourceSecret = nil
}
if in.Secrets != nil {
in, out := in.Secrets, &out.Secrets
*out = make([]SecretBuildSource, len(in))
for i := range in {
if err := DeepCopy_api_SecretBuildSource(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Secrets = nil
}
return nil
}
func DeepCopy_api_BuildSpec(in BuildSpec, out *BuildSpec, c *conversion.Cloner) error {
if err := DeepCopy_api_CommonSpec(in.CommonSpec, &out.CommonSpec, c); err != nil {
return err
}
if in.TriggeredBy != nil {
in, out := in.TriggeredBy, &out.TriggeredBy
*out = make([]BuildTriggerCause, len(in))
for i := range in {
if err := DeepCopy_api_BuildTriggerCause(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.TriggeredBy = nil
}
return nil
}
func DeepCopy_api_BuildStatus(in BuildStatus, out *BuildStatus, c *conversion.Cloner) error {
out.Phase = in.Phase
out.Cancelled = in.Cancelled
out.Reason = in.Reason
out.Message = in.Message
if in.StartTimestamp != nil {
in, out := in.StartTimestamp, &out.StartTimestamp
*out = new(unversioned.Time)
if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil {
return err
}
} else {
out.StartTimestamp = nil
}
if in.CompletionTimestamp != nil {
in, out := in.CompletionTimestamp, &out.CompletionTimestamp
*out = new(unversioned.Time)
if err := unversioned.DeepCopy_unversioned_Time(*in, *out, c); err != nil {
return err
}
} else {
out.CompletionTimestamp = nil
}
out.Duration = in.Duration
out.OutputDockerImageReference = in.OutputDockerImageReference
if in.Config != nil {
in, out := in.Config, &out.Config
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.Config = nil
}
return nil
}
func DeepCopy_api_BuildStrategy(in BuildStrategy, out *BuildStrategy, c *conversion.Cloner) error {
if in.DockerStrategy != nil {
in, out := in.DockerStrategy, &out.DockerStrategy
*out = new(DockerBuildStrategy)
if err := DeepCopy_api_DockerBuildStrategy(*in, *out, c); err != nil {
return err
}
} else {
out.DockerStrategy = nil
}
if in.SourceStrategy != nil {
in, out := in.SourceStrategy, &out.SourceStrategy
*out = new(SourceBuildStrategy)
if err := DeepCopy_api_SourceBuildStrategy(*in, *out, c); err != nil {
return err
}
} else {
out.SourceStrategy = nil
}
if in.CustomStrategy != nil {
in, out := in.CustomStrategy, &out.CustomStrategy
*out = new(CustomBuildStrategy)
if err := DeepCopy_api_CustomBuildStrategy(*in, *out, c); err != nil {
return err
}
} else {
out.CustomStrategy = nil
}
if in.JenkinsPipelineStrategy != nil {
in, out := in.JenkinsPipelineStrategy, &out.JenkinsPipelineStrategy
*out = new(JenkinsPipelineBuildStrategy)
if err := DeepCopy_api_JenkinsPipelineBuildStrategy(*in, *out, c); err != nil {
return err
}
} else {
out.JenkinsPipelineStrategy = nil
}
return nil
}
func DeepCopy_api_BuildTriggerCause(in BuildTriggerCause, out *BuildTriggerCause, c *conversion.Cloner) error {
out.Message = in.Message
if in.GenericWebHook != nil {
in, out := in.GenericWebHook, &out.GenericWebHook
*out = new(GenericWebHookCause)
if err := DeepCopy_api_GenericWebHookCause(*in, *out, c); err != nil {
return err
}
} else {
out.GenericWebHook = nil
}
if in.GitHubWebHook != nil {
in, out := in.GitHubWebHook, &out.GitHubWebHook
*out = new(GitHubWebHookCause)
if err := DeepCopy_api_GitHubWebHookCause(*in, *out, c); err != nil {
return err
}
} else {
out.GitHubWebHook = nil
}
if in.ImageChangeBuild != nil {
in, out := in.ImageChangeBuild, &out.ImageChangeBuild
*out = new(ImageChangeCause)
if err := DeepCopy_api_ImageChangeCause(*in, *out, c); err != nil {
return err
}
} else {
out.ImageChangeBuild = nil
}
return nil
}
func DeepCopy_api_BuildTriggerPolicy(in BuildTriggerPolicy, out *BuildTriggerPolicy, c *conversion.Cloner) error {
out.Type = in.Type
if in.GitHubWebHook != nil {
in, out := in.GitHubWebHook, &out.GitHubWebHook
*out = new(WebHookTrigger)
if err := DeepCopy_api_WebHookTrigger(*in, *out, c); err != nil {
return err
}
} else {
out.GitHubWebHook = nil
}
if in.GenericWebHook != nil {
in, out := in.GenericWebHook, &out.GenericWebHook
*out = new(WebHookTrigger)
if err := DeepCopy_api_WebHookTrigger(*in, *out, c); err != nil {
return err
}
} else {
out.GenericWebHook = nil
}
if in.ImageChange != nil {
in, out := in.ImageChange, &out.ImageChange
*out = new(ImageChangeTrigger)
if err := DeepCopy_api_ImageChangeTrigger(*in, *out, c); err != nil {
return err
}
} else {
out.ImageChange = nil
}
return nil
}
func DeepCopy_api_CommonSpec(in CommonSpec, out *CommonSpec, c *conversion.Cloner) error {
out.ServiceAccount = in.ServiceAccount
if err := DeepCopy_api_BuildSource(in.Source, &out.Source, c); err != nil {
return err
}
if in.Revision != nil {
in, out := in.Revision, &out.Revision
*out = new(SourceRevision)
if err := DeepCopy_api_SourceRevision(*in, *out, c); err != nil {
return err
}
} else {
out.Revision = nil
}
if err := DeepCopy_api_BuildStrategy(in.Strategy, &out.Strategy, c); err != nil {
return err
}
if err := DeepCopy_api_BuildOutput(in.Output, &out.Output, c); err != nil {
return err
}
if err := api.DeepCopy_api_ResourceRequirements(in.Resources, &out.Resources, c); err != nil {
return err
}
if err := DeepCopy_api_BuildPostCommitSpec(in.PostCommit, &out.PostCommit, c); err != nil {
return err
}
if in.CompletionDeadlineSeconds != nil {
in, out := in.CompletionDeadlineSeconds, &out.CompletionDeadlineSeconds
*out = new(int64)
**out = *in
} else {
out.CompletionDeadlineSeconds = nil
}
return nil
}
func DeepCopy_api_CustomBuildStrategy(in CustomBuildStrategy, out *CustomBuildStrategy, c *conversion.Cloner) error {
if err := api.DeepCopy_api_ObjectReference(in.From, &out.From, c); err != nil {
return err
}
if in.PullSecret != nil {
in, out := in.PullSecret, &out.PullSecret
*out = new(api.LocalObjectReference)
if err := api.DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.PullSecret = nil
}
if in.Env != nil {
in, out := in.Env, &out.Env
*out = make([]api.EnvVar, len(in))
for i := range in {
if err := api.DeepCopy_api_EnvVar(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Env = nil
}
out.ExposeDockerSocket = in.ExposeDockerSocket
out.ForcePull = in.ForcePull
if in.Secrets != nil {
in, out := in.Secrets, &out.Secrets
*out = make([]SecretSpec, len(in))
for i := range in {
if err := DeepCopy_api_SecretSpec(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Secrets = nil
}
out.BuildAPIVersion = in.BuildAPIVersion
return nil
}
func DeepCopy_api_DockerBuildStrategy(in DockerBuildStrategy, out *DockerBuildStrategy, c *conversion.Cloner) error {
if in.From != nil {
in, out := in.From, &out.From
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.From = nil
}
if in.PullSecret != nil {
in, out := in.PullSecret, &out.PullSecret
*out = new(api.LocalObjectReference)
if err := api.DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.PullSecret = nil
}
out.NoCache = in.NoCache
if in.Env != nil {
in, out := in.Env, &out.Env
*out = make([]api.EnvVar, len(in))
for i := range in {
if err := api.DeepCopy_api_EnvVar(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Env = nil
}
out.ForcePull = in.ForcePull
out.DockerfilePath = in.DockerfilePath
return nil
}
func DeepCopy_api_GenericWebHookCause(in GenericWebHookCause, out *GenericWebHookCause, c *conversion.Cloner) error {
if in.Revision != nil {
in, out := in.Revision, &out.Revision
*out = new(SourceRevision)
if err := DeepCopy_api_SourceRevision(*in, *out, c); err != nil {
return err
}
} else {
out.Revision = nil
}
out.Secret = in.Secret
return nil
}
func DeepCopy_api_GenericWebHookEvent(in GenericWebHookEvent, out *GenericWebHookEvent, c *conversion.Cloner) error {
if in.Git != nil {
in, out := in.Git, &out.Git
*out = new(GitInfo)
if err := DeepCopy_api_GitInfo(*in, *out, c); err != nil {
return err
}
} else {
out.Git = nil
}
if in.Env != nil {
in, out := in.Env, &out.Env
*out = make([]api.EnvVar, len(in))
for i := range in {
if err := api.DeepCopy_api_EnvVar(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Env = nil
}
return nil
}
func DeepCopy_api_GitBuildSource(in GitBuildSource, out *GitBuildSource, c *conversion.Cloner) error {
out.URI = in.URI
out.Ref = in.Ref
if in.HTTPProxy != nil {
in, out := in.HTTPProxy, &out.HTTPProxy
*out = new(string)
**out = *in
} else {
out.HTTPProxy = nil
}
if in.HTTPSProxy != nil {
in, out := in.HTTPSProxy, &out.HTTPSProxy
*out = new(string)
**out = *in
} else {
out.HTTPSProxy = nil
}
return nil
}
func DeepCopy_api_GitHubWebHookCause(in GitHubWebHookCause, out *GitHubWebHookCause, c *conversion.Cloner) error {
if in.Revision != nil {
in, out := in.Revision, &out.Revision
*out = new(SourceRevision)
if err := DeepCopy_api_SourceRevision(*in, *out, c); err != nil {
return err
}
} else {
out.Revision = nil
}
out.Secret = in.Secret
return nil
}
func DeepCopy_api_GitInfo(in GitInfo, out *GitInfo, c *conversion.Cloner) error {
if err := DeepCopy_api_GitBuildSource(in.GitBuildSource, &out.GitBuildSource, c); err != nil {
return err
}
if err := DeepCopy_api_GitSourceRevision(in.GitSourceRevision, &out.GitSourceRevision, c); err != nil {
return err
}
if in.Refs != nil {
in, out := in.Refs, &out.Refs
*out = make([]GitRefInfo, len(in))
for i := range in {
if err := DeepCopy_api_GitRefInfo(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Refs = nil
}
return nil
}
func DeepCopy_api_GitRefInfo(in GitRefInfo, out *GitRefInfo, c *conversion.Cloner) error {
if err := DeepCopy_api_GitBuildSource(in.GitBuildSource, &out.GitBuildSource, c); err != nil {
return err
}
if err := DeepCopy_api_GitSourceRevision(in.GitSourceRevision, &out.GitSourceRevision, c); err != nil {
return err
}
return nil
}
func DeepCopy_api_GitSourceRevision(in GitSourceRevision, out *GitSourceRevision, c *conversion.Cloner) error {
out.Commit = in.Commit
if err := DeepCopy_api_SourceControlUser(in.Author, &out.Author, c); err != nil {
return err
}
if err := DeepCopy_api_SourceControlUser(in.Committer, &out.Committer, c); err != nil {
return err
}
out.Message = in.Message
return nil
}
func DeepCopy_api_ImageChangeCause(in ImageChangeCause, out *ImageChangeCause, c *conversion.Cloner) error {
out.ImageID = in.ImageID
if in.FromRef != nil {
in, out := in.FromRef, &out.FromRef
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.FromRef = nil
}
return nil
}
func DeepCopy_api_ImageChangeTrigger(in ImageChangeTrigger, out *ImageChangeTrigger, c *conversion.Cloner) error {
out.LastTriggeredImageID = in.LastTriggeredImageID
if in.From != nil {
in, out := in.From, &out.From
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.From = nil
}
return nil
}
func DeepCopy_api_ImageSource(in ImageSource, out *ImageSource, c *conversion.Cloner) error {
if err := api.DeepCopy_api_ObjectReference(in.From, &out.From, c); err != nil {
return err
}
if in.Paths != nil {
in, out := in.Paths, &out.Paths
*out = make([]ImageSourcePath, len(in))
for i := range in {
if err := DeepCopy_api_ImageSourcePath(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Paths = nil
}
if in.PullSecret != nil {
in, out := in.PullSecret, &out.PullSecret
*out = new(api.LocalObjectReference)
if err := api.DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.PullSecret = nil
}
return nil
}
func DeepCopy_api_ImageSourcePath(in ImageSourcePath, out *ImageSourcePath, c *conversion.Cloner) error {
out.SourcePath = in.SourcePath
out.DestinationDir = in.DestinationDir
return nil
}
func DeepCopy_api_JenkinsPipelineBuildStrategy(in JenkinsPipelineBuildStrategy, out *JenkinsPipelineBuildStrategy, c *conversion.Cloner) error {
out.JenkinsfilePath = in.JenkinsfilePath
out.Jenkinsfile = in.Jenkinsfile
return nil
}
func DeepCopy_api_SecretBuildSource(in SecretBuildSource, out *SecretBuildSource, c *conversion.Cloner) error {
if err := api.DeepCopy_api_LocalObjectReference(in.Secret, &out.Secret, c); err != nil {
return err
}
out.DestinationDir = in.DestinationDir
return nil
}
func DeepCopy_api_SecretSpec(in SecretSpec, out *SecretSpec, c *conversion.Cloner) error {
if err := api.DeepCopy_api_LocalObjectReference(in.SecretSource, &out.SecretSource, c); err != nil {
return err
}
out.MountPath = in.MountPath
return nil
}
func DeepCopy_api_SourceBuildStrategy(in SourceBuildStrategy, out *SourceBuildStrategy, c *conversion.Cloner) error {
if err := api.DeepCopy_api_ObjectReference(in.From, &out.From, c); err != nil {
return err
}
if in.PullSecret != nil {
in, out := in.PullSecret, &out.PullSecret
*out = new(api.LocalObjectReference)
if err := api.DeepCopy_api_LocalObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.PullSecret = nil
}
if in.Env != nil {
in, out := in.Env, &out.Env
*out = make([]api.EnvVar, len(in))
for i := range in {
if err := api.DeepCopy_api_EnvVar(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.Env = nil
}
out.Scripts = in.Scripts
if in.Incremental != nil {
in, out := in.Incremental, &out.Incremental
*out = new(bool)
**out = *in
} else {
out.Incremental = nil
}
out.ForcePull = in.ForcePull
if in.RuntimeImage != nil {
in, out := in.RuntimeImage, &out.RuntimeImage
*out = new(api.ObjectReference)
if err := api.DeepCopy_api_ObjectReference(*in, *out, c); err != nil {
return err
}
} else {
out.RuntimeImage = nil
}
if in.RuntimeArtifacts != nil {
in, out := in.RuntimeArtifacts, &out.RuntimeArtifacts
*out = make([]ImageSourcePath, len(in))
for i := range in {
if err := DeepCopy_api_ImageSourcePath(in[i], &(*out)[i], c); err != nil {
return err
}
}
} else {
out.RuntimeArtifacts = nil
}
return nil
}
func DeepCopy_api_SourceControlUser(in SourceControlUser, out *SourceControlUser, c *conversion.Cloner) error {
out.Name = in.Name
out.Email = in.Email
return nil
}
func DeepCopy_api_SourceRevision(in SourceRevision, out *SourceRevision, c *conversion.Cloner) error {
if in.Git != nil {
in, out := in.Git, &out.Git
*out = new(GitSourceRevision)
if err := DeepCopy_api_GitSourceRevision(*in, *out, c); err != nil {
return err
}
} else {
out.Git = nil
}
return nil
}
func DeepCopy_api_WebHookTrigger(in WebHookTrigger, out *WebHookTrigger, c *conversion.Cloner) error {
out.Secret = in.Secret
out.AllowEnv = in.AllowEnv
return nil
}
| {
"content_hash": "e959d69d138bea27c714d76c812aa6ca",
"timestamp": "",
"source": "github",
"line_count": 959,
"max_line_length": 144,
"avg_line_length": 27.008342022940564,
"alnum_prop": 0.6717115169298483,
"repo_name": "xenserverarmy/ose-scanner",
"id": "bfcf47af44a092e722166a06a6efc2b4a2b8f7d9",
"size": "26018",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "arbiter/vendor/github.com/openshift/origin/pkg/build/api/deep_copy_generated.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "152083"
},
{
"name": "Makefile",
"bytes": "5276"
},
{
"name": "Roff",
"bytes": "2082"
},
{
"name": "Shell",
"bytes": "23821"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="true"
android:weightSum="1"
android:nestedScrollingEnabled="false">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Discovery"
android:id="@+id/btn_discoverResource"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:baselineAligned="true"
android:layout_marginLeft="20dp"
android:id="@+id/layout_Security"
android:layout_marginRight="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/security_mode"
android:id="@+id/text_EnableSecurity"
android:phoneNumber="false"
android:textSize="16sp"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_Security"
android:layout_marginLeft="40dp"
android:layout_weight="0"
android:textOff="Disable"
android:textOn="Enable"
android:layout_marginTop="10dp" />
</LinearLayout>
</LinearLayout>
<View
android:layout_height="2dip"
android:background="#FF909090"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_Excution"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/easysetup_sequence"
android:id="@+id/textView22"
android:layout_marginLeft="10dp"
android:textSize="16sp" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:id="@+id/rg_EasysetupProcess"
android:layout_marginLeft="20dp">
<RadioButton
android:layout_width="160dp"
android:layout_height="32dp"
android:text="@string/securityprovisioning"
android:id="@+id/btn_configurSec"
android:checked="false"
android:textSize="12sp" />
<RadioButton
android:layout_width="160dp"
android:layout_height="32dp"
android:text="GetConfiguration"
android:id="@+id/btn_getConfiguration"
android:checked="false"
android:textSize="12sp" />
<RadioButton
android:layout_width="173dp"
android:layout_height="32dp"
android:text="ProvisionDeviceConfig"
android:id="@+id/btn_provisionDevConf"
android:textSize="12sp" />
<RadioButton
android:layout_width="160dp"
android:layout_height="32dp"
android:text="@string/cloudprovisioning"
android:id="@+id/btn_provisionCloudConf"
android:textSize="12sp" />
</RadioGroup>
</LinearLayout>
<View
android:layout_height="2dip"
android:background="#FF909090"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout_Infomation"
android:gravity="center_horizontal"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:id="@+id/layout_ConfigurSec"
android:layout_marginTop="10dp"
android:weightSum="1"
android:visibility="gone">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/security_provisioning_state"
android:id="@+id/textView10" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_secState"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="State"
android:id="@+id/textView12"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_secState" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout2"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="Device ID"
android:id="@+id/textView"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_secDevID" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="82dp"
android:layout_weight="0.64"></FrameLayout>
<Button
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="START"
android:id="@+id/btn_startConfigureSec"
android:layout_marginTop="10dp"
android:layout_gravity="bottom|right" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:id="@+id/layout_GetConfiguration"
android:layout_marginTop="10dp"
android:visibility="gone">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/enrollee_property_data"
android:id="@+id/textView4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="state : "
android:id="@+id/textView18"
android:layout_marginLeft="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="wait"
android:id="@+id/txt_getConfigurationState" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_devID"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="devID"
android:id="@+id/textView6"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_devID" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_devName"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="devName"
android:id="@+id/textView7"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_devName" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_modelNumber"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="modelNumber"
android:id="@+id/textView7"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_modelNumber" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_Language"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="language"
android:id="@+id/textView8"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_language" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_Country"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="country"
android:id="@+id/textView9"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_country" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_wifimode"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="wifi mode"
android:id="@+id/textView20"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_wifiMode" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_wififreq"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="wifi freq"
android:id="@+id/textView21"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_wifiFreq" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_coludAccessAble"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="CloudAccessable"
android:id="@+id/textView14"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="empty"
android:id="@+id/txt_cloudAccessable" />
</LinearLayout>
<Button
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="@string/start"
android:id="@+id/btn_startGetConfiguration"
android:layout_gravity="bottom|right" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:id="@+id/layout_ProvisionDevConf"
android:layout_marginTop="10dp"
android:visibility="gone">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/enroller_infomation"
android:id="@+id/textView_DataProvisioning" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="state : "
android:id="@+id/textView19"
android:layout_marginLeft="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="wait"
android:id="@+id/txt_provisionDevConfState" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_EnrollerSSID"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp">
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="@string/enroller_ssid"
android:id="@+id/txt_ssid"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_EnrollerSSID"
android:text="Test_SSID"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_EnrollerPW"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="Enter Enroller's PW"
android:id="@+id/txt_pass"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_EnrollerPW"
android:text="Test_PW"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_InputLanguage"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="language"
android:id="@+id/textView25"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_Language"
android:text="Test_Language"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_InputCountry"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="country"
android:id="@+id/textView23"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_Country"
android:text="Test_Country"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_InputLocation"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="location"
android:id="@+id/textView23"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_Location"
android:text="Test_Location"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_EnrollerAuthType"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="@string/select_enroller_authentication_type"
android:id="@+id/txt_authtype"
android:layout_gravity="center_vertical" />
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_authType"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical"
android:spinnerMode="dropdown" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_EnrollerEncType"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="@string/select_enroller_encription_type"
android:id="@+id/textView5"
android:layout_gravity="center_vertical" />
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner_encType"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical"
android:spinnerMode="dropdown" />
</LinearLayout>
<Button
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="START"
android:id="@+id/btn_startProvisionDevConf"
android:layout_marginTop="10dp"
android:layout_gravity="bottom|right" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:id="@+id/layout_ProvisionCloudConf"
android:layout_marginTop="10dp"
android:visibility="gone">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Cloud Information"
android:id="@+id/textView15" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="state : "
android:id="@+id/textView24"
android:layout_marginLeft="80dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="wait"
android:id="@+id/txt_provisionCloudConfState" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout11"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="Enter Target Cloud's Authcode"
android:id="@+id/textView16"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_authcode"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical"
android:text="authcode" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout12"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="Enter Target Cloud's AuthProvider"
android:id="@+id/textView17"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_authprovider"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical"
android:text="authprovider" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout"
android:weightSum="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" >
<TextView
android:layout_width="130dp"
android:layout_height="wrap_content"
android:text="Enter Target Cloud's Interface server"
android:id="@+id/textView3"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_ciserver"
android:layout_marginLeft="20dp"
android:layout_gravity="center_vertical"
android:text="coap+tcp://52.69.149.85:5683" />
</LinearLayout>
<Button
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="START"
android:id="@+id/btn_startProvisionCloudConf"
android:layout_marginTop="10dp"
android:layout_gravity="bottom|right" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout> | {
"content_hash": "40597a7b471da301106907b6956521c6",
"timestamp": "",
"source": "github",
"line_count": 807,
"max_line_length": 82,
"avg_line_length": 42.09293680297398,
"alnum_prop": 0.48017309900203126,
"repo_name": "JunhwanPark/TizenRT",
"id": "364f474b08484a52ae9a3da3f286847c664dd5b0",
"size": "33969",
"binary": false,
"copies": "1",
"ref": "refs/heads/artik",
"path": "external/iotivity/iotivity_1.2-rel/service/easy-setup/sampleapp/mediator/android/EasySetup/app/src/main/res/layout/easysetup_main.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "207231"
},
{
"name": "Batchfile",
"bytes": "39014"
},
{
"name": "C",
"bytes": "31851402"
},
{
"name": "C++",
"bytes": "488931"
},
{
"name": "HTML",
"bytes": "2149"
},
{
"name": "Makefile",
"bytes": "552482"
},
{
"name": "Objective-C",
"bytes": "236445"
},
{
"name": "Perl",
"bytes": "31096"
},
{
"name": "Python",
"bytes": "52227"
},
{
"name": "Shell",
"bytes": "145473"
},
{
"name": "Smarty",
"bytes": "15352"
},
{
"name": "Tcl",
"bytes": "787"
}
],
"symlink_target": ""
} |
layout: default
---
<div class="row">
<div class="large-12 columns content">
<h1 class="title">{% if page.title %}{{ page.title}}{% else %} MISSING PAGE TITLE {% endif; %}</h1>
{{content}}
</div>
</div>
{% include breadcrumbs.html %} | {
"content_hash": "1712cc4b23a4709cff4432b63e9c18f6",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 102,
"avg_line_length": 20.583333333333332,
"alnum_prop": 0.5951417004048583,
"repo_name": "jeffaustin81/simplicatedweb",
"id": "762a0f7764eab80b205692dc930b7df1f78a9623",
"size": "251",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_layouts/page-wide.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "611"
},
{
"name": "CSS",
"bytes": "53885"
},
{
"name": "HTML",
"bytes": "22573"
},
{
"name": "JavaScript",
"bytes": "322957"
},
{
"name": "PHP",
"bytes": "1264"
},
{
"name": "Ruby",
"bytes": "3567"
}
],
"symlink_target": ""
} |
Kubernetes Dashboard is a web-based user interface for Kubernetes clusters. It consists of multiple views like overview pages, list of resources and resource details pages. Much textual information is required within these elements. Let's consider sample dialog:

As you noticed there are a lot of different kinds of text messages in each view:
* Titles.
* Headers.
* Labels.
* Values.
* Tooltips.
* Action button.
* Menu and navigation entries.
* All kinds of messages including warnings, errors and help information.
For each one of them a developer has to make the following decisions:
* Grammar - Using a verb in infinitive or gerund form?
* Punctuation - Using a period or not?
* Capitalization - Using capitalized words? Capitalize Kubernetes specific names?
In addition, with few exceptions, all text messages within the Dashboard should be localized. For more details check our [internationalization guidelines](internationalization.md)).
## General terms
### Grammar
The gerund form should be used everywhere. Exceptions are all kinds of messages including warnings, errors and help information.
### Punctuation
Certain types of text resources should have punctuation. Periods should be used for
* All kinds of messages including warnings, errors and help information.
Periods should be avoided for:
* Headers.
* Titles.
* Labels.
* Values.
* Tooltips.
* Menu and navigation entries.
### Capitalization
In general, all kinds of messages should have their first word capitalized. Exceptions are:
* Names which appear in the middle of a message.
* Values and table contents.
Moreover, Kubernetes-specific names should be capitalized everywhere. This includes:
* Application names - Kubernetes, Kubernetes Dashboard etc.
* Resource names - Pod, Service, Endpoint, Node etc.
----
_Copyright 2019 [The Kubernetes Dashboard Authors](https://github.com/kubernetes/dashboard/graphs/contributors)_
| {
"content_hash": "f75de63a2f1e591983a09b8357b61cd8",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 262,
"avg_line_length": 34.06896551724138,
"alnum_prop": 0.7823886639676113,
"repo_name": "kubernetes/dashboard",
"id": "bc888d8ae6a0a7c56a4cc63c6bad30107fdd4a2d",
"size": "1996",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/developer/text-conventions.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "7104"
},
{
"name": "Go",
"bytes": "1250542"
},
{
"name": "HTML",
"bytes": "451845"
},
{
"name": "JavaScript",
"bytes": "3927"
},
{
"name": "Makefile",
"bytes": "17988"
},
{
"name": "SCSS",
"bytes": "67993"
},
{
"name": "Shell",
"bytes": "17925"
},
{
"name": "Smarty",
"bytes": "3598"
},
{
"name": "TypeScript",
"bytes": "846357"
}
],
"symlink_target": ""
} |
@class articleModel;
@interface articleTableViewCell : UITableViewCell
@property(nonatomic,strong)articleModel *model;
@end
| {
"content_hash": "8347796f26aa6b4eedf34abec9559e34",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 49,
"avg_line_length": 18.142857142857142,
"alnum_prop": 0.8188976377952756,
"repo_name": "Tyrannize/interesting",
"id": "e2239a067cc7343a5576a01d67d7a148746130c8",
"size": "292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "meteorDemo/meteorDemo/classes/文章/View/文章/articleTableViewCell.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "6504"
},
{
"name": "Objective-C",
"bytes": "62171"
}
],
"symlink_target": ""
} |
<?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>
<parent>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-parent</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../dropwizard-parent</relativePath>
</parent>
<artifactId>dropwizard-e2e</artifactId>
<name>Dropwizard End-to-end Tests</name>
<properties>
<!-- No need to deploy dropwizard-e2e -->
<maven.source.skip>true</maven.source.skip>
<maven.javadoc.skip>true</maven.javadoc.skip>
<maven.install.skip>true</maven.install.skip>
<maven.deploy.skip>true</maven.deploy.skip>
<maven.site.skip>true</maven.site.skip>
<maven.site.deploy.skip>true</maven.site.deploy.skip>
<skipNexusStagingDeployMojo>true</skipNexusStagingDeployMojo>
</properties>
<dependencies>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-testing</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-client</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-forms</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-jersey</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-logging</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-util</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-validation</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-views</artifactId>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-views-mustache</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-healthchecks</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
</dependency>
<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.ws.rs</groupId>
<artifactId>jakarta.ws.rs-api</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-io</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<id>enforce</id>
<configuration>
<rules>
<DependencyConvergence />
</rules>
</configuration>
<goals>
<goal>enforce</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>none</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
| {
"content_hash": "701256fdf5d12446a050943fef562e33",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 204,
"avg_line_length": 36.005494505494504,
"alnum_prop": 0.5409735998779185,
"repo_name": "micsta/dropwizard",
"id": "43bbdd370152d04caa00e8d75205b6d1902bc1c1",
"size": "6553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dropwizard-e2e/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "992"
},
{
"name": "HTML",
"bytes": "111"
},
{
"name": "Java",
"bytes": "2704084"
},
{
"name": "Mustache",
"bytes": "569"
},
{
"name": "Shell",
"bytes": "6214"
}
],
"symlink_target": ""
} |
package org.apache.gobblin.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.SeekableInput;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.mapred.FsInput;
import org.apache.avro.util.Utf8;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.codehaus.jackson.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Closer;
/**
* A Utils class for dealing with Avro objects
*/
public class AvroUtils {
private static final Logger LOG = LoggerFactory.getLogger(AvroUtils.class);
public static final String FIELD_LOCATION_DELIMITER = ".";
private static final String AVRO_SUFFIX = ".avro";
public static class AvroPathFilter implements PathFilter {
@Override
public boolean accept(Path path) {
return path.getName().endsWith(AVRO_SUFFIX);
}
}
/**
* Given a GenericRecord, this method will return the schema of the field specified by the path parameter. The
* fieldLocation parameter is an ordered string specifying the location of the nested field to retrieve. For example,
* field1.nestedField1 takes the the schema of the field "field1", and retrieves the schema "nestedField1" from it.
* @param schema is the record to retrieve the schema from
* @param fieldLocation is the location of the field
* @return the schema of the field
*/
public static Optional<Schema> getFieldSchema(Schema schema, String fieldLocation) {
Preconditions.checkNotNull(schema);
Preconditions.checkArgument(!Strings.isNullOrEmpty(fieldLocation));
Splitter splitter = Splitter.on(FIELD_LOCATION_DELIMITER).omitEmptyStrings().trimResults();
List<String> pathList = Lists.newArrayList(splitter.split(fieldLocation));
if (pathList.size() == 0) {
return Optional.absent();
}
return AvroUtils.getFieldSchemaHelper(schema, pathList, 0);
}
/**
* Helper method that does the actual work for {@link #getFieldSchema(Schema, String)}
* @param schema passed from {@link #getFieldSchema(Schema, String)}
* @param pathList passed from {@link #getFieldSchema(Schema, String)}
* @param field keeps track of the index used to access the list pathList
* @return the schema of the field
*/
private static Optional<Schema> getFieldSchemaHelper(Schema schema, List<String> pathList, int field) {
if (schema.getType() == Type.RECORD && schema.getField(pathList.get(field)) == null) {
return Optional.absent();
}
switch (schema.getType()) {
case UNION:
throw new AvroRuntimeException("Union of complex types cannot be handled : " + schema);
case MAP:
if ((field + 1) == pathList.size()) {
return Optional.fromNullable(schema.getValueType());
}
return AvroUtils.getFieldSchemaHelper(schema.getValueType(), pathList, ++field);
case RECORD:
if ((field + 1) == pathList.size()) {
return Optional.fromNullable(schema.getField(pathList.get(field)).schema());
}
return AvroUtils.getFieldSchemaHelper(schema.getField(pathList.get(field)).schema(), pathList, ++field);
default:
throw new AvroRuntimeException("Invalid type in schema : " + schema);
}
}
/**
* Given a GenericRecord, this method will return the field specified by the path parameter. The
* fieldLocation parameter is an ordered string specifying the location of the nested field to retrieve. For example,
* field1.nestedField1 takes field "field1", and retrieves "nestedField1" from it.
* @param schema is the record to retrieve the schema from
* @param fieldLocation is the location of the field
* @return the field
*/
public static Optional<Field> getField(Schema schema, String fieldLocation) {
Preconditions.checkNotNull(schema);
Preconditions.checkArgument(!Strings.isNullOrEmpty(fieldLocation));
Splitter splitter = Splitter.on(FIELD_LOCATION_DELIMITER).omitEmptyStrings().trimResults();
List<String> pathList = Lists.newArrayList(splitter.split(fieldLocation));
if (pathList.size() == 0) {
return Optional.absent();
}
return AvroUtils.getFieldHelper(schema, pathList, 0);
}
/**
* Helper method that does the actual work for {@link #getField(Schema, String)}
* @param schema passed from {@link #getFieldSchema(Schema, String)}
* @param pathList passed from {@link #getFieldSchema(Schema, String)}
* @param field keeps track of the index used to access the list pathList
* @return the field
*/
private static Optional<Field> getFieldHelper(Schema schema, List<String> pathList, int field) {
Field curField = schema.getField(pathList.get(field));
if (field + 1 == pathList.size()) {
return Optional.fromNullable(curField);
}
Schema fieldSchema = curField.schema();
switch (fieldSchema.getType()) {
case UNION:
throw new AvroRuntimeException("Union of complex types cannot be handled : " + schema);
case MAP:
return AvroUtils.getFieldHelper(fieldSchema.getValueType(), pathList, ++field);
case RECORD:
return AvroUtils.getFieldHelper(fieldSchema, pathList, ++field);
default:
throw new AvroRuntimeException("Invalid type in schema : " + schema);
}
}
/**
* Given a GenericRecord, this method will return the field specified by the path parameter. The fieldLocation
* parameter is an ordered string specifying the location of the nested field to retrieve. For example,
* field1.nestedField1 takes the the value of the field "field1", and retrieves the field "nestedField1" from it.
* @param record is the record to retrieve the field from
* @param fieldLocation is the location of the field
* @return the value of the field
*/
public static Optional<Object> getFieldValue(GenericRecord record, String fieldLocation) {
Map<String, Object> ret = getMultiFieldValue(record, fieldLocation);
return Optional.fromNullable(ret.get(fieldLocation));
}
public static Map<String, Object> getMultiFieldValue(GenericRecord record, String fieldLocation) {
Preconditions.checkNotNull(record);
Preconditions.checkArgument(!Strings.isNullOrEmpty(fieldLocation));
Splitter splitter = Splitter.on(FIELD_LOCATION_DELIMITER).omitEmptyStrings().trimResults();
List<String> pathList = splitter.splitToList(fieldLocation);
if (pathList.size() == 0) {
return Collections.emptyMap();
}
HashMap<String, Object> retVal = new HashMap<String, Object>();
AvroUtils.getFieldHelper(retVal, record, pathList, 0);
return retVal;
}
/**
* Helper method that does the actual work for {@link #getFieldValue(GenericRecord, String)}
* @param data passed from {@link #getFieldValue(GenericRecord, String)}
* @param pathList passed from {@link #getFieldValue(GenericRecord, String)}
* @param field keeps track of the index used to access the list pathList
* @return the value of the field
*/
private static void getFieldHelper(Map<String, Object> retVal,
Object data, List<String> pathList, int field) {
if (data == null) {
return;
}
if ((field + 1) == pathList.size()) {
Object val = null;
Joiner joiner = Joiner.on(".");
String key = joiner.join(pathList.iterator());
if (data instanceof Map) {
val = getObjectFromMap((Map)data, pathList.get(field));
} else if (data instanceof List) {
val = getObjectFromArray((List)data, Integer.parseInt(pathList.get(field)));
} else {
val = ((Record)data).get(pathList.get(field));
}
if (val != null) {
retVal.put(key, val);
}
return;
}
if (data instanceof Map) {
AvroUtils.getFieldHelper(retVal, getObjectFromMap((Map) data, pathList.get(field)), pathList, ++field);
return;
}
if (data instanceof List) {
if (pathList.get(field).trim().equals("*")) {
List arr = (List)data;
Iterator it = arr.iterator();
int i = 0;
while (it.hasNext()) {
Object val = it.next();
List<String> newPathList = new ArrayList<>(pathList);
newPathList.set(field, String.valueOf(i));
AvroUtils.getFieldHelper(retVal, val, newPathList, field + 1);
i++;
}
} else {
AvroUtils
.getFieldHelper(retVal, getObjectFromArray((List) data, Integer.parseInt(pathList.get(field))), pathList, ++field);
}
return;
}
AvroUtils.getFieldHelper(retVal, ((Record) data).get(pathList.get(field)), pathList, ++field);
return;
}
/**
* Given a map: key -> value, return a map: key.toString() -> value.toString(). Avro serializer wraps a String
* into {@link Utf8}. This method helps to restore the original string map object
*
* @param map a map object
* @return a map of strings
*/
@SuppressWarnings("unchecked")
public static Map<String, String> toStringMap(Object map) {
if (map == null) {
return null;
}
if (map instanceof Map) {
Map<Object, Object> rawMap = (Map<Object, Object>) map;
Map<String, String> stringMap = new HashMap<>();
for (Entry<Object, Object> entry : rawMap.entrySet()) {
stringMap.put(entry.getKey().toString(), entry.getValue().toString());
}
return stringMap;
} else {
throw new AvroRuntimeException("value must be a map");
}
}
/**
* This method is to get object from map given a key as string.
* Avro persists string as Utf8
* @param map passed from {@link #getFieldHelper(Map, Object, List, int)}
* @param key passed from {@link #getFieldHelper(Map, Object, List, int)}
* @return This could again be a GenericRecord
*/
private static Object getObjectFromMap(Map map, String key) {
Utf8 utf8Key = new Utf8(key);
return map.get(utf8Key);
}
/**
* Get an object from an array given an index.
*/
private static Object getObjectFromArray(List array, int index) {
return array.get(index);
}
/**
* Change the schema of an Avro record.
* @param record The Avro record whose schema is to be changed.
* @param newSchema The target schema. It must be compatible as reader schema with record.getSchema() as writer schema.
* @return a new Avro record with the new schema.
* @throws IOException if conversion failed.
*/
public static GenericRecord convertRecordSchema(GenericRecord record, Schema newSchema) throws IOException {
if (record.getSchema().equals(newSchema)) {
return record;
}
try {
BinaryDecoder decoder = new DecoderFactory().binaryDecoder(recordToByteArray(record), null);
DatumReader<GenericRecord> reader = new GenericDatumReader<>(record.getSchema(), newSchema);
return reader.read(null, decoder);
} catch (IOException e) {
throw new IOException(
String.format("Cannot convert avro record to new schema. Origianl schema = %s, new schema = %s",
record.getSchema(), newSchema),
e);
}
}
/**
* Convert a GenericRecord to a byte array.
*/
public static byte[] recordToByteArray(GenericRecord record) throws IOException {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Encoder encoder = EncoderFactory.get().directBinaryEncoder(out, null);
DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(record.getSchema());
writer.write(record, encoder);
byte[] byteArray = out.toByteArray();
return byteArray;
}
}
/**
* Get Avro schema from an Avro data file.
*/
public static Schema getSchemaFromDataFile(Path dataFile, FileSystem fs) throws IOException {
try (SeekableInput sin = new FsInput(dataFile, fs.getConf());
DataFileReader<GenericRecord> reader = new DataFileReader<>(sin, new GenericDatumReader<GenericRecord>())) {
return reader.getSchema();
}
}
/**
* Parse Avro schema from a schema file.
*/
public static Schema parseSchemaFromFile(Path filePath, FileSystem fs) throws IOException {
Preconditions.checkArgument(fs.exists(filePath), filePath + " does not exist");
try (InputStream in = fs.open(filePath)) {
return new Schema.Parser().parse(in);
}
}
public static void writeSchemaToFile(Schema schema, Path filePath, FileSystem fs, boolean overwrite)
throws IOException {
writeSchemaToFile(schema, filePath, fs, overwrite, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.READ));
}
public static void writeSchemaToFile(Schema schema, Path filePath, FileSystem fs, boolean overwrite, FsPermission perm)
throws IOException {
if (!overwrite) {
Preconditions.checkState(!fs.exists(filePath), filePath + " already exists");
} else {
HadoopUtils.deletePath(fs, filePath, true);
}
try (DataOutputStream dos = fs.create(filePath)) {
dos.writeChars(schema.toString());
}
fs.setPermission(filePath, perm);
}
/**
* Get the latest avro schema for a directory
* @param directory the input dir that contains avro files
* @param fs the {@link FileSystem} for the given directory.
* @param latest true to return latest schema, false to return oldest schema
* @return the latest/oldest schema in the directory
* @throws IOException
*/
public static Schema getDirectorySchema(Path directory, FileSystem fs, boolean latest) throws IOException {
Schema schema = null;
try (Closer closer = Closer.create()) {
List<FileStatus> files = getDirectorySchemaHelper(directory, fs);
if (files == null || files.size() == 0) {
LOG.warn("There is no previous avro file in the directory: " + directory);
} else {
FileStatus file = latest ? files.get(0) : files.get(files.size() - 1);
LOG.debug("Path to get the avro schema: " + file);
FsInput fi = new FsInput(file.getPath(), fs.getConf());
GenericDatumReader<GenericRecord> genReader = new GenericDatumReader<>();
schema = closer.register(new DataFileReader<>(fi, genReader)).getSchema();
}
} catch (IOException ioe) {
throw new IOException("Cannot get the schema for directory " + directory, ioe);
}
return schema;
}
/**
* Get the latest avro schema for a directory
* @param directory the input dir that contains avro files
* @param conf configuration
* @param latest true to return latest schema, false to return oldest schema
* @return the latest/oldest schema in the directory
* @throws IOException
*/
public static Schema getDirectorySchema(Path directory, Configuration conf, boolean latest) throws IOException {
return getDirectorySchema(directory, FileSystem.get(conf), latest);
}
private static List<FileStatus> getDirectorySchemaHelper(Path directory, FileSystem fs) throws IOException {
List<FileStatus> files = Lists.newArrayList();
if (fs.exists(directory)) {
getAllNestedAvroFiles(fs.getFileStatus(directory), files, fs);
if (files.size() > 0) {
Collections.sort(files, FileListUtils.LATEST_MOD_TIME_ORDER);
}
}
return files;
}
private static void getAllNestedAvroFiles(FileStatus dir, List<FileStatus> files, FileSystem fs) throws IOException {
if (dir.isDirectory()) {
FileStatus[] filesInDir = fs.listStatus(dir.getPath());
if (filesInDir != null) {
for (FileStatus f : filesInDir) {
getAllNestedAvroFiles(f, files, fs);
}
}
} else if (dir.getPath().getName().endsWith(AVRO_SUFFIX)) {
files.add(dir);
}
}
/**
* Merge oldSchema and newSchame. Set a field default value to null, if this field exists in the old schema but not in the new schema.
* @param oldSchema
* @param newSchema
* @return schema that contains all the fields in both old and new schema.
*/
public static Schema nullifyFieldsForSchemaMerge(Schema oldSchema, Schema newSchema) {
if (oldSchema == null) {
LOG.warn("No previous schema available, use the new schema instead.");
return newSchema;
}
if (!(oldSchema.getType().equals(Type.RECORD) && newSchema.getType().equals(Type.RECORD))) {
LOG.warn("Both previous schema and new schema need to be record type. Quit merging schema.");
return newSchema;
}
List<Field> combinedFields = Lists.newArrayList();
for (Field newFld : newSchema.getFields()) {
combinedFields.add(new Field(newFld.name(), newFld.schema(), newFld.doc(), newFld.defaultValue()));
}
for (Field oldFld : oldSchema.getFields()) {
if (newSchema.getField(oldFld.name()) == null) {
List<Schema> union = Lists.newArrayList();
Schema oldFldSchema = oldFld.schema();
if (oldFldSchema.getType().equals(Type.UNION)) {
union.add(Schema.create(Type.NULL));
for (Schema itemInUion : oldFldSchema.getTypes()) {
if (!itemInUion.getType().equals(Type.NULL)) {
union.add(itemInUion);
}
}
Schema newFldSchema = Schema.createUnion(union);
combinedFields.add(new Field(oldFld.name(), newFldSchema, oldFld.doc(), oldFld.defaultValue()));
} else {
union.add(Schema.create(Type.NULL));
union.add(oldFldSchema);
Schema newFldSchema = Schema.createUnion(union);
combinedFields.add(new Field(oldFld.name(), newFldSchema, oldFld.doc(), oldFld.defaultValue()));
}
}
}
Schema mergedSchema =
Schema.createRecord(newSchema.getName(), newSchema.getDoc(), newSchema.getNamespace(), newSchema.isError());
mergedSchema.setFields(combinedFields);
return mergedSchema;
}
/**
* Remove map, array, enum fields, as well as union fields that contain map, array or enum,
* from an Avro schema. A schema with these fields cannot be used as Mapper key in a
* MapReduce job.
*/
public static Optional<Schema> removeUncomparableFields(Schema schema) {
return removeUncomparableFields(schema, Sets.<Schema> newHashSet());
}
private static Optional<Schema> removeUncomparableFields(Schema schema, Set<Schema> processed) {
switch (schema.getType()) {
case RECORD:
return removeUncomparableFieldsFromRecord(schema, processed);
case UNION:
return removeUncomparableFieldsFromUnion(schema, processed);
case MAP:
return Optional.absent();
case ARRAY:
return Optional.absent();
case ENUM:
return Optional.absent();
default:
return Optional.of(schema);
}
}
private static Optional<Schema> removeUncomparableFieldsFromRecord(Schema record, Set<Schema> processed) {
Preconditions.checkArgument(record.getType() == Schema.Type.RECORD);
if (processed.contains(record)) {
return Optional.absent();
}
processed.add(record);
List<Field> fields = Lists.newArrayList();
for (Field field : record.getFields()) {
Optional<Schema> newFieldSchema = removeUncomparableFields(field.schema(), processed);
if (newFieldSchema.isPresent()) {
fields.add(new Field(field.name(), newFieldSchema.get(), field.doc(), field.defaultValue()));
}
}
Schema newSchema = Schema.createRecord(record.getName(), record.getDoc(), record.getNamespace(), false);
newSchema.setFields(fields);
return Optional.of(newSchema);
}
private static Optional<Schema> removeUncomparableFieldsFromUnion(Schema union, Set<Schema> processed) {
Preconditions.checkArgument(union.getType() == Schema.Type.UNION);
if (processed.contains(union)) {
return Optional.absent();
}
processed.add(union);
List<Schema> newUnion = Lists.newArrayList();
for (Schema unionType : union.getTypes()) {
Optional<Schema> newType = removeUncomparableFields(unionType, processed);
if (newType.isPresent()) {
newUnion.add(newType.get());
}
}
// Discard the union field if one or more types are removed from the union.
if (newUnion.size() != union.getTypes().size()) {
return Optional.absent();
}
return Optional.of(Schema.createUnion(newUnion));
}
/**
* Copies the input {@link org.apache.avro.Schema} but changes the schema name.
* @param schema {@link org.apache.avro.Schema} to copy.
* @param newName name for the copied {@link org.apache.avro.Schema}.
* @return A {@link org.apache.avro.Schema} that is a copy of schema, but has the name newName.
*/
public static Schema switchName(Schema schema, String newName) {
if (schema.getName().equals(newName)) {
return schema;
}
Schema newSchema = Schema.createRecord(newName, schema.getDoc(), schema.getNamespace(), schema.isError());
List<Field> fields = schema.getFields();
Iterable<Field> fieldsNew = Iterables.transform(fields, new Function<Field, Field>() {
@Override
public Schema.Field apply(Field input) {
//this should never happen but the API has marked input as Nullable
if (null == input) {
return null;
}
Field field = new Field(input.name(), input.schema(), input.doc(), input.defaultValue(), input.order());
return field;
}
});
newSchema.setFields(Lists.newArrayList(fieldsNew));
return newSchema;
}
/**
* Copies the input {@link org.apache.avro.Schema} but changes the schema namespace.
* @param schema {@link org.apache.avro.Schema} to copy.
* @param namespaceOverride namespace for the copied {@link org.apache.avro.Schema}.
* @return A {@link org.apache.avro.Schema} that is a copy of schema, but has the new namespace.
*/
public static Schema switchNamespace(Schema schema, Map<String, String> namespaceOverride) {
Schema newSchema;
String newNamespace = StringUtils.EMPTY;
// Process all Schema Types
// (Primitives are simply cloned)
switch (schema.getType()) {
case ENUM:
newNamespace = namespaceOverride.containsKey(schema.getNamespace()) ? namespaceOverride.get(schema.getNamespace())
: schema.getNamespace();
newSchema =
Schema.createEnum(schema.getName(), schema.getDoc(), newNamespace, schema.getEnumSymbols());
break;
case FIXED:
newNamespace = namespaceOverride.containsKey(schema.getNamespace()) ? namespaceOverride.get(schema.getNamespace())
: schema.getNamespace();
newSchema =
Schema.createFixed(schema.getName(), schema.getDoc(), newNamespace, schema.getFixedSize());
break;
case MAP:
newSchema = Schema.createMap(switchNamespace(schema.getValueType(), namespaceOverride));
break;
case RECORD:
newNamespace = namespaceOverride.containsKey(schema.getNamespace()) ? namespaceOverride.get(schema.getNamespace())
: schema.getNamespace();
List<Schema.Field> newFields = new ArrayList<>();
if (schema.getFields().size() > 0) {
for (Schema.Field oldField : schema.getFields()) {
Field newField = new Field(oldField.name(), switchNamespace(oldField.schema(), namespaceOverride), oldField.doc(),
oldField.defaultValue(), oldField.order());
newFields.add(newField);
}
}
newSchema = Schema.createRecord(schema.getName(), schema.getDoc(), newNamespace,
schema.isError());
newSchema.setFields(newFields);
break;
case UNION:
List<Schema> newUnionMembers = new ArrayList<>();
if (null != schema.getTypes() && schema.getTypes().size() > 0) {
for (Schema oldUnionMember : schema.getTypes()) {
newUnionMembers.add(switchNamespace(oldUnionMember, namespaceOverride));
}
}
newSchema = Schema.createUnion(newUnionMembers);
break;
case ARRAY:
newSchema = Schema.createArray(switchNamespace(schema.getElementType(), namespaceOverride));
break;
case BOOLEAN:
case BYTES:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case NULL:
case STRING:
newSchema = Schema.create(schema.getType());
break;
default:
String exceptionMessage = String.format("Schema namespace replacement failed for \"%s\" ", schema);
LOG.error(exceptionMessage);
throw new AvroRuntimeException(exceptionMessage);
}
// Copy schema metadata
copyProperties(schema, newSchema);
return newSchema;
}
/***
* Copy properties from old Avro Schema to new Avro Schema
* @param oldSchema Old Avro Schema to copy properties from
* @param newSchema New Avro Schema to copy properties to
*/
private static void copyProperties(Schema oldSchema, Schema newSchema) {
Preconditions.checkNotNull(oldSchema);
Preconditions.checkNotNull(newSchema);
Map<String, JsonNode> props = oldSchema.getJsonProps();
copyProperties(props, newSchema);
}
/***
* Copy properties to an Avro Schema
* @param props Properties to copy to Avro Schema
* @param schema Avro Schema to copy properties to
*/
private static void copyProperties(Map<String, JsonNode> props, Schema schema) {
Preconditions.checkNotNull(schema);
// (if null, don't copy but do not throw exception)
if (null != props) {
for (Map.Entry<String, JsonNode> prop : props.entrySet()) {
schema.addProp(prop.getKey(), prop.getValue());
}
}
}
/**
* Serialize a generic record as a relative {@link Path}. Useful for converting {@link GenericRecord} type keys
* into file system locations. For example {field1=v1, field2=v2} returns field1=v1/field2=v2 if includeFieldNames
* is true, or v1/v2 if it is false. Illegal HDFS tokens such as ':' and '\\' will be replaced with '_'.
* Additionally, parameter replacePathSeparators controls whether to replace path separators ('/') with '_'.
*
* @param record {@link GenericRecord} to serialize.
* @param includeFieldNames If true, each token in the path will be of the form key=value, otherwise, only the value
* will be included.
* @param replacePathSeparators If true, path separators ('/') in each token will be replaced with '_'.
* @return A relative path where each level is a field in the input record.
*/
public static Path serializeAsPath(GenericRecord record, boolean includeFieldNames, boolean replacePathSeparators) {
if (record == null) {
return new Path("");
}
List<String> tokens = Lists.newArrayList();
for (Schema.Field field : record.getSchema().getFields()) {
String sanitizedName = HadoopUtils.sanitizePath(field.name(), "_");
String sanitizedValue = HadoopUtils.sanitizePath(record.get(field.name()).toString(), "_");
if (replacePathSeparators) {
sanitizedName = sanitizedName.replaceAll(Path.SEPARATOR, "_");
sanitizedValue = sanitizedValue.replaceAll(Path.SEPARATOR, "_");
}
if (includeFieldNames) {
tokens.add(String.format("%s=%s", sanitizedName, sanitizedValue));
} else if (!Strings.isNullOrEmpty(sanitizedValue)) {
tokens.add(sanitizedValue);
}
}
return new Path(Joiner.on(Path.SEPARATOR).join(tokens));
}
/**
* Deserialize a {@link GenericRecord} from a byte array. This method is not intended for high performance.
*/
public static GenericRecord slowDeserializeGenericRecord(byte[] serializedRecord, Schema schema) throws IOException {
Decoder decoder = DecoderFactory.get().binaryDecoder(serializedRecord, null);
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
return reader.read(null, decoder);
}
}
| {
"content_hash": "c9e539cf37513e16519f99c0944de2e4",
"timestamp": "",
"source": "github",
"line_count": 749,
"max_line_length": 136,
"avg_line_length": 39.134846461949266,
"alnum_prop": 0.6847366266375546,
"repo_name": "pcadabam/gobblin",
"id": "d09a6d9c9e80de080e171f2a600e2b2311603f26",
"size": "30112",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "40"
},
{
"name": "CSS",
"bytes": "14588"
},
{
"name": "Groovy",
"bytes": "2273"
},
{
"name": "HTML",
"bytes": "13792"
},
{
"name": "Java",
"bytes": "12052308"
},
{
"name": "JavaScript",
"bytes": "42618"
},
{
"name": "PLSQL",
"bytes": "749"
},
{
"name": "Python",
"bytes": "46478"
},
{
"name": "Roff",
"bytes": "202"
},
{
"name": "Shell",
"bytes": "63889"
},
{
"name": "XSLT",
"bytes": "3081"
}
],
"symlink_target": ""
} |
"""
This module contains a collection of models that implement a simple function:
:func:`~revscoring.ScorerModel.score`. Currently, all models are
a subclass of :class:`revscoring.scorer_models.MLScorerModel`
which means that they also implement
:meth:`~revscoring.scorer_models.MLScorerModel.train` and
:meth:`~revscoring.scorer_models.MLScorerModel.test` methods. See
:mod:`revscoring.scorer_models.statistics` for stats that can be applied to
models.
Support Vector Classifiers
++++++++++++++++++++++++++
.. automodule:: revscoring.scorer_models.svc
Naive Bayes Classifiers
+++++++++++++++++++++++
.. automodule:: revscoring.scorer_models.nb
Random Forest
+++++++++++++
.. automodule:: revscoring.scorer_models.rf
Gradient Boosting
+++++++++++++++++
.. automodule:: revscoring.scorer_models.gradient_boosting
Abstract classes
++++++++++++++++
.. automodule:: revscoring.scorer_models.scorer_model
"""
from .svc import SVC, LinearSVC, RBFSVC
from .gradient_boosting import GradientBoosting
from .nb import NB, GaussianNB, MultinomialNB, BernoulliNB
from .scorer_model import ScorerModel, MLScorerModel
from .sklearn_classifier import ScikitLearnClassifier
from .rf import RF
__all__ = [
SVC, LinearSVC, RBFSVC, NB, GaussianNB, MultinomialNB, BernoulliNB,
ScorerModel, MLScorerModel, ScikitLearnClassifier, RF, GradientBoosting
]
| {
"content_hash": "9a9d0ac51945089a85a2e2aae472757c",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 77,
"avg_line_length": 30.681818181818183,
"alnum_prop": 0.737037037037037,
"repo_name": "yafeunteun/wikipedia-spam-classifier",
"id": "31e30f44d75b818ffb8e7d992df84584408d8dc3",
"size": "1350",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "revscoring/revscoring/scorer_models/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7262"
},
{
"name": "Jupyter Notebook",
"bytes": "971575"
},
{
"name": "Makefile",
"bytes": "7446"
},
{
"name": "Python",
"bytes": "796831"
},
{
"name": "Shell",
"bytes": "132"
}
],
"symlink_target": ""
} |
using UnityEngine;
public class DemoOwnershipGui : MonoBehaviour
{
public GUISkin Skin;
public bool TransferOwnershipOnRequest = true;
public void OnOwnershipRequest(object[] viewAndPlayer)
{
PhotonView view = viewAndPlayer[0] as PhotonView;
PhotonPlayer requestingPlayer = viewAndPlayer[1] as PhotonPlayer;
Debug.Log("OnOwnershipRequest(): Player " + requestingPlayer + " requests ownership of: " + view + ".");
if (this.TransferOwnershipOnRequest)
{
view.TransferOwnership(requestingPlayer.ID);
}
}
#region Unity
public void OnGUI()
{
GUI.skin = this.Skin;
GUILayout.BeginArea(new Rect(Screen.width - 200, 0, 200, Screen.height));
{
string label = TransferOwnershipOnRequest ? "passing objects" : "rejecting to pass";
if (GUILayout.Button(label))
{
this.TransferOwnershipOnRequest = !this.TransferOwnershipOnRequest;
}
}
GUILayout.EndArea();
if (PhotonNetwork.inRoom)
{
int playerNr = PhotonNetwork.player.ID;
string playerIsMaster = PhotonNetwork.player.IsMasterClient ? "(master) " : "";
string playerColor = PlayerVariables.GetColorName(PhotonNetwork.player.ID);
GUILayout.Label(string.Format("player {0}, {1} {2}(you)", playerNr, playerColor, playerIsMaster));
foreach (PhotonPlayer otherPlayer in PhotonNetwork.otherPlayers)
{
playerNr = otherPlayer.ID;
playerIsMaster = otherPlayer.IsMasterClient ? "(master)" : "";
playerColor = PlayerVariables.GetColorName(otherPlayer.ID);
GUILayout.Label(string.Format("player {0}, {1} {2}", playerNr, playerColor, playerIsMaster));
}
if (PhotonNetwork.inRoom && PhotonNetwork.otherPlayers.Length == 0)
{
GUILayout.Label("Join more clients to switch object-control.");
}
}
else
{
GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
}
}
#endregion
} | {
"content_hash": "be5c4d794f4969f302beb1241020fdbe",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 112,
"avg_line_length": 34.6,
"alnum_prop": 0.5878168074699867,
"repo_name": "googlearchive/tango-examples-unity",
"id": "958787c61595498d754e43d5e1dda5ff7f2d30d9",
"size": "2251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TangoWithMultiplayer/Assets/Photon Unity Networking/Demos/DemoChangeOwner/DemoOwnershipGui.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "5858349"
},
{
"name": "GLSL",
"bytes": "3996"
},
{
"name": "HLSL",
"bytes": "20068"
},
{
"name": "Java",
"bytes": "21381"
},
{
"name": "Mask",
"bytes": "305"
},
{
"name": "Objective-C",
"bytes": "1433"
},
{
"name": "Objective-C++",
"bytes": "2960"
},
{
"name": "ShaderLab",
"bytes": "145277"
},
{
"name": "Shell",
"bytes": "360"
}
],
"symlink_target": ""
} |
/*************************************************************************
** **
** Description **
** **
** This module deals with I/O of ASCII files in GAMMA. Although GAMMA **
** data types often come with the ability to read themselves from set **
** parameter files (ASCII files in GAMMA parameter format), often one **
** needs to input a set of values (int, double, string, ....) that **
** control program function but have nothing to do with GAMMA objects. **
** These functions simplify that process by allowing flexible parsing **
** of ASCII files. **
** **
*************************************************************************/
#ifndef Gamascii_h_ // Is file already included?
# define Gamascii_h_ 1 // If no, then remember it
# if defined(GAMPRAGMA) // Using the GNU compiler?
# pragma interface // This is the interface
# endif
#include <GamGen.h> // Know MSVCDLL (__declspec)
#include <string> // Know about libstdc++ strings
#include <Matrix/row_vector.h> // Know about row_vectors
// __________________________________________________________________________________
// i ASCII File I/O Error Functions
// __________________________________________________________________________________
void ASCIIerr(int eidx, int noret=0);
// Input eidx : Flag for error type
// noret : Flag for return (0=return)
// Output none : Error message
void ASCIIdie(int eidx);
// Input eidx : Flag for error type
// noret : Flag for return (0=return)
// Output none : Error message
void ASCIIerr(int eidx, const std::string& pname, int noret=0);
// Input eidx : Flag for error type
// pname : string included in message
// noret : Flag for return (0=return)
// Output none : Error message
// __________________________________________________________________________________
// A ASCII File Reading & Parsing
// __________________________________________________________________________________
// ----------------------------------------------------------------------------------
// I/O To Obtain strings From An ASCII File
// ----------------------------------------------------------------------------------
MSVCDLL std::string* Getstrings(const std::string& filename, int& N);
// Input filename: ASCII input file name
// N : Number of strings
// Return Svect : A string vector is filled with names
// found in the file "filename"
// Value of N is set to # strings found
// Note : Assumes file contains 1 name per
// line
// ----------------------------------------------------------------------------------
// I/O To Obtain Doubles From An ASCII File
// ----------------------------------------------------------------------------------
MSVCDLL double* GetDoubles(const std::string& filename, int& N);
// Input filename: ASCII input file name
// N : Number of doubles
// Return Dvect : A double vector is filled with values
// found in the file "filename"
// Value of N is set to # doubles found
// Note : Assumes file contains 1 value per line
MSVCDLL row_vector GetDoubles(const std::string& filename);
// Input filename: ASCII input file name
// Return data : A vector is filled with values
// found in the file "filename"
MSVCDLL void vxread(const std::string& filename, row_vector& vx);
// Input filename : ASCII input file name
// vx : A row vector
// Return none : vx is filled with data in
// file "filename"
// __________________________________________________________________________________
// G ASCII File Auxiliary Functions
// __________________________________________________________________________________
MSVCDLL void ASCIItell(const std::string& filename, int verbose=0);
// Input filename : ASCII input file name
// vebose : Flag how much info to output
// Return none : The ASCII file is probed to determine
// what type of information it contains
MSVCDLL int LineCount(const std::string& filename);
// Input filename : ASCII input file name
// Return int : The nubmer of lines in the ASCII file
// named filename
#endif // Gascii.h
| {
"content_hash": "ea3903344d741449ab1bc211f957a235",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 85,
"avg_line_length": 42.145161290322584,
"alnum_prop": 0.4050899349406812,
"repo_name": "tesch1/GAMMA",
"id": "e6392e12125bba0b506493b6038b5255b6790b9a",
"size": "5751",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/GamIO/Gascii.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "923133"
},
{
"name": "C++",
"bytes": "11254062"
},
{
"name": "M",
"bytes": "693"
},
{
"name": "Makefile",
"bytes": "539168"
},
{
"name": "Matlab",
"bytes": "4779"
},
{
"name": "Objective-C",
"bytes": "9244"
},
{
"name": "Python",
"bytes": "43687"
},
{
"name": "Shell",
"bytes": "41354"
}
],
"symlink_target": ""
} |
node.default['tomcat']['s3_webapp_path'] = "s3://devopstraining"
node.default['tomcat']['s3_webapp_development'] = "15"
node.default['tomcat']['s3_webapp_production'] = "1"
| {
"content_hash": "2b6f39b96658f629a84b6f02ce741f30",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 64,
"avg_line_length": 57.666666666666664,
"alnum_prop": 0.6878612716763006,
"repo_name": "upendar82/chef-repo",
"id": "55acc8dc95541281a76d3af4434e159c147e49a9",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cookbooks/tomcat/attributes/default.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "367"
},
{
"name": "Ruby",
"bytes": "2922"
}
],
"symlink_target": ""
} |
Archive
=======
Provides functions to create, list, and extract archives.
Functions
---------
- `archive` creates an archive based on the provided archive name.
- `lsarchive` lists the contents of one or more archives.
- `unarchive` extracts the contents of one or more archives.
Supported Formats
-----------------
The following archive formats are supported when the required utilities are
installed:
- *.tar.gz*, *.tgz* require `tar` (optionally `pigz`).
- *.tar.bz2*, *.tbz* require `tar` (optionally `pbzip2`).
- *.tar.xz*, *.txz* require `tar` with *xz* support.
- *.tar.zma*, *.tlz* require `tar` with *lzma* support.
- *.tar* requires `tar`.
- *.gz* requires `gunzip`.
- *.bz2* requires `bunzip2`.
- *.xz* requires `unxz`.
- *.lzma* requires `unlzma`.
- *.Z* requires `uncompress`.
- *.zip*, *.jar* requires `unzip`.
- *.rar* requires `unrar` or `rar`.
- *.7z* requires `7za`.
- *.deb* requires `ar`, `tar`.
Additionally, if `pigz` and/or `pbzip2` are installed, `archive` will use them over
their traditional counterparts, `gzip` and `bzip2` respectively, to take full advantage
of all available CPU cores for compression.
Authors
-------
*The authors of this module should be contacted via the [issue tracker][1].*
- [Sorin Ionescu](https://github.com/sorin-ionescu)
- [Matt Hamilton](https://github.com/Eriner)
[1]: https://github.com/sorin-ionescu/prezto/issues
| {
"content_hash": "f06373812cdafec015eb43a1f289ebde",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 87,
"avg_line_length": 30.934782608695652,
"alnum_prop": 0.6605762473647224,
"repo_name": "und3rdg/zsh",
"id": "6df58d86e823253d5123a7cb2331eed216ebbe76",
"size": "1423",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/archive/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6499"
},
{
"name": "PowerShell",
"bytes": "1386"
},
{
"name": "Shell",
"bytes": "98419"
},
{
"name": "Vim script",
"bytes": "1253"
}
],
"symlink_target": ""
} |
package org.kale.dkim
import java.io.InputStream
import java.security.{MessageDigest, Signature}
import javax.mail.internet.MimeMessage
import org.apache.logging.log4j.LogManager
import org.kale.dkim.DkimVerifier.HeaderStack
import sun.misc.{BASE64Decoder, BASE64Encoder}
import scala.collection.JavaConverters._
import scala.collection.mutable
case class Body(bytes: Array[Byte], length: Int)
// Want this to mimic an Option that has extra information
case class DkimResult(description: String, // Error message, if any goes here
valid: Boolean,
dkim: DkimSignature = DkimSignature.empty) { // Dkim Signature record goes here on success
def isDefined() = valid
def get = dkim
}
case class Header(key: String, value: String, line: String) {
val keyl = key.trim.toLowerCase
}
object DkimVerifier {
case class Body(bytes: Array[Byte], length: Int)
import DkimSignature._
val logger = LogManager.getLogger(getClass)
type HeaderStack = Map[String, mutable.Stack[Header]]
/**
* Do full DKIM verification of both the email headers and body
*
* @param email JavaMail email
* @param dnsHelper (optional) This enables us to query DNS records
*/
def verify(email: MimeMessage, dnsHelper: DnsHelper): DkimResult = {
val headerResult = verifyOnlyHeaders(email, dnsHelper)
if (!headerResult.isDefined())
return headerResult
if (verifyBody(email, headerResult.dkim))
headerResult
else
new DkimResult("Body hash did not match", false, headerResult.dkim)
}
/**
* Verify just the headers -- don't do the body yet
*/
def verifyOnlyHeaders(email: MimeMessage, dnsHelper: DnsHelper): DkimResult = {
val headers = email.getAllHeaderLines.asScala.asInstanceOf[Iterator[String]]
verifyHeadersIterator(headers, dnsHelper)
}
def verifyHeadersIterator(headers: Iterator[String], dnsHelper: DnsHelper): DkimResult = {
val headerStacks = buildHeaderStacks(headers)
val dkim = getDkim(headerStacks)
if (dkim.isEmpty)
return new DkimResult("No valid dkim header found", false)
val verifier = new DkimVerifier(dkim.get,headerStacks, dnsHelper)
verifier.verifyHeaders()
}
def hasCRLF(bytes: Array[Byte], index: Int) = {
if (index + 1 > bytes.length || index < 0)
false
else
bytes(index) == '\r' && bytes(index + 1) == '\n'
}
def simpleBodyFormat(is: InputStream, buffer: Array[Byte], length: Int): Int = {
var byte: Int = is.read()
var count = 0
while ( (count < length) && (byte != -1)) {
buffer(count) = byte.toByte
count += 1
byte = is.read()
}
count
}
def verifyBody(email: MimeMessage, dkim: DkimSignature): Boolean = {
var length: Int = if (dkim.bodyLength > 0) dkim.bodyLength else email.getSize
val body = new Array[Byte](length + 2)
//
// Pull in the body, using a single pass
//
if (dkim.bodyCanonicalization == DkimSignature.Relaxed)
length = relaxedBodyFormat(email.getRawInputStream, body, length)
else
length = simpleBodyFormat(email.getRawInputStream, body, length)
// Ensure that the body has a CRLF at the end
if(!hasCRLF(body, length -2)){
body(length) = '\r'
body(length+1) = '\n'
length += 2
}
// Remove any duplicate CRLF's at the end
length = ignoreExtraEndLines(body, length)
// Create hash and compare it
val digest = getHash(body, length, dkim.getMethodDigestAlgorithm)
digest == dkim.bodyHash
}
def ignoreExtraEndLines(bytes: Array[Byte], end: Int): Int = {
var i = end
while ( hasCRLF(bytes, i -4)) {
i -= 2
}
i
}
def getHash(bytes: Array[Byte], length: Int, method: String): String = {
val md: MessageDigest = MessageDigest.getInstance(method)
md.update(bytes, 0, length)
val bsenc: BASE64Encoder = new BASE64Encoder
bsenc.encode(md.digest)
}
def removeTab(ch: Int) = if (ch == '\t') ' '.toInt else ch
/**
* Put the message body into relaxed format.
*
* Message bodies can be potentially quite large so for efficiency we want to do this running through
* the body just one time
*/
def relaxedBodyFormat(is: InputStream, bytes: Array[Byte], length: Int): Int = {
var outCount = 0
var current = removeTab(is.read())
while(current >= 0 && outCount < length){
val next = removeTab(is.read())
if (current != ' ' || !(next == ' ' || next == '\r')){
bytes(outCount) = current.toByte
outCount += 1
}
current = next
}
outCount
}
/**
* An email might have multiple dkim signatures. For example, it is possible in the future
* that an email will be signed with multiple dkim versions
*
* Return the first dkim signature that we recognize as valid
*/
def getDkim(headerStacks: HeaderStack): Option[DkimSignature] = {
val stack = headerStacks.get(DkimHeader.toLowerCase)
if (stack.isEmpty)
return None
val headers = stack.get.toIterable.map{header => DkimSignature.create(header.value)}
headers.find(dimResult => dimResult.isDefined()).map(_.get)
}
/**
* Handle duplicate header values using a stack (as called for by the DKIM RFC)
*/
def buildHeaderStacks(headers: Iterator[String]): HeaderStack= {
var map = Map[String, mutable.Stack[Header]]()
for( line <- headers; header <- parseHeader(line)) {
if (!map.contains(header.keyl)) {
val stack = new mutable.Stack[Header]
stack.push(header)
map += (header.keyl -> stack)
} else {
val stack = map.get(header.keyl).get
stack.push(header)
}
}
map
}
private def parseHeader(text : String): Option[Header] = {
if (text == null || text.isEmpty)
return None
val parts = text.split(":", 2)
if (parts.length != 2 || parts(0).isEmpty)
return None
val header = Header(parts(0), parts(1), text)
Some(header)
}
/** DKIM RFC relax header canonicalization
* NOTE: For simplicity, we just always remove CRLF's rather than do the "unfolding" that might possibly leave some
* CRLF's intact
*/
def relaxedHeaderFormat(input: String): String = {
val line = input.replaceAll("[\r\n\t ]+", " ")
line.replaceAll("(?m)[ ]+$", "") // remove all whitespace at end of line
}
}
/**
* Verify an email dkim signature
*
* Code is based on RFC 6376
* https://tools.ietf.org/html/rfc6376
*
* comments about the "rfc" are referring to this RFC 6376
*
* @param headerStacks header, with multiple headers with the same key stored in stacks
* @param dnsHelper used to get the public key from the dns host specified in the dkim header
*
*/
class DkimVerifier(dkim: DkimSignature, headerStacks: HeaderStack, dnsHelper: DnsHelper = new DnsHelper) {
import DkimSignature.{DkimHeader, Relaxed}
import DkimVerifier._
def verifyHeaders(): DkimResult = {
try {
val dnsLookup = new DkimDnsLookup(dnsHelper)
val publicKey = dnsLookup.getPublicKey(dkim.dnsRecord)
val dkimHeaderText = getSignatureText()
logger.debug(s"headerText:\n$dkimHeaderText")
val bs: BASE64Decoder = new BASE64Decoder
val sigBuf: Array[Byte] = bs.decodeBuffer(dkim.signature)
val sig = Signature.getInstance(dkim.getSignatureAlgorithm)
sig.initVerify(publicKey)
sig.update(dkimHeaderText.getBytes())
val result = sig.verify(sigBuf)
logger.debug(s"RESULT: $result domain: ${dkim.domain}")
if (result)
new DkimResult("Success", true, dkim)
else{
logger.debug(s"signature: ${dkim.rawSignature}")
new DkimResult("Headers signature did not validate", false, dkim)
}
} catch {
case t: Throwable => logger.debug("verifyHost error", t); new DkimResult(t.getMessage, false, dkim)
}
}
/**
* Produce the header text as specified by the rfc
*/
def getSignatureText(): String = {
val headers = dkim.headerArray
// Add each requested header to our text
var result: String = ""
headers.foreach{ headerName =>
val header = headerStacks.get(headerName.toLowerCase).flatMap(safePop)
if (header.isDefined)
result += processHeader(header.get, dkim.headerCanonicalization) + "\r\n"
}
// Add the dkim header at the end (we have to remove the signature field (b=...) )
val dkimRaw = getHeader(DkimHeader)
val dkimHeader = Header(dkimRaw.key, processDKimHeader(dkimRaw.value), processDKimHeader(dkimRaw.line))
result + processHeader(dkimHeader, dkim.headerCanonicalization)
}
/**
* When verifying, we need the original dkim signature, but with the b tag nulled out
*/
private def processDKimHeader(text: String): String = {
text.replaceAll("b=[^;]*", "b=")
}
private def safePop(stack: mutable.Stack[Header]): Option[Header] = {
if (stack.isEmpty) None else Some(stack.pop())
}
private def getHeader(header: String): Header = {
val result = headerStacks.get(header.toLowerCase).flatMap(safePop)
result.getOrElse(Header(header, "", header + ":"))
}
private def processHeader(header: Header, method: String): String = {
if (method == Relaxed) {
relaxedHeaderFormat(header.keyl + ":" + header.value.trim())
}else {
header.line
}
}
}
| {
"content_hash": "a72b2fded150a0b40c2cb3fd239da8f5",
"timestamp": "",
"source": "github",
"line_count": 343,
"max_line_length": 118,
"avg_line_length": 27.37609329446064,
"alnum_prop": 0.6594249201277955,
"repo_name": "OdysseusLevy/kale",
"id": "9ebe8f70518c1086b835a3e03b0277d2d9ddac28",
"size": "9390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dkim/src/main/scala/org/kale/dkim/DkimVerifier.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Kotlin",
"bytes": "51925"
},
{
"name": "Scala",
"bytes": "29530"
}
],
"symlink_target": ""
} |
package gce
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/GoogleCloudPlatform/k8s-cloud-provider/pkg/cloud"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
apiservice "k8s.io/kubernetes/pkg/api/v1/service"
netsets "k8s.io/kubernetes/pkg/util/net/sets"
computealpha "google.golang.org/api/compute/v0.alpha"
compute "google.golang.org/api/compute/v1"
"k8s.io/klog"
)
// ensureExternalLoadBalancer is the external implementation of LoadBalancer.EnsureLoadBalancer.
// Our load balancers in GCE consist of four separate GCE resources - a static
// IP address, a firewall rule, a target pool, and a forwarding rule. This
// function has to manage all of them.
//
// Due to an interesting series of design decisions, this handles both creating
// new load balancers and updating existing load balancers, recognizing when
// each is needed.
func (g *Cloud) ensureExternalLoadBalancer(clusterName string, clusterID string, apiService *v1.Service, existingFwdRule *compute.ForwardingRule, nodes []*v1.Node) (*v1.LoadBalancerStatus, error) {
if len(nodes) == 0 {
return nil, fmt.Errorf("Cannot EnsureLoadBalancer() with no hosts")
}
hostNames := nodeNames(nodes)
supportsNodesHealthCheck := supportsNodesHealthCheck(nodes)
hosts, err := g.getInstancesByNames(hostNames)
if err != nil {
return nil, err
}
loadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, apiService)
requestedIP := apiService.Spec.LoadBalancerIP
ports := apiService.Spec.Ports
portStr := []string{}
for _, p := range apiService.Spec.Ports {
portStr = append(portStr, fmt.Sprintf("%s/%d", p.Protocol, p.Port))
}
serviceName := types.NamespacedName{Namespace: apiService.Namespace, Name: apiService.Name}
lbRefStr := fmt.Sprintf("%v(%v)", loadBalancerName, serviceName)
klog.V(2).Infof("ensureExternalLoadBalancer(%s, %v, %v, %v, %v, %v)", lbRefStr, g.region, requestedIP, portStr, hostNames, apiService.Annotations)
// Check the current and the desired network tiers. If they do not match,
// tear down the existing resources with the wrong tier.
netTier, err := g.getServiceNetworkTier(apiService)
if err != nil {
klog.Errorf("ensureExternalLoadBalancer(%s): Failed to get the desired network tier: %v.", lbRefStr, err)
return nil, err
}
klog.V(4).Infof("ensureExternalLoadBalancer(%s): Desired network tier %q.", lbRefStr, netTier)
if g.AlphaFeatureGate.Enabled(AlphaFeatureNetworkTiers) {
g.deleteWrongNetworkTieredResources(loadBalancerName, lbRefStr, netTier)
}
// Check if the forwarding rule exists, and if so, what its IP is.
fwdRuleExists, fwdRuleNeedsUpdate, fwdRuleIP, err := g.forwardingRuleNeedsUpdate(loadBalancerName, g.region, requestedIP, ports)
if err != nil {
return nil, err
}
if !fwdRuleExists {
klog.V(2).Infof("ensureExternalLoadBalancer(%s): Forwarding rule %v doesn't exist.", lbRefStr, loadBalancerName)
}
// Make sure we know which IP address will be used and have properly reserved
// it as static before moving forward with the rest of our operations.
//
// We use static IP addresses when updating a load balancer to ensure that we
// can replace the load balancer's other components without changing the
// address its service is reachable on. We do it this way rather than always
// keeping the static IP around even though this is more complicated because
// it makes it less likely that we'll run into quota issues. Only 7 static
// IP addresses are allowed per region by default.
//
// We could let an IP be allocated for us when the forwarding rule is created,
// but we need the IP to set up the firewall rule, and we want to keep the
// forwarding rule creation as the last thing that needs to be done in this
// function in order to maintain the invariant that "if the forwarding rule
// exists, the LB has been fully created".
ipAddressToUse := ""
// Through this process we try to keep track of whether it is safe to
// release the IP that was allocated. If the user specifically asked for
// an IP, we assume they are managing it themselves. Otherwise, we will
// release the IP in case of early-terminating failure or upon successful
// creating of the LB.
// TODO(#36535): boil this logic down into a set of component functions
// and key the flag values off of errors returned.
isUserOwnedIP := false // if this is set, we never release the IP
isSafeToReleaseIP := false
defer func() {
if isUserOwnedIP {
return
}
if isSafeToReleaseIP {
if err := g.DeleteRegionAddress(loadBalancerName, g.region); err != nil && !isNotFound(err) {
klog.Errorf("ensureExternalLoadBalancer(%s): Failed to release static IP %s in region %v: %v.", lbRefStr, ipAddressToUse, g.region, err)
} else if isNotFound(err) {
klog.V(2).Infof("ensureExternalLoadBalancer(%s): IP address %s is not reserved.", lbRefStr, ipAddressToUse)
} else {
klog.Infof("ensureExternalLoadBalancer(%s): Released static IP %s.", lbRefStr, ipAddressToUse)
}
} else {
klog.Warningf("ensureExternalLoadBalancer(%s): Orphaning static IP %s in region %v: %v.", lbRefStr, ipAddressToUse, g.region, err)
}
}()
if requestedIP != "" {
// If user requests a specific IP address, verify first. No mutation to
// the GCE resources will be performed in the verification process.
isUserOwnedIP, err = verifyUserRequestedIP(g, g.region, requestedIP, fwdRuleIP, lbRefStr, netTier)
if err != nil {
return nil, err
}
ipAddressToUse = requestedIP
}
if !isUserOwnedIP {
// If we are not using the user-owned IP, either promote the
// emphemeral IP used by the fwd rule, or create a new static IP.
ipAddr, existed, err := ensureStaticIP(g, loadBalancerName, serviceName.String(), g.region, fwdRuleIP, netTier)
if err != nil {
return nil, fmt.Errorf("failed to ensure a static IP for load balancer (%s): %v", lbRefStr, err)
}
klog.Infof("ensureExternalLoadBalancer(%s): Ensured IP address %s (tier: %s).", lbRefStr, ipAddr, netTier)
// If the IP was not owned by the user, but it already existed, it
// could indicate that the previous update cycle failed. We can use
// this IP and try to run through the process again, but we should
// not release the IP unless it is explicitly flagged as OK.
isSafeToReleaseIP = !existed
ipAddressToUse = ipAddr
}
// Deal with the firewall next. The reason we do this here rather than last
// is because the forwarding rule is used as the indicator that the load
// balancer is fully created - it's what getLoadBalancer checks for.
// Check if user specified the allow source range
sourceRanges, err := apiservice.GetLoadBalancerSourceRanges(apiService)
if err != nil {
return nil, err
}
firewallExists, firewallNeedsUpdate, err := g.firewallNeedsUpdate(loadBalancerName, serviceName.String(), g.region, ipAddressToUse, ports, sourceRanges)
if err != nil {
return nil, err
}
if firewallNeedsUpdate {
desc := makeFirewallDescription(serviceName.String(), ipAddressToUse)
// Unlike forwarding rules and target pools, firewalls can be updated
// without needing to be deleted and recreated.
if firewallExists {
klog.Infof("ensureExternalLoadBalancer(%s): Updating firewall.", lbRefStr)
if err := g.updateFirewall(apiService, MakeFirewallName(loadBalancerName), g.region, desc, sourceRanges, ports, hosts); err != nil {
return nil, err
}
klog.Infof("ensureExternalLoadBalancer(%s): Updated firewall.", lbRefStr)
} else {
klog.Infof("ensureExternalLoadBalancer(%s): Creating firewall.", lbRefStr)
if err := g.createFirewall(apiService, MakeFirewallName(loadBalancerName), g.region, desc, sourceRanges, ports, hosts); err != nil {
return nil, err
}
klog.Infof("ensureExternalLoadBalancer(%s): Created firewall.", lbRefStr)
}
}
tpExists, tpNeedsRecreation, err := g.targetPoolNeedsRecreation(loadBalancerName, g.region, apiService.Spec.SessionAffinity)
if err != nil {
return nil, err
}
if !tpExists {
klog.Infof("ensureExternalLoadBalancer(%s): Target pool for service doesn't exist.", lbRefStr)
}
// Check which health check needs to create and which health check needs to delete.
// Health check management is coupled with target pool operation to prevent leaking.
var hcToCreate, hcToDelete *compute.HttpHealthCheck
hcLocalTrafficExisting, err := g.GetHTTPHealthCheck(loadBalancerName)
if err != nil && !isHTTPErrorCode(err, http.StatusNotFound) {
return nil, fmt.Errorf("error checking HTTP health check for load balancer (%s): %v", lbRefStr, err)
}
if path, healthCheckNodePort := apiservice.GetServiceHealthCheckPathPort(apiService); path != "" {
klog.V(4).Infof("ensureExternalLoadBalancer(%s): Service needs local traffic health checks on: %d%s.", lbRefStr, healthCheckNodePort, path)
if hcLocalTrafficExisting == nil {
// This logic exists to detect a transition for non-OnlyLocal to OnlyLocal service
// turn on the tpNeedsRecreation flag to delete/recreate fwdrule/tpool updating the
// target pool to use local traffic health check.
klog.V(2).Infof("ensureExternalLoadBalancer(%s): Updating from nodes health checks to local traffic health checks.", lbRefStr)
if supportsNodesHealthCheck {
hcToDelete = makeHTTPHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort())
}
tpNeedsRecreation = true
}
hcToCreate = makeHTTPHealthCheck(loadBalancerName, path, healthCheckNodePort)
} else {
klog.V(4).Infof("ensureExternalLoadBalancer(%s): Service needs nodes health checks.", lbRefStr)
if hcLocalTrafficExisting != nil {
// This logic exists to detect a transition from OnlyLocal to non-OnlyLocal service
// and turn on the tpNeedsRecreation flag to delete/recreate fwdrule/tpool updating the
// target pool to use nodes health check.
klog.V(2).Infof("ensureExternalLoadBalancer(%s): Updating from local traffic health checks to nodes health checks.", lbRefStr)
hcToDelete = hcLocalTrafficExisting
tpNeedsRecreation = true
}
if supportsNodesHealthCheck {
hcToCreate = makeHTTPHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort())
}
}
// Now we get to some slightly more interesting logic.
// First, neither target pools nor forwarding rules can be updated in place -
// they have to be deleted and recreated.
// Second, forwarding rules are layered on top of target pools in that you
// can't delete a target pool that's currently in use by a forwarding rule.
// Thus, we have to tear down the forwarding rule if either it or the target
// pool needs to be updated.
if fwdRuleExists && (fwdRuleNeedsUpdate || tpNeedsRecreation) {
// Begin critical section. If we have to delete the forwarding rule,
// and something should fail before we recreate it, don't release the
// IP. That way we can come back to it later.
isSafeToReleaseIP = false
if err := g.DeleteRegionForwardingRule(loadBalancerName, g.region); err != nil && !isNotFound(err) {
return nil, fmt.Errorf("failed to delete existing forwarding rule for load balancer (%s) update: %v", lbRefStr, err)
}
klog.Infof("ensureExternalLoadBalancer(%s): Deleted forwarding rule.", lbRefStr)
}
if err := g.ensureTargetPoolAndHealthCheck(tpExists, tpNeedsRecreation, apiService, loadBalancerName, clusterID, ipAddressToUse, hosts, hcToCreate, hcToDelete); err != nil {
return nil, err
}
if tpNeedsRecreation || fwdRuleNeedsUpdate {
klog.Infof("ensureExternalLoadBalancer(%s): Creating forwarding rule, IP %s (tier: %s).", lbRefStr, ipAddressToUse, netTier)
if err := createForwardingRule(g, loadBalancerName, serviceName.String(), g.region, ipAddressToUse, g.targetPoolURL(loadBalancerName), ports, netTier); err != nil {
return nil, fmt.Errorf("failed to create forwarding rule for load balancer (%s): %v", lbRefStr, err)
}
// End critical section. It is safe to release the static IP (which
// just demotes it to ephemeral) now that it is attached. In the case
// of a user-requested IP, the "is user-owned" flag will be set,
// preventing it from actually being released.
isSafeToReleaseIP = true
klog.Infof("ensureExternalLoadBalancer(%s): Created forwarding rule, IP %s.", lbRefStr, ipAddressToUse)
}
status := &v1.LoadBalancerStatus{}
status.Ingress = []v1.LoadBalancerIngress{{IP: ipAddressToUse}}
return status, nil
}
// updateExternalLoadBalancer is the external implementation of LoadBalancer.UpdateLoadBalancer.
func (g *Cloud) updateExternalLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error {
hosts, err := g.getInstancesByNames(nodeNames(nodes))
if err != nil {
return err
}
loadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, service)
return g.updateTargetPool(loadBalancerName, hosts)
}
// ensureExternalLoadBalancerDeleted is the external implementation of LoadBalancer.EnsureLoadBalancerDeleted
func (g *Cloud) ensureExternalLoadBalancerDeleted(clusterName, clusterID string, service *v1.Service) error {
loadBalancerName := g.GetLoadBalancerName(context.TODO(), clusterName, service)
serviceName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
lbRefStr := fmt.Sprintf("%v(%v)", loadBalancerName, serviceName)
var hcNames []string
if path, _ := apiservice.GetServiceHealthCheckPathPort(service); path != "" {
hcToDelete, err := g.GetHTTPHealthCheck(loadBalancerName)
if err != nil && !isHTTPErrorCode(err, http.StatusNotFound) {
klog.Infof("ensureExternalLoadBalancerDeleted(%s): Failed to retrieve health check:%v.", lbRefStr, err)
return err
}
// If we got 'StatusNotFound' LB was already deleted and it's safe to ignore.
if err == nil {
hcNames = append(hcNames, hcToDelete.Name)
}
} else {
// EnsureLoadBalancerDeleted() could be triggered by changing service from
// LoadBalancer type to others. In this case we have no idea whether it was
// using local traffic health check or nodes health check. Attempt to delete
// both to prevent leaking.
hcNames = append(hcNames, loadBalancerName)
hcNames = append(hcNames, MakeNodesHealthCheckName(clusterID))
}
errs := utilerrors.AggregateGoroutines(
func() error {
klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting firewall rule.", lbRefStr)
fwName := MakeFirewallName(loadBalancerName)
err := ignoreNotFound(g.DeleteFirewall(fwName))
if isForbidden(err) && g.OnXPN() {
klog.V(4).Infof("ensureExternalLoadBalancerDeleted(%s): Do not have permission to delete firewall rule %v (on XPN). Raising event.", lbRefStr, fwName)
g.raiseFirewallChangeNeededEvent(service, FirewallToGCloudDeleteCmd(fwName, g.NetworkProjectID()))
return nil
}
return err
},
// Even though we don't hold on to static IPs for load balancers, it's
// possible that EnsureLoadBalancer left one around in a failed
// creation/update attempt, so make sure we clean it up here just in case.
func() error {
klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting IP address.", lbRefStr)
return ignoreNotFound(g.DeleteRegionAddress(loadBalancerName, g.region))
},
func() error {
klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting forwarding rule.", lbRefStr)
// The forwarding rule must be deleted before either the target pool can,
// unfortunately, so we have to do these two serially.
if err := ignoreNotFound(g.DeleteRegionForwardingRule(loadBalancerName, g.region)); err != nil {
return err
}
klog.Infof("ensureExternalLoadBalancerDeleted(%s): Deleting target pool.", lbRefStr)
if err := g.DeleteExternalTargetPoolAndChecks(service, loadBalancerName, g.region, clusterID, hcNames...); err != nil {
return err
}
return nil
},
)
if errs != nil {
return utilerrors.Flatten(errs)
}
return nil
}
// DeleteExternalTargetPoolAndChecks Deletes an external load balancer pool and verifies the operation
func (g *Cloud) DeleteExternalTargetPoolAndChecks(service *v1.Service, name, region, clusterID string, hcNames ...string) error {
serviceName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
lbRefStr := fmt.Sprintf("%v(%v)", name, serviceName)
if err := g.DeleteTargetPool(name, region); err != nil && isHTTPErrorCode(err, http.StatusNotFound) {
klog.Infof("DeleteExternalTargetPoolAndChecks(%v): Target pool already deleted. Continuing to delete other resources.", lbRefStr)
} else if err != nil {
klog.Warningf("DeleteExternalTargetPoolAndChecks(%v): Failed to delete target pool, got error %s.", lbRefStr, err.Error())
return err
}
// Deletion of health checks is allowed only after the TargetPool reference is deleted
for _, hcName := range hcNames {
if err := func() error {
// Check whether it is nodes health check, which has different name from the load-balancer.
isNodesHealthCheck := hcName != name
if isNodesHealthCheck {
// Lock to prevent deleting necessary nodes health check before it gets attached
// to target pool.
g.sharedResourceLock.Lock()
defer g.sharedResourceLock.Unlock()
}
klog.Infof("DeleteExternalTargetPoolAndChecks(%v): Deleting health check %v.", lbRefStr, hcName)
if err := g.DeleteHTTPHealthCheck(hcName); err != nil {
// Delete nodes health checks will fail if any other target pool is using it.
if isInUsedByError(err) {
klog.V(4).Infof("DeleteExternalTargetPoolAndChecks(%v): Health check %v is in used: %v.", lbRefStr, hcName, err)
return nil
} else if !isHTTPErrorCode(err, http.StatusNotFound) {
klog.Warningf("DeleteExternalTargetPoolAndChecks(%v): Failed to delete health check %v: %v.", lbRefStr, hcName, err)
return err
}
// StatusNotFound could happen when:
// - This is the first attempt but we pass in a healthcheck that is already deleted
// to prevent leaking.
// - This is the first attempt but user manually deleted the heathcheck.
// - This is a retry and in previous round we failed to delete the healthcheck firewall
// after deleted the healthcheck.
// We continue to delete the healthcheck firewall to prevent leaking.
klog.V(4).Infof("DeleteExternalTargetPoolAndChecks(%v): Health check %v is already deleted.", lbRefStr, hcName)
}
// If health check is deleted without error, it means no load-balancer is using it.
// So we should delete the health check firewall as well.
fwName := MakeHealthCheckFirewallName(clusterID, hcName, isNodesHealthCheck)
klog.Infof("DeleteExternalTargetPoolAndChecks(%v): Deleting health check firewall %v.", lbRefStr, fwName)
if err := ignoreNotFound(g.DeleteFirewall(fwName)); err != nil {
if isForbidden(err) && g.OnXPN() {
klog.V(4).Infof("DeleteExternalTargetPoolAndChecks(%v): Do not have permission to delete firewall rule %v (on XPN). Raising event.", lbRefStr, fwName)
g.raiseFirewallChangeNeededEvent(service, FirewallToGCloudDeleteCmd(fwName, g.NetworkProjectID()))
return nil
}
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}
// verifyUserRequestedIP checks the user-provided IP to see whether it meets
// all the expected attributes for the load balancer, and returns an error if
// the verification failed. It also returns a boolean to indicate whether the
// IP address is considered owned by the user (i.e., not managed by the
// controller.
func verifyUserRequestedIP(s CloudAddressService, region, requestedIP, fwdRuleIP, lbRef string, desiredNetTier cloud.NetworkTier) (isUserOwnedIP bool, err error) {
if requestedIP == "" {
return false, nil
}
// If a specific IP address has been requested, we have to respect the
// user's request and use that IP. If the forwarding rule was already using
// a different IP, it will be harmlessly abandoned because it was only an
// ephemeral IP (or it was a different static IP owned by the user, in which
// case we shouldn't delete it anyway).
existingAddress, err := s.GetRegionAddressByIP(region, requestedIP)
if err != nil && !isNotFound(err) {
klog.Errorf("verifyUserRequestedIP: failed to check whether the requested IP %q for LB %s exists: %v", requestedIP, lbRef, err)
return false, err
}
if err == nil {
// The requested IP is a static IP, owned and managed by the user.
// Check if the network tier of the static IP matches the desired
// network tier.
netTierStr, err := s.getNetworkTierFromAddress(existingAddress.Name, region)
if err != nil {
return false, fmt.Errorf("failed to check the network tier of the IP %q: %v", requestedIP, err)
}
netTier := cloud.NetworkTierGCEValueToType(netTierStr)
if netTier != desiredNetTier {
klog.Errorf("verifyUserRequestedIP: requested static IP %q (name: %s) for LB %s has network tier %s, need %s.", requestedIP, existingAddress.Name, lbRef, netTier, desiredNetTier)
return false, fmt.Errorf("requrested IP %q belongs to the %s network tier; expected %s", requestedIP, netTier, desiredNetTier)
}
klog.V(4).Infof("verifyUserRequestedIP: the requested static IP %q (name: %s, tier: %s) for LB %s exists.", requestedIP, existingAddress.Name, netTier, lbRef)
return true, nil
}
if requestedIP == fwdRuleIP {
// The requested IP is not a static IP, but is currently assigned
// to this forwarding rule, so we can just use it.
klog.V(4).Infof("verifyUserRequestedIP: the requested IP %q is not static, but is currently in use by for LB %s", requestedIP, lbRef)
return false, nil
}
// The requested IP is not static and it is not assigned to the
// current forwarding rule. It might be attached to a different
// rule or it might not be part of this project at all. Either
// way, we can't use it.
klog.Errorf("verifyUserRequestedIP: requested IP %q for LB %s is neither static nor assigned to the LB", requestedIP, lbRef)
return false, fmt.Errorf("requested ip %q is neither static nor assigned to the LB", requestedIP)
}
func (g *Cloud) ensureTargetPoolAndHealthCheck(tpExists, tpNeedsRecreation bool, svc *v1.Service, loadBalancerName, clusterID, ipAddressToUse string, hosts []*gceInstance, hcToCreate, hcToDelete *compute.HttpHealthCheck) error {
serviceName := types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}
lbRefStr := fmt.Sprintf("%v(%v)", loadBalancerName, serviceName)
if tpExists && tpNeedsRecreation {
// Pass healthchecks to DeleteExternalTargetPoolAndChecks to cleanup health checks after cleaning up the target pool itself.
var hcNames []string
if hcToDelete != nil {
hcNames = append(hcNames, hcToDelete.Name)
}
if err := g.DeleteExternalTargetPoolAndChecks(svc, loadBalancerName, g.region, clusterID, hcNames...); err != nil {
return fmt.Errorf("failed to delete existing target pool for load balancer (%s) update: %v", lbRefStr, err)
}
klog.Infof("ensureTargetPoolAndHealthCheck(%s): Deleted target pool.", lbRefStr)
}
// Once we've deleted the resources (if necessary), build them back up (or for
// the first time if they're new).
if tpNeedsRecreation {
createInstances := hosts
if len(hosts) > maxTargetPoolCreateInstances {
createInstances = createInstances[:maxTargetPoolCreateInstances]
}
if err := g.createTargetPoolAndHealthCheck(svc, loadBalancerName, serviceName.String(), ipAddressToUse, g.region, clusterID, createInstances, hcToCreate); err != nil {
return fmt.Errorf("failed to create target pool for load balancer (%s): %v", lbRefStr, err)
}
if hcToCreate != nil {
klog.Infof("ensureTargetPoolAndHealthCheck(%s): Created health checks %v.", lbRefStr, hcToCreate.Name)
}
if len(hosts) <= maxTargetPoolCreateInstances {
klog.Infof("ensureTargetPoolAndHealthCheck(%s): Created target pool.", lbRefStr)
} else {
klog.Infof("ensureTargetPoolAndHealthCheck(%s): Created initial target pool (now updating the remaining %d hosts).", lbRefStr, len(hosts)-maxTargetPoolCreateInstances)
if err := g.updateTargetPool(loadBalancerName, hosts); err != nil {
return fmt.Errorf("failed to update target pool for load balancer (%s): %v", lbRefStr, err)
}
klog.Infof("ensureTargetPoolAndHealthCheck(%s): Updated target pool (with %d hosts).", lbRefStr, len(hosts)-maxTargetPoolCreateInstances)
}
} else if tpExists {
// Ensure hosts are updated even if there is no other changes required on target pool.
if err := g.updateTargetPool(loadBalancerName, hosts); err != nil {
return fmt.Errorf("failed to update target pool for load balancer (%s): %v", lbRefStr, err)
}
klog.Infof("ensureTargetPoolAndHealthCheck(%s): Updated target pool (with %d hosts).", lbRefStr, len(hosts))
if hcToCreate != nil {
if hc, err := g.ensureHTTPHealthCheck(hcToCreate.Name, hcToCreate.RequestPath, int32(hcToCreate.Port)); err != nil || hc == nil {
return fmt.Errorf("Failed to ensure health check for %v port %d path %v: %v", loadBalancerName, hcToCreate.Port, hcToCreate.RequestPath, err)
}
}
} else {
// Panic worthy.
klog.Errorf("ensureTargetPoolAndHealthCheck(%s): target pool not exists and doesn't need to be created.", lbRefStr)
}
return nil
}
func (g *Cloud) createTargetPoolAndHealthCheck(svc *v1.Service, name, serviceName, ipAddress, region, clusterID string, hosts []*gceInstance, hc *compute.HttpHealthCheck) error {
// health check management is coupled with targetPools to prevent leaks. A
// target pool is the only thing that requires a health check, so we delete
// associated checks on teardown, and ensure checks on setup.
hcLinks := []string{}
if hc != nil {
// Check whether it is nodes health check, which has different name from the load-balancer.
isNodesHealthCheck := hc.Name != name
if isNodesHealthCheck {
// Lock to prevent necessary nodes health check / firewall gets deleted.
g.sharedResourceLock.Lock()
defer g.sharedResourceLock.Unlock()
}
if err := g.ensureHTTPHealthCheckFirewall(svc, serviceName, ipAddress, region, clusterID, hosts, hc.Name, int32(hc.Port), isNodesHealthCheck); err != nil {
return err
}
var err error
hcRequestPath, hcPort := hc.RequestPath, hc.Port
if hc, err = g.ensureHTTPHealthCheck(hc.Name, hc.RequestPath, int32(hc.Port)); err != nil || hc == nil {
return fmt.Errorf("Failed to ensure health check for %v port %d path %v: %v", name, hcPort, hcRequestPath, err)
}
hcLinks = append(hcLinks, hc.SelfLink)
}
var instances []string
for _, host := range hosts {
instances = append(instances, host.makeComparableHostPath())
}
klog.Infof("Creating targetpool %v with %d healthchecks", name, len(hcLinks))
pool := &compute.TargetPool{
Name: name,
Description: fmt.Sprintf(`{"kubernetes.io/service-name":"%s"}`, serviceName),
Instances: instances,
SessionAffinity: translateAffinityType(svc.Spec.SessionAffinity),
HealthChecks: hcLinks,
}
if err := g.CreateTargetPool(pool, region); err != nil && !isHTTPErrorCode(err, http.StatusConflict) {
return err
}
return nil
}
func (g *Cloud) updateTargetPool(loadBalancerName string, hosts []*gceInstance) error {
pool, err := g.GetTargetPool(loadBalancerName, g.region)
if err != nil {
return err
}
existing := sets.NewString()
for _, instance := range pool.Instances {
existing.Insert(hostURLToComparablePath(instance))
}
var toAdd []*compute.InstanceReference
var toRemove []*compute.InstanceReference
for _, host := range hosts {
link := host.makeComparableHostPath()
if !existing.Has(link) {
toAdd = append(toAdd, &compute.InstanceReference{Instance: link})
}
existing.Delete(link)
}
for link := range existing {
toRemove = append(toRemove, &compute.InstanceReference{Instance: link})
}
if len(toAdd) > 0 {
if err := g.AddInstancesToTargetPool(loadBalancerName, g.region, toAdd); err != nil {
return err
}
}
if len(toRemove) > 0 {
if err := g.RemoveInstancesFromTargetPool(loadBalancerName, g.region, toRemove); err != nil {
return err
}
}
// Try to verify that the correct number of nodes are now in the target pool.
// We've been bitten by a bug here before (#11327) where all nodes were
// accidentally removed and want to make similar problems easier to notice.
updatedPool, err := g.GetTargetPool(loadBalancerName, g.region)
if err != nil {
return err
}
if len(updatedPool.Instances) != len(hosts) {
klog.Errorf("Unexpected number of instances (%d) in target pool %s after updating (expected %d). Instances in updated pool: %s",
len(updatedPool.Instances), loadBalancerName, len(hosts), strings.Join(updatedPool.Instances, ","))
return fmt.Errorf("Unexpected number of instances (%d) in target pool %s after update (expected %d)", len(updatedPool.Instances), loadBalancerName, len(hosts))
}
return nil
}
func (g *Cloud) targetPoolURL(name string) string {
return g.service.BasePath + strings.Join([]string{g.projectID, "regions", g.region, "targetPools", name}, "/")
}
func makeHTTPHealthCheck(name, path string, port int32) *compute.HttpHealthCheck {
return &compute.HttpHealthCheck{
Name: name,
Port: int64(port),
RequestPath: path,
Host: "",
Description: makeHealthCheckDescription(name),
CheckIntervalSec: gceHcCheckIntervalSeconds,
TimeoutSec: gceHcTimeoutSeconds,
HealthyThreshold: gceHcHealthyThreshold,
UnhealthyThreshold: gceHcUnhealthyThreshold,
}
}
// mergeHTTPHealthChecks reconciles HttpHealthCheck configures to be no smaller
// than the default values.
// E.g. old health check interval is 2s, new default is 8.
// The HC interval will be reconciled to 8 seconds.
// If the existing health check is larger than the default interval,
// the configuration will be kept.
func mergeHTTPHealthChecks(hc, newHC *compute.HttpHealthCheck) *compute.HttpHealthCheck {
if hc.CheckIntervalSec > newHC.CheckIntervalSec {
newHC.CheckIntervalSec = hc.CheckIntervalSec
}
if hc.TimeoutSec > newHC.TimeoutSec {
newHC.TimeoutSec = hc.TimeoutSec
}
if hc.UnhealthyThreshold > newHC.UnhealthyThreshold {
newHC.UnhealthyThreshold = hc.UnhealthyThreshold
}
if hc.HealthyThreshold > newHC.HealthyThreshold {
newHC.HealthyThreshold = hc.HealthyThreshold
}
return newHC
}
// needToUpdateHTTPHealthChecks checks whether the http healthcheck needs to be
// updated.
func needToUpdateHTTPHealthChecks(hc, newHC *compute.HttpHealthCheck) bool {
changed := hc.Port != newHC.Port || hc.RequestPath != newHC.RequestPath || hc.Description != newHC.Description
changed = changed || hc.CheckIntervalSec < newHC.CheckIntervalSec || hc.TimeoutSec < newHC.TimeoutSec
changed = changed || hc.UnhealthyThreshold < newHC.UnhealthyThreshold || hc.HealthyThreshold < newHC.HealthyThreshold
return changed
}
func (g *Cloud) ensureHTTPHealthCheck(name, path string, port int32) (hc *compute.HttpHealthCheck, err error) {
newHC := makeHTTPHealthCheck(name, path, port)
hc, err = g.GetHTTPHealthCheck(name)
if hc == nil || err != nil && isHTTPErrorCode(err, http.StatusNotFound) {
klog.Infof("Did not find health check %v, creating port %v path %v", name, port, path)
if err = g.CreateHTTPHealthCheck(newHC); err != nil {
return nil, err
}
hc, err = g.GetHTTPHealthCheck(name)
if err != nil {
klog.Errorf("Failed to get http health check %v", err)
return nil, err
}
klog.Infof("Created HTTP health check %v healthCheckNodePort: %d", name, port)
return hc, nil
}
// Validate health check fields
klog.V(4).Infof("Checking http health check params %s", name)
if needToUpdateHTTPHealthChecks(hc, newHC) {
klog.Warningf("Health check %v exists but parameters have drifted - updating...", name)
newHC = mergeHTTPHealthChecks(hc, newHC)
if err := g.UpdateHTTPHealthCheck(newHC); err != nil {
klog.Warningf("Failed to reconcile http health check %v parameters", name)
return nil, err
}
klog.V(4).Infof("Corrected health check %v parameters successful", name)
hc, err = g.GetHTTPHealthCheck(name)
if err != nil {
return nil, err
}
}
return hc, nil
}
// Passing nil for requested IP is perfectly fine - it just means that no specific
// IP is being requested.
// Returns whether the forwarding rule exists, whether it needs to be updated,
// what its IP address is (if it exists), and any error we encountered.
func (g *Cloud) forwardingRuleNeedsUpdate(name, region string, loadBalancerIP string, ports []v1.ServicePort) (exists bool, needsUpdate bool, ipAddress string, err error) {
fwd, err := g.GetRegionForwardingRule(name, region)
if err != nil {
if isHTTPErrorCode(err, http.StatusNotFound) {
return false, true, "", nil
}
// Err on the side of caution in case of errors. Caller should notice the error and retry.
// We never want to end up recreating resources because g api flaked.
return true, false, "", fmt.Errorf("error getting load balancer's forwarding rule: %v", err)
}
// If the user asks for a specific static ip through the Service spec,
// check that we're actually using it.
// TODO: we report loadbalancer IP through status, so we want to verify if
// that matches the forwarding rule as well.
if loadBalancerIP != "" && loadBalancerIP != fwd.IPAddress {
klog.Infof("LoadBalancer ip for forwarding rule %v was expected to be %v, but was actually %v", fwd.Name, fwd.IPAddress, loadBalancerIP)
return true, true, fwd.IPAddress, nil
}
portRange, err := loadBalancerPortRange(ports)
if err != nil {
// Err on the side of caution in case of errors. Caller should notice the error and retry.
// We never want to end up recreating resources because g api flaked.
return true, false, "", err
}
if portRange != fwd.PortRange {
klog.Infof("LoadBalancer port range for forwarding rule %v was expected to be %v, but was actually %v", fwd.Name, fwd.PortRange, portRange)
return true, true, fwd.IPAddress, nil
}
// The service controller verified all the protocols match on the ports, just check the first one
if string(ports[0].Protocol) != fwd.IPProtocol {
klog.Infof("LoadBalancer protocol for forwarding rule %v was expected to be %v, but was actually %v", fwd.Name, fwd.IPProtocol, string(ports[0].Protocol))
return true, true, fwd.IPAddress, nil
}
return true, false, fwd.IPAddress, nil
}
// Doesn't check whether the hosts have changed, since host updating is handled
// separately.
func (g *Cloud) targetPoolNeedsRecreation(name, region string, affinityType v1.ServiceAffinity) (exists bool, needsRecreation bool, err error) {
tp, err := g.GetTargetPool(name, region)
if err != nil {
if isHTTPErrorCode(err, http.StatusNotFound) {
return false, true, nil
}
// Err on the side of caution in case of errors. Caller should notice the error and retry.
// We never want to end up recreating resources because g api flaked.
return true, false, fmt.Errorf("error getting load balancer's target pool: %v", err)
}
// TODO: If the user modifies their Service's session affinity, it *should*
// reflect in the associated target pool. However, currently not setting the
// session affinity on a target pool defaults it to the empty string while
// not setting in on a Service defaults it to None. There is a lack of
// documentation around the default setting for the target pool, so if we
// find it's the undocumented empty string, don't blindly recreate the
// target pool (which results in downtime). Fix this when we have formally
// defined the defaults on either side.
if tp.SessionAffinity != "" && translateAffinityType(affinityType) != tp.SessionAffinity {
klog.Infof("LoadBalancer target pool %v changed affinity from %v to %v", name, tp.SessionAffinity, affinityType)
return true, true, nil
}
return true, false, nil
}
func (h *gceInstance) makeComparableHostPath() string {
return fmt.Sprintf("/zones/%s/instances/%s", h.Zone, h.Name)
}
func nodeNames(nodes []*v1.Node) []string {
ret := make([]string, len(nodes))
for i, node := range nodes {
ret[i] = node.Name
}
return ret
}
func hostURLToComparablePath(hostURL string) string {
idx := strings.Index(hostURL, "/zones/")
if idx < 0 {
return ""
}
return hostURL[idx:]
}
func loadBalancerPortRange(ports []v1.ServicePort) (string, error) {
if len(ports) == 0 {
return "", fmt.Errorf("no ports specified for GCE load balancer")
}
// The service controller verified all the protocols match on the ports, just check and use the first one
if ports[0].Protocol != v1.ProtocolTCP && ports[0].Protocol != v1.ProtocolUDP {
return "", fmt.Errorf("Invalid protocol %s, only TCP and UDP are supported", string(ports[0].Protocol))
}
minPort := int32(65536)
maxPort := int32(0)
for i := range ports {
if ports[i].Port < minPort {
minPort = ports[i].Port
}
if ports[i].Port > maxPort {
maxPort = ports[i].Port
}
}
return fmt.Sprintf("%d-%d", minPort, maxPort), nil
}
// translate from what K8s supports to what the cloud provider supports for session affinity.
func translateAffinityType(affinityType v1.ServiceAffinity) string {
switch affinityType {
case v1.ServiceAffinityClientIP:
return gceAffinityTypeClientIP
case v1.ServiceAffinityNone:
return gceAffinityTypeNone
default:
klog.Errorf("Unexpected affinity type: %v", affinityType)
return gceAffinityTypeNone
}
}
func (g *Cloud) firewallNeedsUpdate(name, serviceName, region, ipAddress string, ports []v1.ServicePort, sourceRanges netsets.IPNet) (exists bool, needsUpdate bool, err error) {
fw, err := g.GetFirewall(MakeFirewallName(name))
if err != nil {
if isHTTPErrorCode(err, http.StatusNotFound) {
return false, true, nil
}
return false, false, fmt.Errorf("error getting load balancer's firewall: %v", err)
}
if fw.Description != makeFirewallDescription(serviceName, ipAddress) {
return true, true, nil
}
if len(fw.Allowed) != 1 || (fw.Allowed[0].IPProtocol != "tcp" && fw.Allowed[0].IPProtocol != "udp") {
return true, true, nil
}
// Make sure the allowed ports match.
allowedPorts := make([]string, len(ports))
for ix := range ports {
allowedPorts[ix] = strconv.Itoa(int(ports[ix].Port))
}
if !equalStringSets(allowedPorts, fw.Allowed[0].Ports) {
return true, true, nil
}
// The service controller already verified that the protocol matches on all ports, no need to check.
actualSourceRanges, err := netsets.ParseIPNets(fw.SourceRanges...)
if err != nil {
// This really shouldn't happen... GCE has returned something unexpected
klog.Warningf("Error parsing firewall SourceRanges: %v", fw.SourceRanges)
// We don't return the error, because we can hopefully recover from this by reconfiguring the firewall
return true, true, nil
}
if !sourceRanges.Equal(actualSourceRanges) {
return true, true, nil
}
return true, false, nil
}
func (g *Cloud) ensureHTTPHealthCheckFirewall(svc *v1.Service, serviceName, ipAddress, region, clusterID string, hosts []*gceInstance, hcName string, hcPort int32, isNodesHealthCheck bool) error {
// Prepare the firewall params for creating / checking.
desc := fmt.Sprintf(`{"kubernetes.io/cluster-id":"%s"}`, clusterID)
if !isNodesHealthCheck {
desc = makeFirewallDescription(serviceName, ipAddress)
}
sourceRanges := lbSrcRngsFlag.ipn
ports := []v1.ServicePort{{Protocol: "tcp", Port: hcPort}}
fwName := MakeHealthCheckFirewallName(clusterID, hcName, isNodesHealthCheck)
fw, err := g.GetFirewall(fwName)
if err != nil {
if !isHTTPErrorCode(err, http.StatusNotFound) {
return fmt.Errorf("error getting firewall for health checks: %v", err)
}
klog.Infof("Creating firewall %v for health checks.", fwName)
if err := g.createFirewall(svc, fwName, region, desc, sourceRanges, ports, hosts); err != nil {
return err
}
klog.Infof("Created firewall %v for health checks.", fwName)
return nil
}
// Validate firewall fields.
if fw.Description != desc ||
len(fw.Allowed) != 1 ||
fw.Allowed[0].IPProtocol != string(ports[0].Protocol) ||
!equalStringSets(fw.Allowed[0].Ports, []string{strconv.Itoa(int(ports[0].Port))}) ||
!equalStringSets(fw.SourceRanges, sourceRanges.StringSlice()) {
klog.Warningf("Firewall %v exists but parameters have drifted - updating...", fwName)
if err := g.updateFirewall(svc, fwName, region, desc, sourceRanges, ports, hosts); err != nil {
klog.Warningf("Failed to reconcile firewall %v parameters.", fwName)
return err
}
klog.V(4).Infof("Corrected firewall %v parameters successful", fwName)
}
return nil
}
func createForwardingRule(s CloudForwardingRuleService, name, serviceName, region, ipAddress, target string, ports []v1.ServicePort, netTier cloud.NetworkTier) error {
portRange, err := loadBalancerPortRange(ports)
if err != nil {
return err
}
desc := makeServiceDescription(serviceName)
ipProtocol := string(ports[0].Protocol)
switch netTier {
case cloud.NetworkTierPremium:
rule := &compute.ForwardingRule{
Name: name,
Description: desc,
IPAddress: ipAddress,
IPProtocol: ipProtocol,
PortRange: portRange,
Target: target,
}
err = s.CreateRegionForwardingRule(rule, region)
default:
rule := &computealpha.ForwardingRule{
Name: name,
Description: desc,
IPAddress: ipAddress,
IPProtocol: ipProtocol,
PortRange: portRange,
Target: target,
NetworkTier: netTier.ToGCEValue(),
}
err = s.CreateAlphaRegionForwardingRule(rule, region)
}
if err != nil && !isHTTPErrorCode(err, http.StatusConflict) {
return err
}
return nil
}
func (g *Cloud) createFirewall(svc *v1.Service, name, region, desc string, sourceRanges netsets.IPNet, ports []v1.ServicePort, hosts []*gceInstance) error {
firewall, err := g.firewallObject(name, region, desc, sourceRanges, ports, hosts)
if err != nil {
return err
}
if err = g.CreateFirewall(firewall); err != nil {
if isHTTPErrorCode(err, http.StatusConflict) {
return nil
} else if isForbidden(err) && g.OnXPN() {
klog.V(4).Infof("createFirewall(%v): do not have permission to create firewall rule (on XPN). Raising event.", firewall.Name)
g.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudCreateCmd(firewall, g.NetworkProjectID()))
return nil
}
return err
}
return nil
}
func (g *Cloud) updateFirewall(svc *v1.Service, name, region, desc string, sourceRanges netsets.IPNet, ports []v1.ServicePort, hosts []*gceInstance) error {
firewall, err := g.firewallObject(name, region, desc, sourceRanges, ports, hosts)
if err != nil {
return err
}
if err = g.UpdateFirewall(firewall); err != nil {
if isHTTPErrorCode(err, http.StatusConflict) {
return nil
} else if isForbidden(err) && g.OnXPN() {
klog.V(4).Infof("updateFirewall(%v): do not have permission to update firewall rule (on XPN). Raising event.", firewall.Name)
g.raiseFirewallChangeNeededEvent(svc, FirewallToGCloudUpdateCmd(firewall, g.NetworkProjectID()))
return nil
}
return err
}
return nil
}
func (g *Cloud) firewallObject(name, region, desc string, sourceRanges netsets.IPNet, ports []v1.ServicePort, hosts []*gceInstance) (*compute.Firewall, error) {
allowedPorts := make([]string, len(ports))
for ix := range ports {
allowedPorts[ix] = strconv.Itoa(int(ports[ix].Port))
}
// If the node tags to be used for this cluster have been predefined in the
// provider config, just use them. Otherwise, invoke computeHostTags method to get the tags.
hostTags := g.nodeTags
if len(hostTags) == 0 {
var err error
if hostTags, err = g.computeHostTags(hosts); err != nil {
return nil, fmt.Errorf("no node tags supplied and also failed to parse the given lists of hosts for tags. Abort creating firewall rule")
}
}
firewall := &compute.Firewall{
Name: name,
Description: desc,
Network: g.networkURL,
SourceRanges: sourceRanges.StringSlice(),
TargetTags: hostTags,
Allowed: []*compute.FirewallAllowed{
{
// TODO: Make this more generic. Currently this method is only
// used to create firewall rules for loadbalancers, which have
// exactly one protocol, so we can never end up with a list of
// mixed TCP and UDP ports. It should be possible to use a
// single firewall rule for both a TCP and UDP lb.
IPProtocol: strings.ToLower(string(ports[0].Protocol)),
Ports: allowedPorts,
},
},
}
return firewall, nil
}
func ensureStaticIP(s CloudAddressService, name, serviceName, region, existingIP string, netTier cloud.NetworkTier) (ipAddress string, existing bool, err error) {
// If the address doesn't exist, this will create it.
// If the existingIP exists but is ephemeral, this will promote it to static.
// If the address already exists, this will harmlessly return a StatusConflict
// and we'll grab the IP before returning.
existed := false
desc := makeServiceDescription(serviceName)
var creationErr error
switch netTier {
case cloud.NetworkTierPremium:
addressObj := &compute.Address{
Name: name,
Description: desc,
}
if existingIP != "" {
addressObj.Address = existingIP
}
creationErr = s.ReserveRegionAddress(addressObj, region)
default:
addressObj := &computealpha.Address{
Name: name,
Description: desc,
NetworkTier: netTier.ToGCEValue(),
}
if existingIP != "" {
addressObj.Address = existingIP
}
creationErr = s.ReserveAlphaRegionAddress(addressObj, region)
}
if creationErr != nil {
// GCE returns StatusConflict if the name conflicts; it returns
// StatusBadRequest if the IP conflicts.
if !isHTTPErrorCode(creationErr, http.StatusConflict) && !isHTTPErrorCode(creationErr, http.StatusBadRequest) {
return "", false, fmt.Errorf("error creating gce static IP address: %v", creationErr)
}
existed = true
}
addr, err := s.GetRegionAddress(name, region)
if err != nil {
return "", false, fmt.Errorf("error getting static IP address: %v", err)
}
return addr.Address, existed, nil
}
func (g *Cloud) getServiceNetworkTier(svc *v1.Service) (cloud.NetworkTier, error) {
if !g.AlphaFeatureGate.Enabled(AlphaFeatureNetworkTiers) {
return cloud.NetworkTierDefault, nil
}
tier, err := GetServiceNetworkTier(svc)
if err != nil {
// Returns an error if the annotation is invalid.
return cloud.NetworkTier(""), err
}
return tier, nil
}
func (g *Cloud) deleteWrongNetworkTieredResources(lbName, lbRef string, desiredNetTier cloud.NetworkTier) error {
logPrefix := fmt.Sprintf("deleteWrongNetworkTieredResources:(%s)", lbRef)
if err := deleteFWDRuleWithWrongTier(g, g.region, lbName, logPrefix, desiredNetTier); err != nil {
return err
}
if err := deleteAddressWithWrongTier(g, g.region, lbName, logPrefix, desiredNetTier); err != nil {
return err
}
return nil
}
// deleteFWDRuleWithWrongTier checks the network tier of existing forwarding
// rule and delete the rule if the tier does not matched the desired tier.
func deleteFWDRuleWithWrongTier(s CloudForwardingRuleService, region, name, logPrefix string, desiredNetTier cloud.NetworkTier) error {
tierStr, err := s.getNetworkTierFromForwardingRule(name, region)
if isNotFound(err) {
return nil
} else if err != nil {
return err
}
existingTier := cloud.NetworkTierGCEValueToType(tierStr)
if existingTier == desiredNetTier {
return nil
}
klog.V(2).Infof("%s: Network tiers do not match; existing forwarding rule: %q, desired: %q. Deleting the forwarding rule",
logPrefix, existingTier, desiredNetTier)
err = s.DeleteRegionForwardingRule(name, region)
return ignoreNotFound(err)
}
// deleteAddressWithWrongTier checks the network tier of existing address
// and delete the address if the tier does not matched the desired tier.
func deleteAddressWithWrongTier(s CloudAddressService, region, name, logPrefix string, desiredNetTier cloud.NetworkTier) error {
// We only check the IP address matching the reserved name that the
// controller assigned to the LB. We make the assumption that an address of
// such name is owned by the controller and is safe to release. Whether an
// IP is owned by the user is not clearly defined in the current code, and
// this assumption may not match some of the existing logic in the code.
// However, this is okay since network tiering is still Alpha and will be
// properly gated.
// TODO(#51665): Re-evaluate the "ownership" of the IP address to ensure
// we don't release IP unintentionally.
tierStr, err := s.getNetworkTierFromAddress(name, region)
if isNotFound(err) {
return nil
} else if err != nil {
return err
}
existingTier := cloud.NetworkTierGCEValueToType(tierStr)
if existingTier == desiredNetTier {
return nil
}
klog.V(2).Infof("%s: Network tiers do not match; existing address: %q, desired: %q. Deleting the address",
logPrefix, existingTier, desiredNetTier)
err = s.DeleteRegionAddress(name, region)
return ignoreNotFound(err)
}
| {
"content_hash": "23ebd12d8253031c95eee1db88522a32",
"timestamp": "",
"source": "github",
"line_count": 1112,
"max_line_length": 228,
"avg_line_length": 43.860611510791365,
"alnum_prop": 0.7333155639390646,
"repo_name": "eparis/kubernetes",
"id": "5606467586d89cdebdfda7c0ef1cb2aa16f49fbe",
"size": "49342",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "pkg/cloudprovider/providers/gce/gce_loadbalancer_external.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2840"
},
{
"name": "Dockerfile",
"bytes": "60030"
},
{
"name": "Go",
"bytes": "44478570"
},
{
"name": "HTML",
"bytes": "38"
},
{
"name": "Lua",
"bytes": "17200"
},
{
"name": "Makefile",
"bytes": "73329"
},
{
"name": "Python",
"bytes": "3152628"
},
{
"name": "Ruby",
"bytes": "430"
},
{
"name": "Shell",
"bytes": "1542483"
},
{
"name": "sed",
"bytes": "11805"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Mar 03 10:44:38 EST 2014 -->
<title>Uses of Class org.hibernate.metamodel.binding.AbstractSingularAttributeBinding (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.hibernate.metamodel.binding.AbstractSingularAttributeBinding (Hibernate JavaDocs)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/hibernate/metamodel/binding/AbstractSingularAttributeBinding.html" title="class in org.hibernate.metamodel.binding">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/hibernate/metamodel/binding/class-use/AbstractSingularAttributeBinding.html" target="_top">Frames</a></li>
<li><a href="AbstractSingularAttributeBinding.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.hibernate.metamodel.binding.AbstractSingularAttributeBinding" class="title">Uses of Class<br>org.hibernate.metamodel.binding.AbstractSingularAttributeBinding</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/hibernate/metamodel/binding/AbstractSingularAttributeBinding.html" title="class in org.hibernate.metamodel.binding">AbstractSingularAttributeBinding</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.hibernate.metamodel.binding">org.hibernate.metamodel.binding</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.hibernate.metamodel.binding">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/hibernate/metamodel/binding/AbstractSingularAttributeBinding.html" title="class in org.hibernate.metamodel.binding">AbstractSingularAttributeBinding</a> in <a href="../../../../../org/hibernate/metamodel/binding/package-summary.html">org.hibernate.metamodel.binding</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../org/hibernate/metamodel/binding/AbstractSingularAttributeBinding.html" title="class in org.hibernate.metamodel.binding">AbstractSingularAttributeBinding</a> in <a href="../../../../../org/hibernate/metamodel/binding/package-summary.html">org.hibernate.metamodel.binding</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/hibernate/metamodel/binding/BasicAttributeBinding.html" title="class in org.hibernate.metamodel.binding">BasicAttributeBinding</a></strong></code>
<div class="block"><div class="paragraph"></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/hibernate/metamodel/binding/ComponentAttributeBinding.html" title="class in org.hibernate.metamodel.binding">ComponentAttributeBinding</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/hibernate/metamodel/binding/ManyToOneAttributeBinding.html" title="class in org.hibernate.metamodel.binding">ManyToOneAttributeBinding</a></strong></code>
<div class="block"><div class="paragraph"></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/hibernate/metamodel/binding/AbstractSingularAttributeBinding.html" title="class in org.hibernate.metamodel.binding">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/hibernate/metamodel/binding/class-use/AbstractSingularAttributeBinding.html" target="_top">Frames</a></li>
<li><a href="AbstractSingularAttributeBinding.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2001-2014 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.</small></p>
</body>
</html>
| {
"content_hash": "3c4f521ba9b03add5cdfbf1072c4df4c",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 377,
"avg_line_length": 43.976190476190474,
"alnum_prop": 0.663508391987006,
"repo_name": "serious6/HibernateSimpleProject",
"id": "92a2597bfb28fe26ebd539e9f93900e75c479ea2",
"size": "7388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadoc/hibernate_Doc/org/hibernate/metamodel/binding/class-use/AbstractSingularAttributeBinding.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12560"
},
{
"name": "Java",
"bytes": "15329"
}
],
"symlink_target": ""
} |
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/Angular.js?message=docs(angular.isElement)%3A%20describe%20your%20change...#L700' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.4.8/src/Angular.js#L700' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">angular.isElement</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- function in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Determines if a reference is a DOM element (or wrapped jQuery element).</p>
</div>
<div>
<h2 id="usage">Usage</h2>
<p><code>angular.isElement(value);</code></p>
<section class="api-section">
<h3>Arguments</h3>
<table class="variables-matrix input-arguments">
<thead>
<tr>
<th>Param</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
value
</td>
<td>
<a href="" class="label type-hint type-hint-object">*</a>
</td>
<td>
<p>Reference to check.</p>
</td>
</tr>
</tbody>
</table>
</section>
<h3>Returns</h3>
<table class="variables-matrix return-arguments">
<tr>
<td><a href="" class="label type-hint type-hint-boolean">boolean</a></td>
<td><p>True if <code>value</code> is a DOM element (or wrapped jQuery element).</p>
</td>
</tr>
</table>
</div>
| {
"content_hash": "50d64be2a8cb43f02e7de8dc75b0dd2f",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 248,
"avg_line_length": 18.326315789473686,
"alnum_prop": 0.5887421022400919,
"repo_name": "confapp/data_manager",
"id": "533d98ad73d6531e0c7521524069c6589f12492a",
"size": "1741",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "vendor/angular-1.4.8/docs/partials/api/ng/function/angular.isElement.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1550"
},
{
"name": "HTML",
"bytes": "38748"
},
{
"name": "JavaScript",
"bytes": "144342"
},
{
"name": "PHP",
"bytes": "2457"
}
],
"symlink_target": ""
} |
function RecentList(controller) {
this.controller = controller;
this.current_index = 0;
this.list = [];
this.is_deletable = false;
this.is_addable = false;
this.is_label = false;
this.is_getmore = false;
this.show_albums = false;
this.show_header = false;
this.show_deletetrack = false;
this.id = "";
this.label = "";
this.name = "История";
this.icon = "/images/icons/recent.png";
}
extend(RecentList, AbstractList);
RecentList.prototype.getName = function() {
// Название для сайдбара
return this.name;
};
RecentList.prototype.getList = function(successCallback) {
// Получить ajax'ом весь плейлист, затем поиск по id'шникам
// так как асинхронно - ничего не возвращает
// и нужен каллбек. Если можно сразу - то
// вызывает каллбек сама
var _this = this;
_this.showCallback = successCallback;
// Получить поледние треки
$.ajax({
url: "/ajax/nowlistening",
type: "POST",
dataType: "json",
success: function(data) {
if (data["status"] == "OK") {
// Сделать список айдишников
var ids = data.tracks.join(",");
// Получить песенки
_this.controller.player.searchController.searchByIds(ids, function(new_list) {
_this.list = new_list;
_this.showCallback(_this);
});
}
},
error: function () {
}
});
}; | {
"content_hash": "48fd4c76331e34b12df64741ea9a92ec",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 94,
"avg_line_length": 27.814814814814813,
"alnum_prop": 0.566577896138482,
"repo_name": "patrickw14/hiplyst-1.0",
"id": "3d2cc0f35354accde841192c62fb269ad2b86941",
"size": "1709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "media/js/classes/Lists/RecentList.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "212188"
},
{
"name": "JavaScript",
"bytes": "356385"
},
{
"name": "Python",
"bytes": "56129"
}
],
"symlink_target": ""
} |
package org.wso2.am.integration.tests.restapi.admin.throttlingpolicy;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import org.apache.http.HttpStatus;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.admin.ApiException;
import org.wso2.am.integration.clients.admin.ApiResponse;
import org.wso2.am.integration.clients.admin.api.dto.AdvancedThrottlePolicyDTO;
import org.wso2.am.integration.clients.admin.api.dto.BandwidthLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.ConditionalGroupDTO;
import org.wso2.am.integration.clients.admin.api.dto.HeaderConditionDTO;
import org.wso2.am.integration.clients.admin.api.dto.IPConditionDTO;
import org.wso2.am.integration.clients.admin.api.dto.JWTClaimsConditionDTO;
import org.wso2.am.integration.clients.admin.api.dto.QueryParameterConditionDTO;
import org.wso2.am.integration.clients.admin.api.dto.RequestCountLimitDTO;
import org.wso2.am.integration.clients.admin.api.dto.ThrottleConditionDTO;
import org.wso2.am.integration.clients.admin.api.dto.ThrottleLimitDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.test.helpers.AdminApiTestHelper;
import org.wso2.am.integration.test.impl.DtoFactory;
import org.wso2.am.integration.test.impl.RestAPIAdminImpl;
import org.wso2.am.integration.test.impl.RestAPIPublisherImpl;
import org.wso2.am.integration.test.impl.RestAPIStoreImpl;
import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APILifeCycleAction;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.admin.client.UserManagementClient;
import java.net.URL;
import java.util.*;
public class AdvancedThrottlingPolicyTestCase extends APIMIntegrationBaseTest {
private String displayName = "Test Policy";
private String description = "This is a test advanced throttle policy";
private String timeUnit = "min";
private String timeUnitHour = "hour";
private Integer unitTime = 1;
private AdvancedThrottlePolicyDTO requestCountPolicyDTO;
private AdvancedThrottlePolicyDTO requestCountPolicyDTO1;
private AdvancedThrottlePolicyDTO bandwidthPolicyDTO;
private AdvancedThrottlePolicyDTO conditionalGroupsPolicyDTO;
private AdminApiTestHelper adminApiTestHelper;
private final String ADMIN_ROLE = "admin";
private final String ADMIN1_USERNAME = "admin1";
private final String ADMIN2_USERNAME = "admin2";
private final String PASSWORD = "admin1";
private String apiId1;
private String apiId2;
private String applicationId1;
private String applicationId2;
private ApplicationKeyDTO applicationKeyDTO;
private final String API_END_POINT_METHOD = "/customers/123";
private String apiEndPointUrl;
private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
@Factory(dataProvider = "userModeDataProvider")
public AdvancedThrottlingPolicyTestCase(TestUserMode userMode) {
this.userMode = userMode;
}
@DataProvider
public static Object[][] userModeDataProvider() {
return new Object[][]{new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
new Object[]{TestUserMode.TENANT_ADMIN}};
}
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
super.init(userMode);
adminApiTestHelper = new AdminApiTestHelper();
userManagementClient = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(),
keyManagerContext.getContextTenant().getTenantAdmin().getUserName(),
keyManagerContext.getContextTenant().getTenantAdmin().getPassword());
userManagementClient
.addUser(ADMIN1_USERNAME, PASSWORD, new String[] { ADMIN_ROLE }, ADMIN1_USERNAME);
userManagementClient
.addUser(ADMIN2_USERNAME, PASSWORD, new String[] { ADMIN_ROLE }, ADMIN2_USERNAME);
apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
}
@Test(groups = {"wso2.am"}, description = "Test add advanced throttling policy with request count limit")
public void testAddPolicyWithRequestCountLimit() throws Exception {
//Create the advanced throttling policy DTO with request count limit
String policyName = "TestPolicyOne";
Long requestCount = 50L;
List<ConditionalGroupDTO> conditionalGroups = new ArrayList<>();
RequestCountLimitDTO requestCountLimit =
DtoFactory.createRequestCountLimitDTO(timeUnit, unitTime, requestCount);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT, requestCountLimit, null);
requestCountPolicyDTO = DtoFactory
.createAdvancedThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
conditionalGroups);
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(requestCountPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
AdvancedThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
requestCountPolicyDTO.setPolicyId(policyId);
requestCountPolicyDTO.setIsDeployed(true);
//Verify the created advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(requestCountPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test add advanced throttling policy with bandwidth limit",
dependsOnMethods = "testAddPolicyWithRequestCountLimit")
public void testAddPolicyWithBandwidthLimit() throws Exception {
//Create the advanced throttling policy DTO with bandwidth limit
String policyName = "TestPolicyTwo_WithUnderscore";
Long dataAmount = 2L;
String dataUnit = "KB";
List<ConditionalGroupDTO> conditionalGroups = new ArrayList<>();
BandwidthLimitDTO bandwidthLimit = DtoFactory.createBandwidthLimitDTO(timeUnit, unitTime, dataAmount, dataUnit);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.BANDWIDTHLIMIT, null, bandwidthLimit);
bandwidthPolicyDTO = DtoFactory
.createAdvancedThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
conditionalGroups);
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(bandwidthPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
AdvancedThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
bandwidthPolicyDTO.setPolicyId(policyId);
bandwidthPolicyDTO.setIsDeployed(true);
//Verify the created advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(bandwidthPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test add advanced throttling policy with conditional groups",
dependsOnMethods = "testAddPolicyWithBandwidthLimit")
public void testAddPolicyWithConditionalGroups() throws Exception {
//Create the advanced throttling policy DTO with conditional groups
String policyName = "TestPolicyThree";
Long requestCount = 50L;
List<ConditionalGroupDTO> conditionalGroups = new ArrayList<>();
RequestCountLimitDTO requestCountLimit =
DtoFactory.createRequestCountLimitDTO(timeUnit, unitTime, requestCount);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT, requestCountLimit, null);
conditionalGroups.add(createConditionalGroup(defaultLimit));
conditionalGroupsPolicyDTO = DtoFactory
.createAdvancedThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
conditionalGroups);
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(conditionalGroupsPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
AdvancedThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
conditionalGroupsPolicyDTO.setPolicyId(policyId);
conditionalGroupsPolicyDTO.setIsDeployed(true);
//Verify the created advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(conditionalGroupsPolicyDTO, addedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test get and update advanced throttling policy",
dependsOnMethods = "testAddPolicyWithConditionalGroups")
public void testGetAndUpdatePolicy() throws Exception {
//Get the added advanced throttling policy with request count limit
String policyId = requestCountPolicyDTO.getPolicyId();
ApiResponse<AdvancedThrottlePolicyDTO> retrievedPolicy =
restAPIAdmin.getAdvancedThrottlingPolicy(policyId);
AdvancedThrottlePolicyDTO retrievedPolicyDTO = retrievedPolicy.getData();
Assert.assertEquals(retrievedPolicy.getStatusCode(), HttpStatus.SC_OK);
//Verify the retrieved advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(requestCountPolicyDTO, retrievedPolicyDTO);
//Update the advanced throttling policy
String updatedDescription = "This is a updated test advanced throttle policy";
requestCountPolicyDTO.setDescription(updatedDescription);
ApiResponse<AdvancedThrottlePolicyDTO> updatedPolicy =
restAPIAdmin.updateAdvancedThrottlingPolicy(policyId, requestCountPolicyDTO);
AdvancedThrottlePolicyDTO updatedPolicyDTO = updatedPolicy.getData();
Assert.assertEquals(updatedPolicy.getStatusCode(), HttpStatus.SC_OK);
//Verify the updated advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(requestCountPolicyDTO, updatedPolicyDTO);
}
@Test(groups = {"wso2.am"}, description = "Test delete already assigned advanced throttling policy",
dependsOnMethods = "testGetAndUpdatePolicy")
public void testDeletePolicyAlreadyExisting() throws Exception {
APIRequest apiRequest = new APIRequest("AdvancedThrottlingPolicyTest", "AdvancedThrottlingPolicy",
new URL(backEndServerUrl.getWebAppURLHttp() + "jaxrs_basic/services/customers/customerservice/"));
apiRequest.setProvider(user.getUserName());
apiRequest.setVersion("1.0.0");
HttpResponse addResponse = restAPIPublisher.addAPI(apiRequest);
String apiID = addResponse.getData();
apiRequest.setApiTier(requestCountPolicyDTO.getPolicyName());
restAPIPublisher.updateAPI(apiRequest, apiID);
try {
restAPIAdmin.deleteAdvancedThrottlingPolicy(requestCountPolicyDTO.getPolicyId());
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_FORBIDDEN,
"Advanced throttling policy " + requestCountPolicyDTO.getPolicyName() + ": " + requestCountPolicyDTO
.getPolicyId() + " deleted even it is already assigned to an API.");
Assert.assertTrue(e.getResponseBody().contains(
"Cannot delete the advanced policy with the name " + requestCountPolicyDTO.getPolicyName()
+ " because it is already assigned to an API/Resource"));
} finally {
if (apiID != null) {
restAPIPublisher.deleteAPI(apiID);
}
}
}
@Test(groups = {"wso2.am"}, description = "Test delete advanced throttling policy",
dependsOnMethods = "testDeletePolicyAlreadyExisting")
public void testDeletePolicy() throws Exception {
ApiResponse<Void> apiResponse =
restAPIAdmin.deleteAdvancedThrottlingPolicy(requestCountPolicyDTO.getPolicyId());
Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK);
}
@Test(groups = {"wso2.am"}, description = "Test add advanced throttling policy with existing policy name",
dependsOnMethods = "testDeletePolicy")
public void testAddPolicyWithExistingPolicyName() {
//Exception occurs when adding an advanced throttling policy with an existing policy name. The status code
//in the Exception object is used to assert this scenario
try {
restAPIAdmin.addAdvancedThrottlingPolicy(bandwidthPolicyDTO);
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_CONFLICT);
}
}
@Test(groups = {"wso2.am"}, description = "Test delete advanced throttling policy with non existing policy ID",
dependsOnMethods = "testAddPolicyWithExistingPolicyName")
public void testDeletePolicyWithNonExistingPolicyId() {
//Exception occurs when deleting an advanced throttling policy with a non existing policy ID. The
//status code in the Exception object is used to assert this scenario
try {
//The policy ID is created by combining two generated UUIDs
restAPIAdmin
.deleteAdvancedThrottlingPolicy(UUID.randomUUID().toString() + UUID.randomUUID().toString());
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_NOT_FOUND);
}
}
@Test(groups = {"wso2.am"}, description = "Test change throttling policy from Operation level to API level ",
dependsOnMethods = "testDeletePolicyWithNonExistingPolicyId")
public void testChangePolicyOperationLevelToAPILevel() throws Exception {
requestCountPolicyDTO1 = createThrottlingPolicy("NewThrottlingPolicy");
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(requestCountPolicyDTO1);
APIRequest apiRequest = new APIRequest("AdvancedThrottlingPolicyTestAPI5",
"AdvancedThrottlingPolicyTestAPI5", new URL(apiEndPointUrl));
apiRequest.setProvider(user.getUserName());
apiRequest.setVersion("1.0.0");
HttpResponse addResponse = restAPIPublisher.addAPI(apiRequest);
apiId2 = addResponse.getData();
apiRequest.setApiTier(requestCountPolicyDTO1.getPolicyName());
restAPIPublisher.updateAPI(apiRequest, apiId2);
createAPIRevisionAndDeployUsingRest(apiId2, restAPIPublisher);
restAPIPublisher.changeAPILifeCycleStatusToPublish(apiId2, false);
waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
APIMIntegrationConstants.IS_API_EXISTS);
//Verifying the change in swagger
String retrievedSwagger;
retrievedSwagger = restAPIPublisher.getSwaggerByID(apiId2);
OpenAPIParser parser = new OpenAPIParser();
SwaggerParseResult swaggerParseResult = parser.readContents(retrievedSwagger, null, null);
OpenAPI openAPI = swaggerParseResult.getOpenAPI();
Assert.assertEquals(openAPI.getExtensions().get("x-throttling-tier"), requestCountPolicyDTO1.getPolicyName());
HttpResponse applicationResponse = restAPIStore.createApplication("TestApplication2",
"Test Application", APIMIntegrationConstants.APPLICATION_TIER.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN,
ApplicationDTO.TokenTypeEnum.OAUTH);
Assert.assertEquals(applicationResponse.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
applicationId2 = applicationResponse.getData();
restAPIStore.createSubscription(apiId2, applicationId2, APIMIntegrationConstants.API_TIER.GOLD);
ArrayList grantTypes = new ArrayList();
grantTypes.add("client_credentials");
applicationKeyDTO = restAPIStore.generateKeys(applicationId2, "3600", null,
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
String accessToken = applicationKeyDTO.getToken().getAccessToken();
Assert.assertNotNull("Access Token not found. return token: ", accessToken);
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("Authorization", "Bearer " + accessToken);
requestHeaders.put("accept", "text/xml");
//verify throttling
verifyThrottling("AdvancedThrottlingPolicyTestAPI5", requestHeaders);
}
@Test(groups = {"wso2.am"}, description = "Test change throttling policy from API level to Operation level ",
dependsOnMethods = "testChangePolicyOperationLevelToAPILevel")
public void testChangePolicyAPILevelToOperationLevel() throws Exception {
//Create API and assign policy
APIRequest apiRequest = new APIRequest("AdvancedThrottlingPolicyTestAPI4",
"AdvancedThrottlingPolicyTestAPI4", new URL(apiEndPointUrl));
apiRequest.setProvider(user.getUserName());
apiRequest.setVersion("1.0.0");
apiRequest.setApiTier(requestCountPolicyDTO1.getPolicyName());
HttpResponse addResponse = restAPIPublisher.addAPI(apiRequest);
apiId1 = addResponse.getData();
APIDTO apidto = restAPIPublisher.getAPIByID(apiId1);
Assert.assertEquals(apidto.getApiThrottlingPolicy(), requestCountPolicyDTO1.getPolicyName());
List<APIOperationsDTO> operationsDTOS = apidto.getOperations();
for (APIOperationsDTO operationsDTO : operationsDTOS) {
operationsDTO.setThrottlingPolicy(requestCountPolicyDTO1.getPolicyName());
}
apiRequest.setOperationsDTOS(operationsDTOS);
restAPIPublisher.updateAPI(apiRequest, apiId1);
//publish the api
createAPIRevisionAndDeployUsingRest(apiId1, restAPIPublisher);
restAPIPublisher.changeAPILifeCycleStatusToPublish(apiId1, false);
waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
APIMIntegrationConstants.IS_API_EXISTS);
//Verifying the change in swagger
String retrievedSwagger;
List<Object> resourceThrottlingTiers;
retrievedSwagger = restAPIPublisher.getSwaggerByID(apiId1);
resourceThrottlingTiers = getResourceThrottlingPolicies(retrievedSwagger);
Assert.assertEquals(resourceThrottlingTiers.get(0), requestCountPolicyDTO1.getPolicyName());
//Create application
HttpResponse applicationResponse = restAPIStore.createApplication("TestApplication1",
"Test Application", APIMIntegrationConstants.APPLICATION_TIER.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN,
ApplicationDTO.TokenTypeEnum.OAUTH);
Assert.assertEquals(applicationResponse.getResponseCode(), HttpStatus.SC_OK, "Response code is not as expected");
applicationId1 = applicationResponse.getData();
restAPIStore.createSubscription(apiId1, applicationId1, APIMIntegrationConstants.API_TIER.GOLD);
ArrayList grantTypes = new ArrayList();
grantTypes.add("client_credentials");
applicationKeyDTO = restAPIStore.generateKeys(applicationId1, "3600", null,
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
String accessToken = applicationKeyDTO.getToken().getAccessToken();
Assert.assertNotNull("Access Token not found. return token: ", accessToken);
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("Authorization", "Bearer " + accessToken);
requestHeaders.put("accept", "text/xml");
//verify throttling
verifyThrottling("AdvancedThrottlingPolicyTestAPI4", requestHeaders);
}
@Test(groups = {"wso2.am"}, description = "Test delete advanced throttling policy created with a different " +
"admin user ", dependsOnMethods = "testChangePolicyAPILevelToOperationLevel")
public void testDeleteAdvancedPolicyWithDifferentAdminUser() throws Exception {
restAPIAdmin = new RestAPIAdminImpl(ADMIN1_USERNAME, PASSWORD, user.getUserDomain(),
adminURLHttps);
requestCountPolicyDTO = createThrottlingPolicy("TestPolicyAdmin1");
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(requestCountPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
AdvancedThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
requestCountPolicyDTO.setPolicyId(policyId);
requestCountPolicyDTO.setIsDeployed(true);
//Verify the created advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(requestCountPolicyDTO, addedPolicyDTO);
restAPIAdmin = new RestAPIAdminImpl(ADMIN2_USERNAME, PASSWORD, user.getUserDomain(),
adminURLHttps);
//Delete the policy from a different admin user
ApiResponse<Void> apiResponse =
restAPIAdmin.deleteAdvancedThrottlingPolicy(policyId);
Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK);
}
@Test(groups = {"wso2.am"}, description = "Test delete advanced throttling policy assigned to API created with a" +
" different admin user ", dependsOnMethods = "testDeleteAdvancedPolicyWithDifferentAdminUser")
public void testDeleteAssignedAPILevelAdvancedPolicyWithDifferentAdminUser() throws Exception {
restAPIAdmin = new RestAPIAdminImpl(ADMIN1_USERNAME, PASSWORD, user.getUserDomain(),
adminURLHttps);
requestCountPolicyDTO = createThrottlingPolicy("TestPolicyAdmin2");
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(requestCountPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
AdvancedThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
requestCountPolicyDTO.setPolicyId(policyId);
requestCountPolicyDTO.setIsDeployed(true);
//Verify the created advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(requestCountPolicyDTO, addedPolicyDTO);
restAPIPublisher = new RestAPIPublisherImpl(ADMIN1_USERNAME, PASSWORD,
user.getUserDomain(), publisherURLHttps);
//Create API and assign policy to API
APIRequest apiRequest = new APIRequest("AdvancedThrottlingPolicyTestAPI2",
"AdvancedThrottlingPolicyTestAPI2", new URL(backEndServerUrl.getWebAppURLHttp() +
"jaxrs_basic/services/customers/customerservice/"));
apiRequest.setProvider(user.getUserName());
apiRequest.setVersion("1.0.0");
HttpResponse addResponse = restAPIPublisher.addAPI(apiRequest);
String apiID = addResponse.getData();
apiRequest.setApiTier(requestCountPolicyDTO.getPolicyName());
restAPIPublisher.updateAPI(apiRequest, apiID);
restAPIAdmin = new RestAPIAdminImpl(ADMIN2_USERNAME, PASSWORD, user.getUserDomain(),
adminURLHttps);
try {
restAPIAdmin.deleteAdvancedThrottlingPolicy(policyId);
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_FORBIDDEN);
} finally {
if (apiID != null) {
restAPIPublisher.deleteAPI(apiID);
}
}
}
@Test(groups = {"wso2.am"}, description = "Test delete advanced throttling policy assigned to a resource created " +
"with a different admin user ", dependsOnMethods = "testDeleteAssignedAPILevelAdvancedPolicyWithDifferentAdminUser")
public void testDeleteAssignedResourceLevelAdvancedPolicyWithDifferentAdminUser() throws Exception {
restAPIAdmin = new RestAPIAdminImpl(ADMIN1_USERNAME, PASSWORD, user.getUserDomain(),
adminURLHttps);
requestCountPolicyDTO = createThrottlingPolicy("TestPolicyAdmin3");
//Add the advanced throttling policy
ApiResponse<AdvancedThrottlePolicyDTO> addedPolicy =
restAPIAdmin.addAdvancedThrottlingPolicy(requestCountPolicyDTO);
//Assert the status code and policy ID
Assert.assertEquals(addedPolicy.getStatusCode(), HttpStatus.SC_CREATED);
AdvancedThrottlePolicyDTO addedPolicyDTO = addedPolicy.getData();
String policyId = addedPolicyDTO.getPolicyId();
Assert.assertNotNull(policyId, "The policy ID cannot be null or empty");
requestCountPolicyDTO.setPolicyId(policyId);
requestCountPolicyDTO.setIsDeployed(true);
//Verify the created advanced throttling policy DTO
adminApiTestHelper.verifyAdvancedThrottlePolicyDTO(requestCountPolicyDTO, addedPolicyDTO);
//Create API and assign policy to resource
APIRequest apiRequest = new APIRequest("AdvancedThrottlingPolicyTestAPI3",
"AdvancedThrottlingPolicyTestAPI3", new URL(backEndServerUrl.getWebAppURLHttp() +
"jaxrs_basic/services/customers/customerservice/"));
apiRequest.setProvider(user.getUserName());
apiRequest.setVersion("1.0.0");
APIOperationsDTO apiOperationsDTO = new APIOperationsDTO();
apiOperationsDTO.setVerb("GET");
apiOperationsDTO.setTarget("/customers/{id}");
apiOperationsDTO.setAuthType("None");
apiOperationsDTO.setThrottlingPolicy(requestCountPolicyDTO.getPolicyName());
List<APIOperationsDTO> operationsDTOS = new ArrayList<>();
operationsDTOS.add(apiOperationsDTO);
apiRequest.setOperationsDTOS(operationsDTOS);
HttpResponse addResponse = restAPIPublisher.addAPI(apiRequest);
String apiID = addResponse.getData();
Assert.assertNotNull(apiID);
restAPIAdmin = new RestAPIAdminImpl(ADMIN2_USERNAME, PASSWORD, user.getUserDomain(),
adminURLHttps);
try {
restAPIAdmin.deleteAdvancedThrottlingPolicy(policyId);
} catch (ApiException e) {
Assert.assertEquals(e.getCode(), HttpStatus.SC_FORBIDDEN);
} finally {
if (apiID != null) {
restAPIPublisher.deleteAPI(apiID);
}
}
}
/**
* Creates a conditional group with a list of conditions
*
* @param limit Throttle limit of the conditional group.
* @return Created conditional group DTO
*/
public ConditionalGroupDTO createConditionalGroup(ThrottleLimitDTO limit) {
String conditionalGroupDescription = "This is a test conditional group";
List<ThrottleConditionDTO> conditions = createThrottlingConditions();
return DtoFactory.createConditionalGroupDTO(conditionalGroupDescription, conditions, limit);
}
/**
* Creates a list of throttling conditions
*
* @return Created list of throttling condition DTOs
*/
public List<ThrottleConditionDTO> createThrottlingConditions() {
List<ThrottleConditionDTO> throttleConditions = new ArrayList<>();
//Create the IP condition and add it to the throttle conditions list
String specificIP = "10.100.1.22";
IPConditionDTO ipConditionDTO =
DtoFactory.createIPConditionDTO(IPConditionDTO.IpConditionTypeEnum.IPSPECIFIC, specificIP, null, null);
ThrottleConditionDTO ipCondition = DtoFactory
.createThrottleConditionDTO(ThrottleConditionDTO.TypeEnum.IPCONDITION, false, null, ipConditionDTO,
null, null);
throttleConditions.add(ipCondition);
//Create the header condition and add it to the throttle conditions list
String headerName = "Host";
String headerValue = "10.100.7.77";
HeaderConditionDTO headerConditionDTO = DtoFactory.createHeaderConditionDTO(headerName, headerValue);
ThrottleConditionDTO headerCondition = DtoFactory
.createThrottleConditionDTO(ThrottleConditionDTO.TypeEnum.HEADERCONDITION, false, headerConditionDTO,
null, null, null);
throttleConditions.add(headerCondition);
//Create the query parameter condition and add it to the throttle conditions list
String claimUrl = "claimUrl";
String attribute = "claimAttribute";
QueryParameterConditionDTO queryParameterConditionDTO =
DtoFactory.createQueryParameterConditionDTO(claimUrl, attribute);
ThrottleConditionDTO queryParameterCondition = DtoFactory
.createThrottleConditionDTO(ThrottleConditionDTO.TypeEnum.QUERYPARAMETERCONDITION, false, null, null,
null, queryParameterConditionDTO);
throttleConditions.add(queryParameterCondition);
//Create the JWT claims condition and add it to the throttle conditions list
String parameterName = "name";
String parameterValue = "admin";
JWTClaimsConditionDTO jwtClaimsConditionDTO =
DtoFactory.createJWTClaimsConditionDTO(parameterName, parameterValue);
ThrottleConditionDTO jwtClaimsCondition = DtoFactory
.createThrottleConditionDTO(ThrottleConditionDTO.TypeEnum.JWTCLAIMSCONDITION, false, null, null,
jwtClaimsConditionDTO, null);
throttleConditions.add(jwtClaimsCondition);
return throttleConditions;
}
/**
* Creates an Advanced Throttling Policy
*
* @return Created Advanced Throttling Policy
*/
public AdvancedThrottlePolicyDTO createThrottlingPolicy(String policyName) {
AdvancedThrottlePolicyDTO advancedThrottlePolicyDTO;
Long requestCount = 10L;
List<ConditionalGroupDTO> conditionalGroups = new ArrayList<>();
RequestCountLimitDTO requestCountLimit =
DtoFactory.createRequestCountLimitDTO(timeUnitHour, unitTime, requestCount);
ThrottleLimitDTO defaultLimit =
DtoFactory.createThrottleLimitDTO(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT, requestCountLimit, null);
advancedThrottlePolicyDTO = DtoFactory
.createAdvancedThrottlePolicyDTO(policyName, displayName, description, false, defaultLimit,
conditionalGroups);
return advancedThrottlePolicyDTO;
}
/**
* @param apiContext
* @param requestHeaders
*/
private void verifyThrottling(String apiContext, Map<String, String> requestHeaders) throws Exception {
waitUntilClockHour();
boolean isThrottled = false;
for (int invocationCount = 0; invocationCount < 20; invocationCount++) {
//Invoke API
HttpResponse invokeResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttps(apiContext, "1.0.0") + API_END_POINT_METHOD,
requestHeaders);
if (invokeResponse.getResponseCode() == 429) {
Assert.assertTrue(invocationCount >= 10);
isThrottled = true;
break;
}
Thread.sleep(1000);
}
Assert.assertTrue(isThrottled, "Request not throttled by Throttling Policy");
}
/**
* Gets Throttling policies of resources
*
* @return List of Throttling policies
*/
private List<Object> getResourceThrottlingPolicies(String swaggerContent) throws APIManagementException {
OpenAPIParser parser = new OpenAPIParser();
SwaggerParseResult swaggerParseResult = parser.readContents(swaggerContent, null, null);
OpenAPI openAPI = swaggerParseResult.getOpenAPI();
Paths paths = openAPI.getPaths();
List<Object> throttlingPolicies = new ArrayList<>();
for (String pathKey : paths.keySet()) {
Map<PathItem.HttpMethod, Operation> operationsMap = paths.get(pathKey).readOperationsMap();
for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
Operation operation = entry.getValue();
Map<String, Object> extensions = operation.getExtensions();
Assert.assertNotNull(extensions.get("x-throttling-tier"));
throttlingPolicies.add(extensions.get("x-throttling-tier"));
}
}
return throttlingPolicies;
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
restAPIAdmin.deleteAdvancedThrottlingPolicy(bandwidthPolicyDTO.getPolicyId());
restAPIAdmin.deleteAdvancedThrottlingPolicy(conditionalGroupsPolicyDTO.getPolicyId());
restAPIStore.deleteApplication(applicationId1);
restAPIStore.deleteApplication(applicationId2);
restAPIPublisher.deleteAPI(apiId1);
restAPIPublisher.deleteAPI(apiId2);
}
}
| {
"content_hash": "3df98708fc9ec516e0917360ee04c6d9",
"timestamp": "",
"source": "github",
"line_count": 683,
"max_line_length": 128,
"avg_line_length": 51.796486090775986,
"alnum_prop": 0.7183763462136417,
"repo_name": "chamilaadhi/product-apim",
"id": "f75fb5c2bc12e3738ae09311c40d1c8691c30201",
"size": "36026",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/restapi/admin/throttlingpolicy/AdvancedThrottlingPolicyTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34412"
},
{
"name": "CSS",
"bytes": "62967"
},
{
"name": "HTML",
"bytes": "19955"
},
{
"name": "Handlebars",
"bytes": "2861"
},
{
"name": "Java",
"bytes": "14979392"
},
{
"name": "JavaScript",
"bytes": "306906"
},
{
"name": "Jinja",
"bytes": "464508"
},
{
"name": "Jupyter Notebook",
"bytes": "4346"
},
{
"name": "Less",
"bytes": "199838"
},
{
"name": "Mustache",
"bytes": "71460"
},
{
"name": "Python",
"bytes": "39021"
},
{
"name": "Scala",
"bytes": "3419"
},
{
"name": "Shell",
"bytes": "45764"
},
{
"name": "XSLT",
"bytes": "8193"
}
],
"symlink_target": ""
} |
/**
* author: shimmy rothstein
* directive for adding logging ability to html elements
*
* add client-logger attribute to element.
* add name-to-log attribute with desired name
* add action-to-log attribute with desired events to log, if multiple seperate with ',' (defualt is "change")
* add value-to-log attribute with name of desired value to add to log (defualt is "value")
*
* Inject 'ClientLogger' into client module and controller
*
* API:
* ClientLogService.setAddress("your address here");
*
* ClientLogService.setBuffer(num)
*
* ClientLogService.addLog(obj) where obj type of {elementName: "chosen element", elementType: "chosen element type", action: "event", value: "value"}
*
* ClientLogService.getLog()
*
* ClientLogService.deleteLog()
*
* ClientLogService.emptyLog()
*
* ClientLogService.sendLogTo(address)
*
* DeveloperLogService.rerunLog()
*
* log is array of {time: "time of log", log: {elementName: "chosen element", elementType: "chosen element type", action: "event", value: "value"}}
*
* enjoy
* live long and prosper \V/
*/
var ConfigObject = function () {
return {
App: "ClientLogger",
Controller: "Loggercntrl",
ClientLogService: 'ClientLogService',
DeveloperLogService: 'DeveloperLogService',
UniqueIdService: 'UniqueIdService',
Directive: 'clientLogger',
OverlayDirective: 'loggerOverLay',
DirectiveUse: 'client-logger',
IdAttribute: 'logger-id'
}
}();
angular.isUndefinedOrNull = function (val) {
return angular.isUndefined(val) || val === null;
}
var app = angular.module(ConfigObject.App, []);
app.run();
app.service(ConfigObject.UniqueIdService, function () {
return new function () {
var self = this;
var nextId = 0;
self.getUniqueId = function () { return nextId++; };
}
});
app.service(ConfigObject.DeveloperLogService, function ($timeout, ClientLogService) {
return new DeveloperLogServiceObj($timeout, ClientLogService);
});
function DeveloperLogServiceObj($timeout, ClientLogService) {
var self = this;
var rerunStack = [];
self.logMessages = [];
//add log to stack
var borderStyle = document.createElement('style');
borderStyle.innerHTML = '.logCurrentAction{border-style:inset; border-color:#f09942; border-width:5px;}';
document.head.appendChild(borderStyle);
self.speed;
var loggerOverlay = null;
var rerunLoop = function (i) {
if (i >= rerunStack.length) {
ClientLogService.allowLogging = true;
loggerOverlay.css('display', 'none');
self.logMessages = {};
return;
}
var string = "[" + ConfigObject.IdAttribute + "=\"" + rerunStack[i].log.loggerId + "\"]";
var JQElem = document.querySelector(string);
var elem = angular.element(JQElem);
if (angular.isUndefinedOrNull(JQElem)) {
rerunStack[i].log.message = "Element no longer exists in html"
} else {
elem.addClass('logCurrentAction');
elem.val(rerunStack[i].log.value);
elem.triggerHandler(rerunStack[i].log.action);
}
self.logMessages = rerunStack[i].log;//put in if(elem exsits)
$timeout(function (elem, i) {
elem.removeClass('logCurrentAction');
$timeout(function (i) { rerunLoop(i + 1); }, 400, true, i);
}, self.speed, true, elem, i);
}
//play log
self.rerunLog = function (stack) {
if (angular.isUndefinedOrNull(stack)) {
rerunStack = ClientLogService.getLog();
} else {
rerunStack = stack;
}
if (angular.isUndefinedOrNull(loggerOverlay)) {
loggerOverlay = angular.element(document.querySelector('#loggerOverlay'))
}
loggerOverlay.css('display', 'initial');
ClientLogService.allowLogging = false;
rerunLoop(0);
}
}
app.service(ConfigObject.ClientLogService, function ($http, $window) {
return new ClientLogServiceObj($http, $window);
});
function ClientLogServiceObj($http, $window) {
var self = this;
self.allowLogging = true;
//buffer size of log stack
var buffer = 500;
self.setBuffer = function (num) { if (isFinite(num)) { buffer = num }; };
//http address to send log to
var address = undefined;
self.setAddress = function (addrss) { address = addrss };
var LogStack = [];
//add log to stack
self.addLog = function (obj) {
if (!angular.isUndefinedOrNull(obj)) {
if (self.allowLogging) {
LogStack.push({ time: new Date().toLocaleString('en-GB'), log: obj });
}
if (LogStack.length >= buffer && !angular.isUndefinedOrNull(address)) { //buffer reached
self.diluteLog();
}
}
}
//remove first third of log and send to sever if address is available
var diluteLog = function () {
var spliced = LogStack.splice(0, Math.floor(buffer / 3));
if (!angular.isUndefinedOrNull(address)) {
$http.put(address, spliced);
}
};
self.getLog = function () { return LogStack; };
self.deleteLog = function () { LogStack = []; };
self.emptyLog = function () { self.sendLog(); self.deleteLog(); };
//send whole log to server if address is available
self.sendLog = function (adrs) {
if (!angular.isUndefinedOrNull(adrs)) {
$http.put(adrs, LogStack);
} else {
if (!angular.isUndefinedOrNull(address)) {
$http.put(address, LogStack);
}
}
};
//on window close\tab close\refresh send log to server if exsits
$window.onbeforeunload = self.sendLog;
}
app.directive(ConfigObject.Directive, function ($compile, ClientLogService, UniqueIdService) {
var linkFunction = function ($scope, element, attrs) {
$scope.loggerId = UniqueIdService.getUniqueId();
element.attr(ConfigObject.IdAttribute, $scope.loggerId);
if (angular.isUndefinedOrNull($scope.actionsToLog)) {
$scope.actionsToLog = "change";
}
if (angular.isUndefinedOrNull($scope.valueToLog)) {
$scope.valueToLog = "value";
}
var temp = $scope.actionsToLog.split(',');
for (var i = 0; i < temp.length; i++) {
element.on(temp[i], function (event) {
if (!angular.isUndefinedOrNull($scope.valueToLog)) {
ClientLogService.addLog({ elementName: $scope.nameToLog, loggerId: $scope.loggerId, elementType: element[0].localName, action: event.type, value: element[0][$scope.valueToLog] });
}
});
}
};
return {
restrict:'A',
scope: {
actionsToLog: "@",
nameToLog: "@",
valueToLog: "@",
loggerId: "@"
},
link: linkFunction
}
});
app.directive('loggerOverlay', function (DeveloperLogService) {
return {
scope:{
},
replace: true,
template: '<div id="loggerOverlay" style="z-index=999; background-color:rgba(0,0,0,0.1); position:absolute; left:0; top:0; width:100%; height:100%; display:none;">'+
'<div style="height: 20%; width: 20%; position: absolute; right: 0; bottom: 0; background-color: rgba(0,0,0,0.2); ">'+
'<div>speed</div>'+
'<input type="range" min="100" max="5000" ng-model="speed" style="column-rule-color:black; bottom:0; background:orange;" />' +
'<div>Log Messages:</div>' +
'<div>{{logMessages.message}}</div>' +
'<div>Element Name: {{logMessages.elementName}}</div>' +
'<div>Element Type: {{logMessages.elementType}}</div>' +
'<div>Action Logged: {{logMessages.action}}</div>' +
'<div>Value: {{logMessages.value}}</div>' +
'</div>' +
'</div>',
link: function ($scope, element, attrs) {
$scope.logService = DeveloperLogService;
$scope.speed = 4000;
$scope.logService.speed = 5000 - $scope.speed;
$scope.$watch('logService.logMessages', function (newVal, oldVal, scope) {
if (newVal === oldVal) return;
$scope.logMessages = newVal;
})
$scope.$watch('speed', function (newVal, oldVal, scope) {
if (newVal === oldVal) return;
$scope.logService.speed = 5000 - newVal;
})
}
}
});
| {
"content_hash": "9712409c6ae2488ceb1744a3d9242031",
"timestamp": "",
"source": "github",
"line_count": 495,
"max_line_length": 199,
"avg_line_length": 19.167676767676767,
"alnum_prop": 0.5381534569983136,
"repo_name": "shimmz/client-logger",
"id": "7f06691c813037f9aa526c3e9ff1a75737364fcb",
"size": "9488",
"binary": false,
"copies": "1",
"ref": "refs/heads/split-client-and-developer-services",
"path": "ClientLogger.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "9488"
}
],
"symlink_target": ""
} |
/**
* A directive for managing all active Guacamole sessions.
*/
angular.module('settings').directive('guacSettingsSessions', [function guacSettingsSessions() {
return {
// Element only
restrict: 'E',
replace: true,
scope: {
},
templateUrl: 'app/settings/templates/settingsSessions.html',
controller: ['$scope', '$injector', function settingsSessionsController($scope, $injector) {
// Required types
var ActiveConnectionWrapper = $injector.get('ActiveConnectionWrapper');
var ConnectionGroup = $injector.get('ConnectionGroup');
var SortOrder = $injector.get('SortOrder');
// Required services
var $filter = $injector.get('$filter');
var $translate = $injector.get('$translate');
var $q = $injector.get('$q');
var activeConnectionService = $injector.get('activeConnectionService');
var authenticationService = $injector.get('authenticationService');
var connectionGroupService = $injector.get('connectionGroupService');
var dataSourceService = $injector.get('dataSourceService');
var guacNotification = $injector.get('guacNotification');
/**
* The identifiers of all data sources accessible by the current
* user.
*
* @type String[]
*/
var dataSources = authenticationService.getAvailableDataSources();
/**
* The ActiveConnectionWrappers of all active sessions accessible
* by the current user, or null if the active sessions have not yet
* been loaded.
*
* @type ActiveConnectionWrapper[]
*/
$scope.wrappers = null;
/**
* SortOrder instance which maintains the sort order of the visible
* connection wrappers.
*
* @type SortOrder
*/
$scope.wrapperOrder = new SortOrder([
'activeConnection.username',
'startDate',
'activeConnection.remoteHost',
'name'
]);
/**
* Array of all wrapper properties that are filterable.
*
* @type String[]
*/
$scope.filteredWrapperProperties = [
'activeConnection.username',
'startDate',
'activeConnection.remoteHost',
'name'
];
/**
* All active connections, if known, grouped by corresponding data
* source identifier, or null if active connections have not yet
* been loaded.
*
* @type Object.<String, Object.<String, ActiveConnection>>
*/
var allActiveConnections = null;
/**
* Map of all visible connections by data source identifier and
* object identifier, or null if visible connections have not yet
* been loaded.
*
* @type Object.<String, Object.<String, Connection>>
*/
var allConnections = null;
/**
* The date format for use for session-related dates.
*
* @type String
*/
var sessionDateFormat = null;
/**
* Map of all currently-selected active connection wrappers by
* data source and identifier.
*
* @type Object.<String, Object.<String, ActiveConnectionWrapper>>
*/
var allSelectedWrappers = {};
/**
* Adds the given connection to the internal set of visible
* connections.
*
* @param {String} dataSource
* The identifier of the data source associated with the given
* connection.
*
* @param {Connection} connection
* The connection to add to the internal set of visible
* connections.
*/
var addConnection = function addConnection(dataSource, connection) {
// Add given connection to set of visible connections
allConnections[dataSource][connection.identifier] = connection;
};
/**
* Adds all descendant connections of the given connection group to
* the internal set of connections.
*
* @param {String} dataSource
* The identifier of the data source associated with the given
* connection group.
*
* @param {ConnectionGroup} connectionGroup
* The connection group whose descendant connections should be
* added to the internal set of connections.
*/
var addDescendantConnections = function addDescendantConnections(dataSource, connectionGroup) {
// Add all child connections
angular.forEach(connectionGroup.childConnections, function addConnectionForDataSource(connection) {
addConnection(dataSource, connection);
});
// Add all child connection groups
angular.forEach(connectionGroup.childConnectionGroups, function addConnectionGroupForDataSource(connectionGroup) {
addDescendantConnections(dataSource, connectionGroup);
});
};
/**
* Wraps all loaded active connections, storing the resulting array
* within the scope. If required data has not yet finished loading,
* this function has no effect.
*/
var wrapAllActiveConnections = function wrapAllActiveConnections() {
// Abort if not all required data is available
if (!allActiveConnections || !allConnections || !sessionDateFormat)
return;
// Wrap all active connections for sake of display
$scope.wrappers = [];
angular.forEach(allActiveConnections, function wrapActiveConnections(activeConnections, dataSource) {
angular.forEach(activeConnections, function wrapActiveConnection(activeConnection, identifier) {
// Retrieve corresponding connection
var connection = allConnections[dataSource][activeConnection.connectionIdentifier];
// Add wrapper
$scope.wrappers.push(new ActiveConnectionWrapper({
dataSource : dataSource,
name : connection.name,
startDate : $filter('date')(activeConnection.startDate, sessionDateFormat),
activeConnection : activeConnection
}));
});
});
};
// Retrieve all connections
dataSourceService.apply(
connectionGroupService.getConnectionGroupTree,
dataSources,
ConnectionGroup.ROOT_IDENTIFIER
)
.then(function connectionGroupsReceived(rootGroups) {
allConnections = {};
// Load connections from each received root group
angular.forEach(rootGroups, function connectionGroupReceived(rootGroup, dataSource) {
allConnections[dataSource] = {};
addDescendantConnections(dataSource, rootGroup);
});
// Attempt to produce wrapped list of active connections
wrapAllActiveConnections();
});
// Query active sessions
dataSourceService.apply(
activeConnectionService.getActiveConnections,
dataSources
)
.then(function sessionsRetrieved(retrievedActiveConnections) {
// Store received map of active connections
allActiveConnections = retrievedActiveConnections;
// Attempt to produce wrapped list of active connections
wrapAllActiveConnections();
});
// Get session date format
$translate('SETTINGS_SESSIONS.FORMAT_STARTDATE').then(function sessionDateFormatReceived(retrievedSessionDateFormat) {
// Store received date format
sessionDateFormat = retrievedSessionDateFormat;
// Attempt to produce wrapped list of active connections
wrapAllActiveConnections();
});
/**
* Returns whether critical data has completed being loaded.
*
* @returns {Boolean}
* true if enough data has been loaded for the user interface
* to be useful, false otherwise.
*/
$scope.isLoaded = function isLoaded() {
return $scope.wrappers !== null;
};
/**
* An action to be provided along with the object sent to
* showStatus which closes the currently-shown status dialog.
*/
var ACKNOWLEDGE_ACTION = {
name : "SETTINGS_SESSIONS.ACTION_ACKNOWLEDGE",
// Handle action
callback : function acknowledgeCallback() {
guacNotification.showStatus(false);
}
};
/**
* An action to be provided along with the object sent to
* showStatus which closes the currently-shown status dialog.
*/
var CANCEL_ACTION = {
name : "SETTINGS_SESSIONS.ACTION_CANCEL",
// Handle action
callback : function cancelCallback() {
guacNotification.showStatus(false);
}
};
/**
* An action to be provided along with the object sent to
* showStatus which immediately deletes the currently selected
* sessions.
*/
var DELETE_ACTION = {
name : "SETTINGS_SESSIONS.ACTION_DELETE",
className : "danger",
// Handle action
callback : function deleteCallback() {
deleteAllSessionsImmediately();
guacNotification.showStatus(false);
}
};
/**
* Immediately deletes the selected sessions, without prompting the
* user for confirmation.
*/
var deleteAllSessionsImmediately = function deleteAllSessionsImmediately() {
var deletionRequests = [];
// Perform deletion for each relevant data source
angular.forEach(allSelectedWrappers, function deleteSessionsImmediately(selectedWrappers, dataSource) {
// Delete sessions, if any are selected
var identifiers = Object.keys(selectedWrappers);
if (identifiers.length)
deletionRequests.push(activeConnectionService.deleteActiveConnections(dataSource, identifiers));
});
// Update interface
$q.all(deletionRequests)
.then(function activeConnectionsDeleted() {
// Remove deleted connections from wrapper array
$scope.wrappers = $scope.wrappers.filter(function activeConnectionStillExists(wrapper) {
return !(wrapper.activeConnection.identifier in (allSelectedWrappers[wrapper.dataSource] || {}));
});
// Clear selection
allSelectedWrappers = {};
},
// Notify of any errors
function activeConnectionDeletionFailed(error) {
guacNotification.showStatus({
'className' : 'error',
'title' : 'SETTINGS_SESSIONS.DIALOG_HEADER_ERROR',
'text' : error.message,
'actions' : [ ACKNOWLEDGE_ACTION ]
});
});
};
/**
* Delete all selected sessions, prompting the user first to
* confirm that deletion is desired.
*/
$scope.deleteSessions = function deleteSessions() {
// Confirm deletion request
guacNotification.showStatus({
'title' : 'SETTINGS_SESSIONS.DIALOG_HEADER_CONFIRM_DELETE',
'text' : 'SETTINGS_SESSIONS.TEXT_CONFIRM_DELETE',
'actions' : [ DELETE_ACTION, CANCEL_ACTION]
});
};
/**
* Returns whether the selected sessions can be deleted.
*
* @returns {Boolean}
* true if selected sessions can be deleted, false otherwise.
*/
$scope.canDeleteSessions = function canDeleteSessions() {
// We can delete sessions if at least one is selected
for (var dataSource in allSelectedWrappers) {
for (var identifier in allSelectedWrappers[dataSource])
return true;
}
return false;
};
/**
* Called whenever an active connection wrapper changes selected
* status.
*
* @param {ActiveConnectionWrapper} wrapper
* The wrapper whose selected status has changed.
*/
$scope.wrapperSelectionChange = function wrapperSelectionChange(wrapper) {
// Get selection map for associated data source, creating if necessary
var selectedWrappers = allSelectedWrappers[wrapper.dataSource];
if (!selectedWrappers)
selectedWrappers = allSelectedWrappers[wrapper.dataSource] = {};
// Add wrapper to map if selected
if (wrapper.checked)
selectedWrappers[wrapper.activeConnection.identifier] = wrapper;
// Otherwise, remove wrapper from map
else
delete selectedWrappers[wrapper.activeConnection.identifier];
};
}]
};
}]);
| {
"content_hash": "95689f02e3bf3dd6816f4805791aedcd",
"timestamp": "",
"source": "github",
"line_count": 385,
"max_line_length": 130,
"avg_line_length": 38.9038961038961,
"alnum_prop": 0.5231673120576846,
"repo_name": "DaanWillemsen/guacamole-client",
"id": "0b1d806a2f00d669869771e916a8a7b87881ba2d",
"size": "15785",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "guacamole/src/main/webapp/app/settings/directives/guacSettingsSessions.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "100882"
},
{
"name": "HTML",
"bytes": "55251"
},
{
"name": "Java",
"bytes": "1585154"
},
{
"name": "JavaScript",
"bytes": "1256220"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hbase.client;
import static org.junit.Assert.fail;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Category({ ClientTests.class, MediumTests.class })
public class TestCISleep extends AbstractTestCITimeout {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestCISleep.class);
private static Logger LOG = LoggerFactory.getLogger(TestCISleep.class);
private TableName tableName;
@Before
public void setUp() {
tableName = TableName.valueOf(name.getMethodName());
}
/**
* Test starting from 0 index when RpcRetryingCaller calculate the backoff time.
*/
@Test
public void testRpcRetryingCallerSleep() throws Exception {
TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
.setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAM_NAM))
.setCoprocessor(CoprocessorDescriptorBuilder.newBuilder(SleepAndFailFirstTime.class.getName())
.setProperty(SleepAndFailFirstTime.SLEEP_TIME_CONF_KEY, String.valueOf(2000))
.build())
.build();
TEST_UTIL.getAdmin().createTable(htd);
Configuration c = new Configuration(TEST_UTIL.getConfiguration());
c.setInt(HConstants.HBASE_CLIENT_PAUSE, 3000);
c.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 4000);
try (Connection conn = ConnectionFactory.createConnection(c)) {
SleepAndFailFirstTime.ct.set(0);
try (Table table = conn.getTableBuilder(tableName, null).setOperationTimeout(8000).build()) {
// Check that it works. Because 2s + 3s * RETRY_BACKOFF[0] + 2s < 8s
table.get(new Get(FAM_NAM));
}
SleepAndFailFirstTime.ct.set(0);
try (Table table = conn.getTableBuilder(tableName, null).setOperationTimeout(6000).build()) {
// Will fail this time. After sleep, there are not enough time for second retry
// Beacuse 2s + 3s + 2s > 6s
table.get(new Get(FAM_NAM));
fail("We expect an exception here");
} catch (RetriesExhaustedException e) {
LOG.info("We received an exception, as expected ", e);
}
}
}
}
| {
"content_hash": "06f3887cee2f6ec81bcac5c650f07c26",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 100,
"avg_line_length": 37.028985507246375,
"alnum_prop": 0.7322896281800392,
"repo_name": "francisliu/hbase",
"id": "1c8480931ef354b08c52e55a5f6e47393bd5a7de",
"size": "3361",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestCISleep.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25343"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "56085"
},
{
"name": "CMake",
"bytes": "13186"
},
{
"name": "CSS",
"bytes": "37063"
},
{
"name": "Dockerfile",
"bytes": "15673"
},
{
"name": "Groovy",
"bytes": "42572"
},
{
"name": "HTML",
"bytes": "17275"
},
{
"name": "Java",
"bytes": "36671577"
},
{
"name": "JavaScript",
"bytes": "9342"
},
{
"name": "Makefile",
"bytes": "1359"
},
{
"name": "PHP",
"bytes": "8385"
},
{
"name": "Perl",
"bytes": "383739"
},
{
"name": "Python",
"bytes": "127994"
},
{
"name": "Ruby",
"bytes": "696921"
},
{
"name": "Shell",
"bytes": "305875"
},
{
"name": "Thrift",
"bytes": "55223"
},
{
"name": "XSLT",
"bytes": "6764"
}
],
"symlink_target": ""
} |
from urllib import request
response = request.urlopen('http://localhost:8080/')
print('RESPONSE:', response)
print('URL :', response.geturl())
headers = response.info()
print('DATE :', headers['date'])
print('HEADERS :')
print('---------')
print(headers)
data = response.read().decode('utf-8')
print('LENGTH :', len(data))
print('DATA :')
print('---------')
print(data)
| {
"content_hash": "439290451826b1e7afec22f762861934",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 52,
"avg_line_length": 22.58823529411765,
"alnum_prop": 0.625,
"repo_name": "jasonwee/asus-rt-n14uhp-mrtg",
"id": "6920c2d964798c6a32666f3e9cfdd7420ed6238f",
"size": "384",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lesson_the_internet/urllib_request_urlopen.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45876"
},
{
"name": "HTML",
"bytes": "107072"
},
{
"name": "JavaScript",
"bytes": "161335"
},
{
"name": "Python",
"bytes": "6923750"
},
{
"name": "Shell",
"bytes": "7616"
}
],
"symlink_target": ""
} |
<?php
namespace Pagekit\Auth\Handler;
use Pagekit\Cookie\CookieJar;
use Pagekit\Database\Connection;
use RandomLib\Generator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class DatabaseHandler implements HandlerInterface
{
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
const STATUS_REMEMBERED = 2;
/**
* @var array
*/
protected $config;
/**
* @var CookieJar
*/
protected $cookie;
/**
* @var RequestStack
*/
protected $requests;
/**
* @var Connection
*/
protected $connection;
/**
* @var Generator
*/
protected $random;
/**
* Constructor.
*
* @param Connection $connection
* @param RequestStack $requests
* @param CookieJar $cookie
* @param Generator $random
* @param array $config
*/
public function __construct(Connection $connection, RequestStack $requests, CookieJar $cookie, Generator $random, $config = null)
{
$this->connection = $connection;
$this->requests = $requests;
$this->cookie = $cookie;
$this->random = $random;
$this->config = $config;
}
/**
* {@inheritdoc}
*/
public function read()
{
if ($token = $this->getToken() and $data = $this->connection->executeQuery("SELECT user_id, status, access FROM {$this->config['table']} WHERE id = :id AND status > :status", [
'id' => sha1($token),
'status' => self::STATUS_INACTIVE
])->fetch(\PDO::FETCH_ASSOC)) {
if (strtotime($data['access']) + $this->config['timeout'] < time()) {
if ($data['status'] == self::STATUS_REMEMBERED) {
$this->write($data['user_id'], self::STATUS_REMEMBERED);
} else {
return null;
}
}
$this->connection->update($this->config['table'], ['access' => date('Y-m-d H:i:s')], ['id' => sha1($token)]);
return $data['user_id'];
}
return null;
}
/**
* {@inheritdoc}
*/
public function write($user, $remember = false)
{
if ($token = $this->getToken()) {
$this->connection->delete($this->config['table'], ['id' => sha1($token)]);
}
$id = $this->random->generateString(64);
$this->cookie->set($this->config['cookie']['name'], $id, $this->config['cookie']['lifetime'] + time());
$this->createTable();
$this->connection->insert($this->config['table'], [
'id' => sha1($id),
'user_id' => $user,
'access' => date('Y-m-d H:i:s'),
'status' => $remember ? self::STATUS_REMEMBERED : self::STATUS_ACTIVE,
'data' => json_encode([
'ip' => $this->getRequest()->getClientIp(),
'user-agent' => $this->getRequest()->headers->get('User-Agent')
])
]);
}
/**
* {@inheritdoc}
*/
public function destroy()
{
if ($token = $this->getToken()) {
$this->connection->update($this->config['table'], ['status' => 0], ['id' => sha1($token)]);
}
}
/**
* Gets the token from the request.
*
* @return mixed
*/
protected function getToken()
{
if ($request = $this->getRequest()) {
return $request->cookies->get($this->config['cookie']['name']);
}
}
/**
* @return null|Request
*/
protected function getRequest()
{
return $this->requests->getCurrentRequest();
}
/**
* @deprecated to be removed in Pagekit 1.0
*/
protected function createTable()
{
$util = $this->connection->getUtility();
if ($util->tableExists($this->config['table']) === false) {
$util->createTable($this->config['table'], function ($table) {
$table->addColumn('id', 'string', ['length' => 255]);
$table->addColumn('user_id', 'integer', ['unsigned' => true, 'length' => 10, 'default' => 0]);
$table->addColumn('access', 'datetime', ['notnull' => false]);
$table->addColumn('status', 'smallint');
$table->addColumn('data', 'json_array', ['notnull' => false]);
$table->setPrimaryKey(['id']);
});
}
}
}
| {
"content_hash": "95f1fed11d979b93b090ea636ef32cde",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 184,
"avg_line_length": 27.51851851851852,
"alnum_prop": 0.5098698968147152,
"repo_name": "brandon-james105/armstrongbcm",
"id": "a17b8e50d8d9d34766c07349a7d7d5e3ffee2f9d",
"size": "4458",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "app/modules/auth/src/Handler/DatabaseHandler.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "142"
},
{
"name": "CSS",
"bytes": "1936466"
},
{
"name": "HTML",
"bytes": "14221"
},
{
"name": "JavaScript",
"bytes": "2854457"
},
{
"name": "PHP",
"bytes": "3679533"
},
{
"name": "Vue",
"bytes": "328931"
}
],
"symlink_target": ""
} |
package se.jiderhamn.classloader.leak.prevention.cleanup;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp;
/**
* Unregister MBeans loaded by the protected class loader
* @author Mattias Jiderhamn
* @author rapla
*/
public class MBeanCleanUp implements ClassLoaderPreMortemCleanUp {
@Override
public void cleanUp(ClassLoaderLeakPreventor preventor) {
try {
final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
// Special treatment for Jetty, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=423255
JettyJMXRemover jettyJMXRemover = null;
if(isJettyWithJMX(preventor)) {
try {
jettyJMXRemover = new JettyJMXRemover(preventor);
}
catch (Exception ex) {
preventor.error(ex);
}
}
// Look for custom MBeans
for(ObjectName objectName : allMBeanNames) {
try {
if (jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName)) {
continue;
}
final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
if(preventor.isClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded by protected ClassLoader
preventor.warn("MBean '" + objectName + "' was loaded by protected ClassLoader; unregistering");
mBeanServer.unregisterMBean(objectName);
}
/*
else if(... instanceof NotificationBroadcasterSupport) {
unregisterNotificationListeners((NotificationBroadcasterSupport) ...);
}
*/
}
catch(Exception e) { // MBeanRegistrationException / InstanceNotFoundException
preventor.error(e);
}
}
}
catch (Exception e) { // MalformedObjectNameException
preventor.error(e);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods and classes for Jetty, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=423255
/** Are we running in Jetty with JMX enabled? */
@SuppressWarnings("WeakerAccess")
protected boolean isJettyWithJMX(ClassLoaderLeakPreventor preventor) {
final ClassLoader classLoader = preventor.getClassLoader();
try {
// If package org.eclipse.jetty is found, we may be running under jetty
if (classLoader.getResource("org/eclipse/jetty") == null) {
return false;
}
Class.forName("org.eclipse.jetty.jmx.MBeanContainer", false, classLoader.getParent()); // JMX enabled?
Class.forName("org.eclipse.jetty.webapp.WebAppContext", false, classLoader.getParent());
}
catch(Exception ex) { // For example ClassNotFoundException
return false;
}
// Seems we are running in Jetty with JMX enabled
return true;
}
/**
* Inner utility class that helps dealing with Jetty MBeans class.
* If you enable JMX support in Jetty 8 or 9 some MBeans (e.g. for the ServletHolder or SessionManager) are
* instantiated in the web application thread and a reference to the WebappClassloader is stored in a private
* ObjectMBean._loader which is unfortunately not the classloader that loaded the class. Therefore we need to access
* the MBeanContainer class of the Jetty container and unregister the MBeans.
*/
private class JettyJMXRemover {
private final ClassLoaderLeakPreventor preventor;
/** List of objects that may be wrapped in MBean by Jetty. Should be allowed to contain null. */
private List<Object> objectsWrappedWithMBean;
/** The org.eclipse.jetty.jmx.MBeanContainer instance */
private Object beanContainer;
/** org.eclipse.jetty.jmx.MBeanContainer.findBean() */
private Method findBeanMethod;
/** org.eclipse.jetty.jmx.MBeanContainer.removeBean() */
private Method removeBeanMethod;
@SuppressWarnings("WeakerAccess")
public JettyJMXRemover(ClassLoaderLeakPreventor preventor) throws Exception {
this.preventor = preventor;
// First we need access to the MBeanContainer to access the beans
// WebAppContext webappContext = (WebAppContext)servletContext;
final Object webappContext = findJettyClass("org.eclipse.jetty.webapp.WebAppClassLoader")
.getMethod("getContext").invoke(preventor.getClassLoader());
if(webappContext == null)
return;
// Server server = (Server)webappContext.getServer();
final Class<?> webAppContextClass = findJettyClass("org.eclipse.jetty.webapp.WebAppContext");
final Object server = webAppContextClass.getMethod("getServer").invoke(webappContext);
if(server == null)
return;
// MBeanContainer beanContainer = (MBeanContainer)server.getBean(MBeanContainer.class);
final Class<?> mBeanContainerClass = findJettyClass("org.eclipse.jetty.jmx.MBeanContainer");
beanContainer = findJettyClass("org.eclipse.jetty.server.Server")
.getMethod("getBean", Class.class).invoke(server, mBeanContainerClass);
// Now we store all objects that belong to the web application and that will be wrapped by MBeans in a list
if (beanContainer != null) {
findBeanMethod = mBeanContainerClass.getMethod("findBean", ObjectName.class);
try {
removeBeanMethod = mBeanContainerClass.getMethod("removeBean", Object.class);
} catch (NoSuchMethodException e) {
preventor.warn("MBeanContainer.removeBean() method can not be found. giving up");
return;
}
objectsWrappedWithMBean = new ArrayList<Object>();
// SessionHandler sessionHandler = webappContext.getSessionHandler();
final Object sessionHandler = webAppContextClass.getMethod("getSessionHandler").invoke(webappContext);
if(sessionHandler != null) {
objectsWrappedWithMBean.add(sessionHandler);
// SessionManager sessionManager = sessionHandler.getSessionManager();
final Object sessionManager = findJettyClass("org.eclipse.jetty.server.session.SessionHandler")
.getMethod("getSessionManager").invoke(sessionHandler);
if(sessionManager != null) {
objectsWrappedWithMBean.add(sessionManager);
// SessionIdManager sessionIdManager = sessionManager.getSessionIdManager();
final Object sessionIdManager = findJettyClass("org.eclipse.jetty.server.SessionManager")
.getMethod("getSessionIdManager").invoke(sessionManager);
objectsWrappedWithMBean.add(sessionIdManager);
}
}
// SecurityHandler securityHandler = webappContext.getSecurityHandler();
objectsWrappedWithMBean.add(webAppContextClass.getMethod("getSecurityHandler").invoke(webappContext));
// ServletHandler servletHandler = webappContext.getServletHandler();
final Object servletHandler = webAppContextClass.getMethod("getServletHandler").invoke(webappContext);
if(servletHandler != null) {
objectsWrappedWithMBean.add(servletHandler);
final Class<?> servletHandlerClass = findJettyClass("org.eclipse.jetty.servlet.ServletHandler");
// Object[] servletMappings = servletHandler.getServletMappings();
objectsWrappedWithMBean.add(Arrays.asList((Object[]) servletHandlerClass.getMethod("getServletMappings").invoke(servletHandler)));
// Object[] servlets = servletHandler.getServlets();
objectsWrappedWithMBean.add(Arrays.asList((Object[]) servletHandlerClass.getMethod("getServlets").invoke(servletHandler)));
}
}
}
/**
* Test if objectName denotes a wrapping Jetty MBean and if so unregister it.
* @return {@code true} if Jetty MBean was unregistered, otherwise {@code false}
*/
boolean unregisterJettyJMXBean(ObjectName objectName) {
if (objectsWrappedWithMBean == null || ! objectName.getDomain().contains("org.eclipse.jetty")) {
return false;
}
else { // Possibly a Jetty MBean that needs to be unregistered
try {
final Object bean = findBeanMethod.invoke(beanContainer, objectName);
if(bean == null)
return false;
// Search suspect list
for (Object wrapped : objectsWrappedWithMBean) {
if (wrapped == bean) {
preventor.warn("Jetty MBean '" + objectName + "' is a suspect in causing memory leaks; unregistering");
removeBeanMethod.invoke(beanContainer, bean); // Remove it via the MBeanContainer
return true;
}
}
}
catch (Exception ex) {
preventor.error(ex);
}
return false;
}
}
Class findJettyClass(String className) throws ClassNotFoundException {
try {
return Class.forName(className, false, preventor.getClassLoader());
} catch (ClassNotFoundException e1) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e2) {
e2.addSuppressed(e1);
throw e2;
}
}
}
}
} | {
"content_hash": "0101980c2a4e394c843168840008a536",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 140,
"avg_line_length": 42.42035398230089,
"alnum_prop": 0.6749765307186816,
"repo_name": "hazendaz/classloader-leak-prevention",
"id": "5c749c26a9791bbc9f03a8f6aa9089d27221f159",
"size": "9587",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "classloader-leak-prevention/classloader-leak-prevention-core/src/main/java/se/jiderhamn/classloader/leak/prevention/cleanup/MBeanCleanUp.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "264141"
}
],
"symlink_target": ""
} |
collectd-warp
=================
collectd writer plugin for Warp 10.
Standard - Install
-------------------
# Install collectd
apt-get install collectd
# Clone the plugin repo
git clone git://github.com/senx/collectd-plugin-warp10.git
# Compile the plugin
cd collectd-warp
javac -classpath /usr/share/collectd-core/java/collectd-api.jar org/collectd/java/WriteWarp.java
Insert this into your `collectd.conf` (likely at `/etc/collectd/collectd.conf`):
# Configure Interval (Time in seconds between 2 values collectd by collectd)
Interval 30
# Configure Timeout (Time before flushing the buffer)
Timeout 120
# Configure JAVA plugin to push data on Warp
LoadPlugin java
<Plugin java>
JVMArg "-Djava.class.path=/usr/share/collectd-core/java/collectd-api.jar:/path/to/collectd-plugin-warp10/"
LoadPlugin "org.collectd.java.WriteWarp"
<Plugin "WriteWarp">
Server "https://HOST:PORT/api/v0/update" "TOKEN" "testing" 100
</Plugin>
</Plugin>
Restart collectd.
If issues detectd with JAVA uninstall collectd
JAVA - Install
--------------
# Clone collectd repo
git clone https://github.com/collectd/collectd.git
# Configure JAVA_HOME environnement variable
export JAVA_HOME=/usr/lib/jvm/java-8-oracle/
# Configure collectd
./configure --with-java=$JAVA_HOME
# Install collectd
make
make install
# Clone the plugin repo
git clone git://github.com/senx/collectd-plugin-warp10.git
# Compile the plugin
cd collectd-warp
$JAVA_HOME/bin/javac -classpath /opt/collectd/share/collectd/java/collectd-api.jar org/collectd/java/WriteWarp.java
Start collect
/opt/collectd/sbin/collectd
| {
"content_hash": "8f6e0cc75077c1115e0a8b7536ce7622",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 118,
"avg_line_length": 29.403508771929825,
"alnum_prop": 0.7130071599045346,
"repo_name": "cityzendata/collectd-plugin-warp10",
"id": "c8c5c0a9cf6f8123dc7226553b2b07b3681e5c20",
"size": "1676",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7947"
}
],
"symlink_target": ""
} |
/**
* @constructor
* @implements {WebInspector.ViewFactory}
*/
WebInspector.AdvancedSearchController = function()
{
this._shortcut = WebInspector.AdvancedSearchController.createShortcut();
this._searchId = 0;
WebInspector.settings.advancedSearchConfig = WebInspector.settings.createSetting("advancedSearchConfig", new WebInspector.SearchConfig("", true, false));
WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this);
WebInspector.inspectorView.registerViewInDrawer("search", WebInspector.UIString("Search"), this);
}
/**
* @return {!WebInspector.KeyboardShortcut.Descriptor}
*/
WebInspector.AdvancedSearchController.createShortcut = function()
{
if (WebInspector.isMac())
return WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.Meta | WebInspector.KeyboardShortcut.Modifiers.Alt);
else
return WebInspector.KeyboardShortcut.makeDescriptor("f", WebInspector.KeyboardShortcut.Modifiers.Ctrl | WebInspector.KeyboardShortcut.Modifiers.Shift);
}
WebInspector.AdvancedSearchController.prototype = {
/**
* @param {string=} id
* @return {WebInspector.View}
*/
createView: function(id)
{
if (!this._searchView)
this._searchView = new WebInspector.SearchView(this);
return this._searchView;
},
/**
* @param {KeyboardEvent} event
* @return {boolean}
*/
handleShortcut: function(event)
{
if (WebInspector.KeyboardShortcut.makeKeyFromEvent(event) === this._shortcut.key) {
if (!this._searchView || !this._searchView.isShowing() || this._searchView._search !== document.activeElement) {
WebInspector.showPanel("sources");
this.show();
} else
WebInspector.inspectorView.closeDrawer();
event.consume(true);
return true;
}
return false;
},
_frameNavigated: function()
{
this.resetSearch();
},
/**
* @param {WebInspector.SearchScope} searchScope
*/
registerSearchScope: function(searchScope)
{
// FIXME: implement multiple search scopes.
this._searchScope = searchScope;
},
show: function()
{
var selection = window.getSelection();
var queryCandidate;
if (selection.rangeCount)
queryCandidate = selection.toString().replace(/\r?\n.*/, "");
if (!this._searchView || !this._searchView.isShowing())
WebInspector.inspectorView.showViewInDrawer("search");
if (queryCandidate)
this._searchView._search.value = queryCandidate;
this._searchView.focus();
this.startIndexing();
},
/**
* @param {boolean} finished
*/
_onIndexingFinished: function(finished)
{
delete this._isIndexing;
this._searchView.indexingFinished(finished);
if (!finished)
delete this._pendingSearchConfig;
if (!this._pendingSearchConfig)
return;
var searchConfig = this._pendingSearchConfig
delete this._pendingSearchConfig;
this._innerStartSearch(searchConfig);
},
startIndexing: function()
{
this._isIndexing = true;
// FIXME: this._currentSearchScope should be initialized based on searchConfig
this._currentSearchScope = this._searchScope;
if (this._progressIndicator)
this._progressIndicator.done();
this._progressIndicator = new WebInspector.ProgressIndicator();
this._searchView.indexingStarted(this._progressIndicator);
this._currentSearchScope.performIndexing(this._progressIndicator, this._onIndexingFinished.bind(this));
},
/**
* @param {number} searchId
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
*/
_onSearchResult: function(searchId, searchResult)
{
if (searchId !== this._searchId)
return;
this._searchView.addSearchResult(searchResult);
if (!searchResult.searchMatches.length)
return;
if (!this._searchResultsPane)
this._searchResultsPane = this._currentSearchScope.createSearchResultsPane(this._searchConfig);
this._searchView.resultsPane = this._searchResultsPane;
this._searchResultsPane.addSearchResult(searchResult);
},
/**
* @param {number} searchId
* @param {boolean} finished
*/
_onSearchFinished: function(searchId, finished)
{
if (searchId !== this._searchId)
return;
if (!this._searchResultsPane)
this._searchView.nothingFound();
this._searchView.searchFinished(finished);
delete this._searchConfig;
},
/**
* @param {WebInspector.SearchConfig} searchConfig
*/
startSearch: function(searchConfig)
{
this.resetSearch();
++this._searchId;
if (!this._isIndexing)
this.startIndexing();
this._pendingSearchConfig = searchConfig;
},
/**
* @param {WebInspector.SearchConfig} searchConfig
*/
_innerStartSearch: function(searchConfig)
{
this._searchConfig = searchConfig;
// FIXME: this._currentSearchScope should be initialized based on searchConfig
this._currentSearchScope = this._searchScope;
if (this._progressIndicator)
this._progressIndicator.done();
this._progressIndicator = new WebInspector.ProgressIndicator();
var totalSearchResultsCount = this._currentSearchScope.performSearch(searchConfig, this._progressIndicator, this._onSearchResult.bind(this, this._searchId), this._onSearchFinished.bind(this, this._searchId));
this._searchView.searchStarted(this._progressIndicator);
},
resetSearch: function()
{
this.stopSearch();
if (this._searchResultsPane) {
this._searchView.resetResults();
delete this._searchResultsPane;
}
},
stopSearch: function()
{
if (this._progressIndicator)
this._progressIndicator.cancel();
if (this._currentSearchScope)
this._currentSearchScope.stopSearch();
delete this._searchConfig;
}
}
/**
* @constructor
* @extends {WebInspector.View}
* @param {WebInspector.AdvancedSearchController} controller
*/
WebInspector.SearchView = function(controller)
{
WebInspector.View.call(this);
this._controller = controller;
this.element.className = "search-view vbox";
this._searchPanelElement = this.element.createChild("div", "search-drawer-header");
this._searchPanelElement.addEventListener("keydown", this._onKeyDown.bind(this), false);
this._searchResultsElement = this.element.createChild("div");
this._searchResultsElement.className = "search-results";
this._search = this._searchPanelElement.createChild("input");
this._search.placeholder = WebInspector.UIString("Search sources");
this._search.setAttribute("type", "text");
this._search.addStyleClass("search-config-search");
this._search.setAttribute("results", "0");
this._search.setAttribute("size", 30);
this._ignoreCaseLabel = this._searchPanelElement.createChild("label");
this._ignoreCaseLabel.addStyleClass("search-config-label");
this._ignoreCaseCheckbox = this._ignoreCaseLabel.createChild("input");
this._ignoreCaseCheckbox.setAttribute("type", "checkbox");
this._ignoreCaseCheckbox.addStyleClass("search-config-checkbox");
this._ignoreCaseLabel.appendChild(document.createTextNode(WebInspector.UIString("Ignore case")));
this._regexLabel = this._searchPanelElement.createChild("label");
this._regexLabel.addStyleClass("search-config-label");
this._regexCheckbox = this._regexLabel.createChild("input");
this._regexCheckbox.setAttribute("type", "checkbox");
this._regexCheckbox.addStyleClass("search-config-checkbox");
this._regexLabel.appendChild(document.createTextNode(WebInspector.UIString("Regular expression")));
this._searchStatusBarElement = this.element.createChild("div", "search-status-bar-summary");
this._searchMessageElement = this._searchStatusBarElement.createChild("span");
this._searchResultsMessageElement = document.createElement("span");
this._load();
}
// Number of recent search queries to store.
WebInspector.SearchView.maxQueriesCount = 20;
WebInspector.SearchView.prototype = {
/**
* @return {WebInspector.SearchConfig}
*/
get searchConfig()
{
return new WebInspector.SearchConfig(this._search.value, this._ignoreCaseCheckbox.checked, this._regexCheckbox.checked);
},
/**
* @type {WebInspector.SearchResultsPane}
*/
set resultsPane(resultsPane)
{
this.resetResults();
this._searchResultsElement.appendChild(resultsPane.element);
},
/**
* @param {WebInspector.ProgressIndicator} progressIndicator
*/
searchStarted: function(progressIndicator)
{
this.resetResults();
this._resetCounters();
this._searchMessageElement.textContent = WebInspector.UIString("Searching...");
progressIndicator.show(this._searchStatusBarElement);
this._updateSearchResultsMessage();
if (!this._searchingView)
this._searchingView = new WebInspector.EmptyView(WebInspector.UIString("Searching..."));
this._searchingView.show(this._searchResultsElement);
},
/**
* @param {WebInspector.ProgressIndicator} progressIndicator
*/
indexingStarted: function(progressIndicator)
{
this._searchMessageElement.textContent = WebInspector.UIString("Indexing...");
progressIndicator.show(this._searchStatusBarElement);
},
/**
* @param {boolean} finished
*/
indexingFinished: function(finished)
{
this._searchMessageElement.textContent = finished ? "" : WebInspector.UIString("Indexing interrupted.");
},
_updateSearchResultsMessage: function()
{
if (this._searchMatchesCount && this._searchResultsCount)
this._searchResultsMessageElement.textContent = WebInspector.UIString("Found %d matches in %d files.", this._searchMatchesCount, this._nonEmptySearchResultsCount);
else
this._searchResultsMessageElement.textContent = "";
},
resetResults: function()
{
if (this._searchingView)
this._searchingView.detach();
if (this._notFoundView)
this._notFoundView.detach();
this._searchResultsElement.removeChildren();
},
_resetCounters: function()
{
this._searchMatchesCount = 0;
this._searchResultsCount = 0;
this._nonEmptySearchResultsCount = 0;
},
nothingFound: function()
{
this.resetResults();
if (!this._notFoundView)
this._notFoundView = new WebInspector.EmptyView(WebInspector.UIString("No matches found."));
this._notFoundView.show(this._searchResultsElement);
this._searchResultsMessageElement.textContent = WebInspector.UIString("No matches found.");
},
/**
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
*/
addSearchResult: function(searchResult)
{
this._searchMatchesCount += searchResult.searchMatches.length;
this._searchResultsCount++;
if (searchResult.searchMatches.length)
this._nonEmptySearchResultsCount++;
this._updateSearchResultsMessage();
},
/**
* @param {boolean} finished
*/
searchFinished: function(finished)
{
this._searchMessageElement.textContent = finished ? WebInspector.UIString("Search finished.") : WebInspector.UIString("Search interrupted.");
},
focus: function()
{
WebInspector.setCurrentFocusElement(this._search);
this._search.select();
},
afterShow: function()
{
this.focus();
},
willHide: function()
{
this._controller.stopSearch();
},
/**
* @param {Event} event
*/
_onKeyDown: function(event)
{
switch (event.keyCode) {
case WebInspector.KeyboardShortcut.Keys.Enter.code:
this._onAction();
break;
}
},
_save: function()
{
var searchConfig = new WebInspector.SearchConfig(this.searchConfig.query, this.searchConfig.ignoreCase, this.searchConfig.isRegex);
WebInspector.settings.advancedSearchConfig.set(searchConfig);
},
_load: function()
{
var searchConfig = WebInspector.settings.advancedSearchConfig.get();
this._search.value = searchConfig.query;
this._ignoreCaseCheckbox.checked = searchConfig.ignoreCase;
this._regexCheckbox.checked = searchConfig.isRegex;
},
_onAction: function()
{
if (!this.searchConfig.query || !this.searchConfig.query.length)
return;
this._save();
this._controller.startSearch(this.searchConfig);
},
__proto__: WebInspector.View.prototype
}
/**
* @constructor
* @param {string} query
* @param {boolean} ignoreCase
* @param {boolean} isRegex
*/
WebInspector.SearchConfig = function(query, ignoreCase, isRegex)
{
this.query = query;
this.ignoreCase = ignoreCase;
this.isRegex = isRegex;
}
/**
* @interface
*/
WebInspector.SearchScope = function()
{
}
WebInspector.SearchScope.prototype = {
/**
* @param {WebInspector.SearchConfig} searchConfig
* @param {WebInspector.Progress} progress
* @param {function(WebInspector.FileBasedSearchResultsPane.SearchResult)} searchResultCallback
* @param {function(boolean)} searchFinishedCallback
*/
performSearch: function(searchConfig, progress, searchResultCallback, searchFinishedCallback) { },
stopSearch: function() { },
/**
* @param {WebInspector.SearchConfig} searchConfig
* @return {WebInspector.SearchResultsPane}
*/
createSearchResultsPane: function(searchConfig) { }
}
/**
* @constructor
* @param {number} offset
* @param {number} length
*/
WebInspector.SearchResult = function(offset, length)
{
this.offset = offset;
this.length = length;
}
/**
* @constructor
* @param {WebInspector.SearchConfig} searchConfig
*/
WebInspector.SearchResultsPane = function(searchConfig)
{
this._searchConfig = searchConfig;
this.element = document.createElement("div");
}
WebInspector.SearchResultsPane.prototype = {
/**
* @return {WebInspector.SearchConfig}
*/
get searchConfig()
{
return this._searchConfig;
},
/**
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
*/
addSearchResult: function(searchResult) { }
}
/**
* @constructor
* @extends {WebInspector.SearchResultsPane}
* @param {WebInspector.SearchConfig} searchConfig
*/
WebInspector.FileBasedSearchResultsPane = function(searchConfig)
{
WebInspector.SearchResultsPane.call(this, searchConfig);
this._searchResults = [];
this.element.id ="search-results-pane-file-based";
this._treeOutlineElement = document.createElement("ol");
this._treeOutlineElement.className = "search-results-outline-disclosure";
this.element.appendChild(this._treeOutlineElement);
this._treeOutline = new TreeOutline(this._treeOutlineElement);
this._matchesExpandedCount = 0;
}
WebInspector.FileBasedSearchResultsPane.matchesExpandedByDefaultCount = 20;
WebInspector.FileBasedSearchResultsPane.fileMatchesShownAtOnce = 20;
WebInspector.FileBasedSearchResultsPane.prototype = {
/**
* @param {WebInspector.UISourceCode} uiSourceCode
* @param {number} lineNumber
* @param {number} columnNumber
* @return {Element}
*/
_createAnchor: function(uiSourceCode, lineNumber, columnNumber)
{
var anchor = document.createElement("a");
anchor.preferredPanel = "sources";
anchor.href = sanitizeHref(uiSourceCode.originURL());
anchor.uiSourceCode = uiSourceCode;
anchor.lineNumber = lineNumber;
return anchor;
},
/**
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
*/
addSearchResult: function(searchResult)
{
this._searchResults.push(searchResult);
var uiSourceCode = searchResult.uiSourceCode;
if (!uiSourceCode)
return;
var searchMatches = searchResult.searchMatches;
var fileTreeElement = this._addFileTreeElement(uiSourceCode.fullDisplayName(), searchMatches.length, this._searchResults.length - 1);
},
/**
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
* @param {TreeElement} fileTreeElement
*/
_fileTreeElementExpanded: function(searchResult, fileTreeElement)
{
if (fileTreeElement._initialized)
return;
var toIndex = Math.min(searchResult.searchMatches.length, WebInspector.FileBasedSearchResultsPane.fileMatchesShownAtOnce);
if (toIndex < searchResult.searchMatches.length) {
this._appendSearchMatches(fileTreeElement, searchResult, 0, toIndex - 1);
this._appendShowMoreMatchesElement(fileTreeElement, searchResult, toIndex - 1);
} else
this._appendSearchMatches(fileTreeElement, searchResult, 0, toIndex);
fileTreeElement._initialized = true;
},
/**
* @param {TreeElement} fileTreeElement
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
* @param {number} fromIndex
* @param {number} toIndex
*/
_appendSearchMatches: function(fileTreeElement, searchResult, fromIndex, toIndex)
{
var uiSourceCode = searchResult.uiSourceCode;
var searchMatches = searchResult.searchMatches;
var regex = createSearchRegex(this._searchConfig.query, !this._searchConfig.ignoreCase, this._searchConfig.isRegex);
for (var i = fromIndex; i < toIndex; ++i) {
var lineNumber = searchMatches[i].lineNumber;
var lineContent = searchMatches[i].lineContent;
var matchRanges = this._regexMatchRanges(lineContent, regex);
var anchor = this._createAnchor(uiSourceCode, lineNumber, matchRanges[0].offset);
var numberString = numberToStringWithSpacesPadding(lineNumber + 1, 4);
var lineNumberSpan = document.createElement("span");
lineNumberSpan.addStyleClass("search-match-line-number");
lineNumberSpan.textContent = numberString;
anchor.appendChild(lineNumberSpan);
var contentSpan = this._createContentSpan(lineContent, matchRanges);
anchor.appendChild(contentSpan);
var searchMatchElement = new TreeElement("", null, false);
searchMatchElement.selectable = false;
fileTreeElement.appendChild(searchMatchElement);
searchMatchElement.listItemElement.className = "search-match source-code";
searchMatchElement.listItemElement.appendChild(anchor);
}
},
/**
* @param {TreeElement} fileTreeElement
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
* @param {number} startMatchIndex
*/
_appendShowMoreMatchesElement: function(fileTreeElement, searchResult, startMatchIndex)
{
var matchesLeftCount = searchResult.searchMatches.length - startMatchIndex;
var showMoreMatchesText = WebInspector.UIString("Show all matches (%d more).", matchesLeftCount);
var showMoreMatchesElement = new TreeElement(showMoreMatchesText, null, false);
fileTreeElement.appendChild(showMoreMatchesElement);
showMoreMatchesElement.listItemElement.addStyleClass("show-more-matches");
showMoreMatchesElement.onselect = this._showMoreMatchesElementSelected.bind(this, searchResult, startMatchIndex, showMoreMatchesElement);
},
/**
* @param {WebInspector.FileBasedSearchResultsPane.SearchResult} searchResult
* @param {number} startMatchIndex
* @param {TreeElement} showMoreMatchesElement
*/
_showMoreMatchesElementSelected: function(searchResult, startMatchIndex, showMoreMatchesElement)
{
var fileTreeElement = showMoreMatchesElement.parent;
fileTreeElement.removeChild(showMoreMatchesElement);
this._appendSearchMatches(fileTreeElement, searchResult, startMatchIndex, searchResult.searchMatches.length);
},
/**
* @param {string} fileName
* @param {number} searchMatchesCount
* @param {number} searchResultIndex
*/
_addFileTreeElement: function(fileName, searchMatchesCount, searchResultIndex)
{
var fileTreeElement = new TreeElement("", null, true);
fileTreeElement.toggleOnClick = true;
fileTreeElement.selectable = false;
this._treeOutline.appendChild(fileTreeElement);
fileTreeElement.listItemElement.addStyleClass("search-result");
var fileNameSpan = document.createElement("span");
fileNameSpan.className = "search-result-file-name";
fileNameSpan.textContent = fileName;
fileTreeElement.listItemElement.appendChild(fileNameSpan);
var matchesCountSpan = document.createElement("span");
matchesCountSpan.className = "search-result-matches-count";
if (searchMatchesCount === 1)
matchesCountSpan.textContent = WebInspector.UIString("(%d match)", searchMatchesCount);
else
matchesCountSpan.textContent = WebInspector.UIString("(%d matches)", searchMatchesCount);
fileTreeElement.listItemElement.appendChild(matchesCountSpan);
var searchResult = this._searchResults[searchResultIndex];
fileTreeElement.onexpand = this._fileTreeElementExpanded.bind(this, searchResult, fileTreeElement);
// Expand until at least certain amount of matches is expanded.
if (this._matchesExpandedCount < WebInspector.FileBasedSearchResultsPane.matchesExpandedByDefaultCount)
fileTreeElement.expand();
this._matchesExpandedCount += searchResult.searchMatches.length;
return fileTreeElement;
},
/**
* @param {string} lineContent
* @param {RegExp} regex
* @return {Array.<WebInspector.SearchResult>}
*/
_regexMatchRanges: function(lineContent, regex)
{
regex.lastIndex = 0;
var match;
var offset = 0;
var matchRanges = [];
while ((regex.lastIndex < lineContent.length) && (match = regex.exec(lineContent)))
matchRanges.push(new WebInspector.SearchResult(match.index, match[0].length));
return matchRanges;
},
/**
* @param {string} lineContent
* @param {Array.<WebInspector.SearchResult>} matchRanges
*/
_createContentSpan: function(lineContent, matchRanges)
{
var contentSpan = document.createElement("span");
contentSpan.className = "search-match-content";
contentSpan.textContent = lineContent;
WebInspector.highlightRangesWithStyleClass(contentSpan, matchRanges, "highlighted-match");
return contentSpan;
},
__proto__: WebInspector.SearchResultsPane.prototype
}
/**
* @constructor
* @param {WebInspector.UISourceCode} uiSourceCode
* @param {Array.<Object>} searchMatches
*/
WebInspector.FileBasedSearchResultsPane.SearchResult = function(uiSourceCode, searchMatches) {
this.uiSourceCode = uiSourceCode;
this.searchMatches = searchMatches;
}
/**
* @type {WebInspector.AdvancedSearchController}
*/
WebInspector.advancedSearchController = null;
| {
"content_hash": "9fe63fe886eb6c5ec73a221dc8c84b64",
"timestamp": "",
"source": "github",
"line_count": 703,
"max_line_length": 216,
"avg_line_length": 34.092460881934564,
"alnum_prop": 0.6721742395794217,
"repo_name": "widged/neo-console-redux",
"id": "7748d1bacf3b7328f4cb206baf723da1883914dd",
"size": "25322",
"binary": false,
"copies": "3",
"ref": "refs/heads/gh-pages",
"path": "electron/lib/react-devtools/blink/Source/devtools/front_end/AdvancedSearchController.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "268769"
},
{
"name": "HTML",
"bytes": "55136"
},
{
"name": "JavaScript",
"bytes": "1413646"
},
{
"name": "Shell",
"bytes": "44"
}
],
"symlink_target": ""
} |
use 5.008001;
use strict;
use warnings;
package Pantry::Model::Environment;
# ABSTRACT: Pantry data model for Chef environments
our $VERSION = '0.012'; # VERSION
use Moose 2;
use MooseX::Types::Path::Class::MoreCoercions qw/File/;
use List::AllUtils qw/uniq first/;
use Pantry::Model::Util qw/hash_to_dot dot_to_hash/;
use namespace::autoclean;
# new_from_file, save_as
with 'Pantry::Role::Serializable' => {
freezer => '_freeze',
thawer => '_thaw',
};
#--------------------------------------------------------------------------#
# Chef environment attributes
#--------------------------------------------------------------------------#
has _path => (
is => 'ro',
reader => 'path',
isa => File,
coerce => 1,
predicate => 'has_path',
);
has name => (
is => 'ro',
isa => 'Str',
required => 1,
);
has description => (
is => 'ro',
isa => 'Str',
lazy_build => 1,
);
sub _build_description {
my $self = shift;
return "The " . $self->name . " environment";
}
has default_attributes => (
is => 'ro',
isa => 'HashRef',
traits => ['Hash'],
default => sub { +{} },
handles => {
set_default_attribute => 'set',
get_default_attribute => 'get',
delete_default_attribute => 'delete',
},
);
has override_attributes => (
is => 'ro',
isa => 'HashRef',
traits => ['Hash'],
default => sub { +{} },
handles => {
set_override_attribute => 'set',
get_override_attribute => 'get',
delete_override_attribute => 'delete',
},
);
sub save {
my ($self) = @_;
die "No _path attribute set" unless $self->has_path;
return $self->save_as( $self->path );
}
my @attribute_keys = qw/default_attributes override_attributes/;
sub _freeze {
my ($self, $data) = @_;
for my $attr ( qw/default_attributes override_attributes/ ) {
my $old = delete $data->{$attr};
my $new = {};
for my $k ( keys %$old ) {
dot_to_hash($new, $k, $old->{$k});
}
$data->{$attr} = $new;
}
$data->{json_class} = "Chef::Environment";
$data->{chef_type} = "environment";
return $data;
}
sub _thaw {
my ($self, $data) = @_;
delete $data->{$_} for qw/json_class chef_type/;
for my $attr ( qw/default_attributes override_attributes/ ) {
my $old = delete $data->{$attr};
my $new = {};
for my $k ( keys %$old ) {
my $v = $old->{$k};
$k =~ s{\.}{\\.}g; # escape existing dots in key
for my $pair ( hash_to_dot($k, $v) ) {
my ($key, $value) = @$pair;
$new->{$key} = $value;
}
}
$data->{$attr} = $new;
}
return $data;
}
1;
# vim: ts=2 sts=2 sw=2 et:
__END__
=pod
=head1 NAME
Pantry::Model::Environment - Pantry data model for Chef environments
=head1 VERSION
version 0.012
=head1 DESCRIPTION
Under development.
=head1 ATTRIBUTES
=head2 default_attributes
This attribute holds environment default attribute data as key-value pairs. Keys may
be separated by a period to indicate nesting (literal periods must be
escaped by a backslash). Values should be scalars or array references.
=head2 override_attributes
This attribute holds environment override attribute data as key-value pairs. Keys may
be separated by a period to indicate nesting (literal periods must be
escaped by a backslash). Values should be scalars or array references.
=head1 METHODS
=head2 set_default_attribute
$environment->set_default_attribute("nginx.port", 80);
Sets the environment default attribute for the given key to the given value.
=head2 get_default_attribute
my $port = $environment->get_default_attribute("nginx.port");
Returns the environment default attribute for the given key.
=head2 delete_default_attribute
$environment->delete_default_attribute("nginx.port");
Deletes the environment default attribute for the given key.
=head2 set_override_attribute
$environment->set_override_attribute("nginx.port", 80);
Sets the environment override attribute for the given key to the given value.
=head2 get_override_attribute
my $port = $environment->get_override_attribute("nginx.port");
Returns the environment override attribute for the given key.
=head2 delete_override_attribute
$environment->delete_override_attribute("nginx.port");
Deletes the environment override attribute for the given key.
=head2 save
Saves the node to a file in the pantry. If the private C<_path>
attribute has not been set, an exception is thrown.
=head1 AUTHOR
David Golden <dagolden@cpan.org>
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2011 by David Golden.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
=cut
| {
"content_hash": "cb8154091a509057927f74671d14c013",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 86,
"avg_line_length": 22.114832535885167,
"alnum_prop": 0.6352228472522717,
"repo_name": "gitpan/Pantry",
"id": "7da4de72b070d4045a8e37a4f0bc5447fb07431e",
"size": "4622",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Pantry/Model/Environment.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Perl",
"bytes": "172307"
}
],
"symlink_target": ""
} |
/**
* \file gcm.h
*
* \brief Galois/Counter Mode (GCM) for 128-bit block ciphers, as defined
* in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation
* (GCM), Natl. Inst. Stand. Technol.</em>
*
* For more information on GCM, see <em>NIST SP 800-38D: Recommendation for
* Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>.
*
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_GCM_H
#define MBEDTLS_GCM_H
#include "cipher.h"
#include <stdint.h>
#define MBEDTLS_GCM_ENCRYPT 1
#define MBEDTLS_GCM_DECRYPT 0
#define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */
#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */
#define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */
#if !defined(MBEDTLS_GCM_ALT)
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The GCM context structure.
*/
typedef struct {
mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */
uint64_t HL[16]; /*!< Precalculated HTable low. */
uint64_t HH[16]; /*!< Precalculated HTable high. */
uint64_t len; /*!< The total length of the encrypted data. */
uint64_t add_len; /*!< The total length of the additional data. */
unsigned char base_ectr[16]; /*!< The first ECTR for tag. */
unsigned char y[16]; /*!< The Y working value. */
unsigned char buf[16]; /*!< The buf working value. */
int mode; /*!< The operation to perform:
#MBEDTLS_GCM_ENCRYPT or
#MBEDTLS_GCM_DECRYPT. */
}
mbedtls_gcm_context;
/**
* \brief This function initializes the specified GCM context,
* to make references valid, and prepares the context
* for mbedtls_gcm_setkey() or mbedtls_gcm_free().
*
* The function does not bind the GCM context to a particular
* cipher, nor set the key. For this purpose, use
* mbedtls_gcm_setkey().
*
* \param ctx The GCM context to initialize.
*/
void mbedtls_gcm_init( mbedtls_gcm_context *ctx );
/**
* \brief This function associates a GCM context with a
* cipher algorithm and a key.
*
* \param ctx The GCM context to initialize.
* \param cipher The 128-bit block cipher to use.
* \param key The encryption key.
* \param keybits The key size in bits. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success, or a cipher specific error code.
*/
int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits );
/**
* \brief This function performs GCM encryption or decryption of a buffer.
*
* \note For encryption, the output buffer can be the same as the input buffer.
* For decryption, the output buffer cannot be the same as input buffer.
* If the buffers overlap, the output buffer must trail at least 8 Bytes
* behind the input buffer.
*
* \param ctx The GCM context to use for encryption or decryption.
* \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or
* #MBEDTLS_GCM_DECRYPT.
* \param length The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
* \param iv The initialization vector.
* \param iv_len The length of the IV.
* \param add The buffer holding the additional data.
* \param add_len The length of the additional data.
* \param input The buffer holding the input data.
* \param output The buffer for holding the output data.
* \param tag_len The length of the tag to generate.
* \param tag The buffer for holding the tag.
*
* \return \c 0 on success.
*/
int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
int mode,
size_t length,
const unsigned char *iv,
size_t iv_len,
const unsigned char *add,
size_t add_len,
const unsigned char *input,
unsigned char *output,
size_t tag_len,
unsigned char *tag );
/**
* \brief This function performs a GCM authenticated decryption of a
* buffer.
*
* \note For decryption, the output buffer cannot be the same as input buffer.
* If the buffers overlap, the output buffer must trail at least 8 Bytes
* behind the input buffer.
*
* \param ctx The GCM context.
* \param length The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
* \param iv The initialization vector.
* \param iv_len The length of the IV.
* \param add The buffer holding the additional data.
* \param add_len The length of the additional data.
* \param tag The buffer holding the tag.
* \param tag_len The length of the tag.
* \param input The buffer holding the input data.
* \param output The buffer for holding the output data.
*
* \return 0 if successful and authenticated, or
* #MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match.
*/
int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
size_t length,
const unsigned char *iv,
size_t iv_len,
const unsigned char *add,
size_t add_len,
const unsigned char *tag,
size_t tag_len,
const unsigned char *input,
unsigned char *output );
/**
* \brief This function starts a GCM encryption or decryption
* operation.
*
* \param ctx The GCM context.
* \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or
* #MBEDTLS_GCM_DECRYPT.
* \param iv The initialization vector.
* \param iv_len The length of the IV.
* \param add The buffer holding the additional data, or NULL if \p add_len is 0.
* \param add_len The length of the additional data. If 0, \p add is NULL.
*
* \return \c 0 on success.
*/
int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
int mode,
const unsigned char *iv,
size_t iv_len,
const unsigned char *add,
size_t add_len );
/**
* \brief This function feeds an input buffer into an ongoing GCM
* encryption or decryption operation.
*
* ` The function expects input to be a multiple of 16
* Bytes. Only the last call before calling
* mbedtls_gcm_finish() can be less than 16 Bytes.
*
* \note For decryption, the output buffer cannot be the same as input buffer.
* If the buffers overlap, the output buffer must trail at least 8 Bytes
* behind the input buffer.
*
* \param ctx The GCM context.
* \param length The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
* \param input The buffer holding the input data.
* \param output The buffer for holding the output data.
*
* \return \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
*/
int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
size_t length,
const unsigned char *input,
unsigned char *output );
/**
* \brief This function finishes the GCM operation and generates
* the authentication tag.
*
* It wraps up the GCM stream, and generates the
* tag. The tag can have a maximum length of 16 Bytes.
*
* \param ctx The GCM context.
* \param tag The buffer for holding the tag.
* \param tag_len The length of the tag to generate. Must be at least four.
*
* \return \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
*/
int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
unsigned char *tag,
size_t tag_len );
/**
* \brief This function clears a GCM context and the underlying
* cipher sub-context.
*
* \param ctx The GCM context to clear.
*/
void mbedtls_gcm_free( mbedtls_gcm_context *ctx );
#ifdef __cplusplus
}
#endif
#else /* !MBEDTLS_GCM_ALT */
#include "gcm_alt.h"
#endif /* !MBEDTLS_GCM_ALT */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The GCM checkup routine.
*
* \return \c 0 on success, or \c 1 on failure.
*/
int mbedtls_gcm_self_test( int verbose );
#ifdef __cplusplus
}
#endif
#endif /* gcm.h */
| {
"content_hash": "4ae07257e9381c1199c8dc1a0e312bdd",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 132,
"avg_line_length": 38.22813688212928,
"alnum_prop": 0.5842450765864332,
"repo_name": "oyooyo/nodemcu-firmware",
"id": "1e5a507a26517b3c232f83a7a4815d71f677b2fb",
"size": "10054",
"binary": false,
"copies": "21",
"ref": "refs/heads/uuid.space-dev",
"path": "app/include/mbedtls/gcm.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "8906"
},
{
"name": "C",
"bytes": "26002770"
},
{
"name": "C++",
"bytes": "96204"
},
{
"name": "HTML",
"bytes": "6678"
},
{
"name": "Lua",
"bytes": "148001"
},
{
"name": "Makefile",
"bytes": "73095"
},
{
"name": "Objective-C",
"bytes": "474"
},
{
"name": "Shell",
"bytes": "261"
}
],
"symlink_target": ""
} |
/*
*
* Travel
*
*/
import React from 'react';
import Page from './../shared/Page';
import PageHeader from './../shared/PageHeader';
import Schedule from './../Travel/Schedule';
import MobileBackground from './../../assets/images/Travel/mobile-travel-header-img.jpg';
import DesktopBackground from './../../assets/images/Travel/travel-header-img.jpg';
const entries = [
{
dateString: 'December 10-13',
placeName: 'Seven Swords Tattoo',
address: 'Philadelphia, PA',
},
{
dateString: 'December 21-24',
placeName: 'Coast To Coast Tattoo',
address: 'Charlotte, NC',
},
];
export class Travel extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Page>
<PageHeader
title="Travel"
mobileBackground={MobileBackground}
desktopBackground={DesktopBackground}
altText="Coming to a tattoo convention or shop near you soon"
/>
<Schedule entries={entries} />
</Page>
);
}
}
| {
"content_hash": "3361798628e234de59956108cb4b571c",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 104,
"avg_line_length": 24.186046511627907,
"alnum_prop": 0.6365384615384615,
"repo_name": "bzswords/blackstallion",
"id": "1d806cc5bf637d13c16ce035e1ce1ef6ea87fba0",
"size": "1040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/components/Travel/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2447"
},
{
"name": "JavaScript",
"bytes": "67123"
}
],
"symlink_target": ""
} |
""" Registro de las clases en el admin de django """
from django.contrib import admin
from .models import SliderImage, SliderAlbum
class SliderImageAdmin(admin.ModelAdmin):
list_display = ('thumb', 'name','description', 'order')
admin.site.register(SliderImage, SliderImageAdmin)
class SliderAlbumAdmin(admin.ModelAdmin):
filter_horizontal = 'images',
admin.site.register(SliderAlbum, SliderAlbumAdmin)
| {
"content_hash": "0e82bffcf7d9056598dda39e2a67ee17",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 60,
"avg_line_length": 32.38461538461539,
"alnum_prop": 0.7600950118764845,
"repo_name": "zakwilson/cmsplugin_jcarousellite",
"id": "4570b545c509b9db480bd463add2dee25fbec86e",
"size": "497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "admin.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "24939"
}
],
"symlink_target": ""
} |
You will need several things from your adminstrator to be able to make calls to the Catalina API
- license key (license key that was given to you by Catalina Technology)
- Site Key (also known as the encryption key)
- license expiration date (if there is one. leave blank if it is a non-expiring license)
- license name (this is the name of your company as it was encrypted against the license key)
- Site ID (this points to a site configuration)
- CpnyID (company ID in Dynamics SL)
## app.config or web.config
We often store settings like license information in the app.config or web.config. In all of these examples, you will see this in the app.config. This allows you to update the app.config in the example and replace that information with your own.
<add key="SITEID" value="Your SiteID"/>
<add key="CPNYID" value="Your Company ID"/>
<add key="LICENSEKEY" value="Your License Key"/>
<add key="LICENSENAME" value="Your License Name" />
<add key="LICENSEEXPIRATION" value="Your license expiration date -- leave blank if non-expiring" />
<add key="SITEKEY" value="Encryption site key"/>
| {
"content_hash": "02a4a42548241f6954612a6ebac94fcf",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 246,
"avg_line_length": 47.958333333333336,
"alnum_prop": 0.7211120764552563,
"repo_name": "CatalinaTechnology/ctAPIClientExamples",
"id": "b1a2448b359a7c2520b8b96a01fc17423c1eefb1",
"size": "1151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TestSLConsole/README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.colorTest');
goog.setTestOnly('goog.colorTest');
goog.require('goog.array');
goog.require('goog.color');
goog.require('goog.color.names');
goog.require('goog.testing.jsunit');
function testIsValidColor() {
var goodColors = ['#ffffff', '#ff7812', '#012345', '#Ff003D', '#3CA',
'(255, 26, 75)', 'RGB(2, 3, 4)', '(0,0,0)', 'white',
'blue'];
var badColors = ['#xxxxxx', '8899000', 'not_color', '#1234567', 'fffffg',
'(2555,0,0)', '(1,2,3,4)', 'rgb(1,20,)', 'RGB(20,20,20,)',
'omgwtfbbq'];
for (var i = 0; i < goodColors.length; i++) {
assertTrue(goodColors[i], goog.color.isValidColor(goodColors[i]));
}
for (var i = 0; i < badColors.length; i++) {
assertFalse(badColors[i], goog.color.isValidColor(badColors[i]));
}
}
function testIsValidHexColor() {
var goodHexColors = ['#ffffff', '#ff7812', '#012345', '#Ff003D', '#3CA'];
var badHexColors = ['#xxxxxx', '889900', 'not_color', '#1234567', 'fffffg'];
for (var i = 0; i < goodHexColors.length; i++) {
assertTrue(goodHexColors[i], goog.color.isValidHexColor_(goodHexColors[i]));
}
for (var i = 0; i < badHexColors.length; i++) {
assertFalse(badHexColors[i], goog.color.isValidHexColor_(badHexColors[i]));
}
}
function testIsValidRgbColor() {
var goodRgbColors = ['(255, 26, 75)', 'RGB(2, 3, 4)', '(0,0,0)',
'rgb(255,255,255)'];
var badRgbColors = ['(2555,0,0)', '(1,2,3,4)', 'rgb(1,20,)',
'RGB(20,20,20,)'];
for (var i = 0; i < goodRgbColors.length; i++) {
assertEquals(goodRgbColors[i],
goog.color.isValidRgbColor_(goodRgbColors[i]).length, 3);
}
for (var i = 0; i < badRgbColors.length; i++) {
assertEquals(badRgbColors[i],
goog.color.isValidRgbColor_(badRgbColors[i]).length, 0);
}
}
function testParse() {
var colors = ['rgb(15, 250, 77)', '(127, 127, 127)', '#ffeedd', '123456',
'magenta'];
var parsed = goog.array.map(colors, goog.color.parse);
assertEquals('rgb', parsed[0].type);
assertEquals(goog.color.rgbToHex(15, 250, 77), parsed[0].hex);
assertEquals('rgb', parsed[1].type);
assertEquals(goog.color.rgbToHex(127, 127, 127), parsed[1].hex);
assertEquals('hex', parsed[2].type);
assertEquals('#ffeedd', parsed[2].hex);
assertEquals('hex', parsed[3].type);
assertEquals('#123456', parsed[3].hex);
assertEquals('named', parsed[4].type);
assertEquals('#ff00ff', parsed[4].hex);
var badColors = ['rgb(01, 1, 23)', '(256, 256, 256)', '#ffeeddaa'];
for (var i = 0; i < badColors.length; i++) {
var e = assertThrows(goog.partial(goog.color.parse, badColors[i]));
assertContains('is not a valid color string', e.message);
}
}
function testHexToRgb() {
var testColors = [['#B0FF2D', [176, 255, 45]],
['#b26e5f', [178, 110, 95]],
['#66f', [102, 102, 255]]];
for (var i = 0; i < testColors.length; i++) {
var r = goog.color.hexToRgb(testColors[i][0]);
var t = testColors[i][1];
assertEquals('Red channel should match.', t[0], r[0]);
assertEquals('Green channel should match.', t[1], r[1]);
assertEquals('Blue channel should match.', t[2], r[2]);
}
var badColors = ['', '#g00', 'some words'];
for (var i = 0; i < badColors.length; i++) {
var e = assertThrows(goog.partial(goog.color.hexToRgb, badColors[i]));
assertEquals("'" + badColors[i] + "' is not a valid hex color", e.message);
}
}
function testHexToRgbStyle() {
assertEquals('rgb(255,0,0)', goog.color.hexToRgbStyle(goog.color.names.red));
assertEquals('rgb(206,206,206)', goog.color.hexToRgbStyle('#cecece'));
assertEquals('rgb(51,204,170)', goog.color.hexToRgbStyle('#3CA'));
var badHexColors = ['#1234', null, undefined, '#.1234567890'];
for (var i = 0; i < badHexColors.length; ++i) {
var badHexColor = badHexColors[i];
var e = assertThrows(goog.partial(goog.color.hexToRgbStyle, badHexColor));
assertEquals("'" + badHexColor + "' is not a valid hex color", e.message);
}
}
function testRgbToHex() {
assertEquals(goog.color.names.red, goog.color.rgbToHex(255, 0, 0));
assertEquals('#af13ff', goog.color.rgbToHex(175, 19, 255));
var badRgb = [[-1, -1, -1],
[256, 0, 0],
['a', 'b', 'c'],
[undefined, 5, 5],
[1.2, 3, 4]];
for (var i = 0; i < badRgb.length; ++i) {
var e = assertThrows(goog.partial(goog.color.rgbArrayToHex, badRgb[i]));
assertContains('is not a valid RGB color', e.message);
}
}
function testRgbToHsl() {
var rgb = [255, 171, 32];
var hsl = goog.color.rgbArrayToHsl(rgb);
assertEquals(37, hsl[0]);
assertTrue(1.0 - hsl[1] < 0.01);
assertTrue(hsl[2] - .5625 < 0.01);
}
function testHslToRgb() {
var hsl = [60, 0.5, 0.1];
var rgb = goog.color.hslArrayToRgb(hsl);
assertEquals(38, rgb[0]);
assertEquals(38, rgb[1]);
assertEquals(13, rgb[2]);
}
// Tests accuracy of HSL to RGB conversion
function testHSLBidiToRGB() {
var DELTA = 1;
var color = [[100, 56, 200],
[255, 0, 0],
[0, 0, 255],
[0, 255, 0],
[255, 255, 255],
[0, 0, 0]];
for (var i = 0; i < color.length; i++) {
colorConversionTestHelper(
function(color) {
return goog.color.rgbToHsl(color[0], color[1], color[2]);
},
function(color) {
return goog.color.hslToRgb(color[0], color[1], color[2]);
},
color[i], DELTA);
colorConversionTestHelper(
function(color) { return goog.color.rgbArrayToHsl(color); },
function(color) { return goog.color.hslArrayToRgb(color); },
color[i], DELTA);
}
}
// Tests HSV to RGB conversion
function testHSVToRGB() {
var DELTA = 1;
var color = [[100, 56, 200],
[255, 0, 0],
[0, 0, 255],
[0, 255, 0],
[255, 255, 255],
[0, 0, 0]];
for (var i = 0; i < color.length; i++) {
colorConversionTestHelper(
function(color) {
return goog.color.rgbToHsv(color[0], color[1], color[2]);
},
function(color) {
return goog.color.hsvToRgb(color[0], color[1], color[2]);
},
color[i], DELTA);
colorConversionTestHelper(
function(color) { return goog.color.rgbArrayToHsv(color); },
function(color) { return goog.color.hsvArrayToRgb(color); },
color[i], DELTA);
}
}
// Tests that HSV space is (0-360) for hue
function testHSVSpecRangeIsCorrect() {
var color = [0, 0, 255]; // Blue is in the middle of hue range
var hsv = goog.color.rgbToHsv(color[0], color[1], color[2]);
assertTrue("H in HSV space looks like it's not 0-360", hsv[0] > 1);
}
// Tests conversion between HSL and Hex
function testHslToHex() {
var DELTA = 1;
var color = [[0, 0, 0],
[20, 0.5, 0.5],
[0, 0, 1],
[255, .45, .76]];
for (var i = 0; i < color.length; i++) {
colorConversionTestHelper(
function(hsl) { return goog.color.hslToHex(hsl[0], hsl[1], hsl[2]); },
function(hex) { return goog.color.hexToHsl(hex); },
color[i], DELTA);
colorConversionTestHelper(
function(hsl) { return goog.color.hslArrayToHex(hsl); },
function(hex) { return goog.color.hexToHsl(hex); },
color[i], DELTA);
}
}
// Tests conversion between HSV and Hex
function testHsvToHex() {
var DELTA = 1;
var color = [[0, 0, 0],
[.5, 0.5, 155],
[0, 0, 255],
[.7, .45, 21]];
for (var i = 0; i < color.length; i++) {
colorConversionTestHelper(
function(hsl) { return goog.color.hsvToHex(hsl[0], hsl[1], hsl[2]); },
function(hex) { return goog.color.hexToHsv(hex); },
color[i], DELTA);
colorConversionTestHelper(
function(hsl) { return goog.color.hsvArrayToHex(hsl); },
function(hex) { return goog.color.hexToHsv(hex); },
color[i], DELTA);
}
}
/**
* This helper method compares two RGB colors, checking that each color
* component is the same.
* @param {Array<number>} rgb1 Color represented by a 3-element array with
* red, green, and blue values respectively, in the range [0, 255].
* @param {Array<number>} rgb2 Color represented by a 3-element array with
* red, green, and blue values respectively, in the range [0, 255].
* @return {boolean} True if the colors are the same, false otherwise.
*/
function rgbColorsAreEqual(rgb1, rgb2) {
return (rgb1[0] == rgb2[0] &&
rgb1[1] == rgb2[1] &&
rgb1[2] == rgb2[2]);
}
/**
* This method runs unit tests against goog.color.blend(). Test cases include:
* blending arbitrary colors with factors of 0 and 1, blending the same colors
* using arbitrary factors, blending different colors of varying factors,
* and blending colors using factors outside the expected range.
*/
function testColorBlend() {
// Define some RGB colors for our tests.
var black = [0, 0, 0];
var blue = [0, 0, 255];
var gray = [128, 128, 128];
var green = [0, 255, 0];
var purple = [128, 0, 128];
var red = [255, 0, 0];
var yellow = [255, 255, 0];
var white = [255, 255, 255];
// Blend arbitrary colors, using 0 and 1 for factors. Using 0 should return
// the first color, while using 1 should return the second color.
var redWithNoGreen = goog.color.blend(red, green, 1);
assertTrue('red + 0 * green = red',
rgbColorsAreEqual(red, redWithNoGreen));
var whiteWithAllBlue = goog.color.blend(white, blue, 0);
assertTrue('white + 1 * blue = blue',
rgbColorsAreEqual(blue, whiteWithAllBlue));
// Blend the same colors using arbitrary factors. This should return the
// same colors.
var greenWithGreen = goog.color.blend(green, green, .25);
assertTrue('green + .25 * green = green',
rgbColorsAreEqual(green, greenWithGreen));
// Blend different colors using varying factors.
var blackWithWhite = goog.color.blend(black, white, .5);
assertTrue('black + .5 * white = gray',
rgbColorsAreEqual(gray, blackWithWhite));
var redAndBlue = goog.color.blend(red, blue, .5);
assertTrue('red + .5 * blue = purple',
rgbColorsAreEqual(purple, redAndBlue));
var lightGreen = goog.color.blend(green, white, .75);
assertTrue('green + .25 * white = a lighter shade of white',
lightGreen[0] > 0 &&
lightGreen[1] == 255 &&
lightGreen[2] > 0);
// Blend arbitrary colors using factors outside the expected range.
var noGreenAllPurple = goog.color.blend(green, purple, -0.5);
assertTrue('green * -0.5 + purple = purple.',
rgbColorsAreEqual(purple, noGreenAllPurple));
var allBlueNoYellow = goog.color.blend(blue, yellow, 1.37);
assertTrue('blue * 1.37 + yellow = blue.',
rgbColorsAreEqual(blue, allBlueNoYellow));
}
/**
* This method runs unit tests against goog.color.darken(). Test cases
* include darkening black with arbitrary factors, edge cases (using 0 and 1),
* darkening colors using various factors, and darkening colors using factors
* outside the expected range.
*/
function testColorDarken() {
// Define some RGB colors
var black = [0, 0, 0];
var green = [0, 255, 0];
var darkGray = [68, 68, 68];
var olive = [128, 128, 0];
var purple = [128, 0, 128];
var white = [255, 255, 255];
// Darken black by an arbitrary factor, which should still return black.
var darkBlack = goog.color.darken(black, .63);
assertTrue('black darkened by .63 is still black.',
rgbColorsAreEqual(black, darkBlack));
// Call darken() with edge-case factors (0 and 1).
var greenNotDarkened = goog.color.darken(green, 0);
assertTrue('green darkened by 0 is still green.',
rgbColorsAreEqual(green, greenNotDarkened));
var whiteFullyDarkened = goog.color.darken(white, 1);
assertTrue('white darkened by 1 is black.',
rgbColorsAreEqual(black, whiteFullyDarkened));
// Call darken() with various colors and factors. The result should be
// a color with less luminance.
var whiteHsl = goog.color.rgbToHsl(white[0],
white[1],
white[2]);
var whiteDarkened = goog.color.darken(white, .43);
var whiteDarkenedHsl = goog.color.rgbToHsl(whiteDarkened[0],
whiteDarkened[1],
whiteDarkened[2]);
assertTrue('White that\'s darkened has less luminance than white.',
whiteDarkenedHsl[2] < whiteHsl[2]);
var purpleHsl = goog.color.rgbToHsl(purple[0],
purple[1],
purple[2]);
var purpleDarkened = goog.color.darken(purple, .1);
var purpleDarkenedHsl = goog.color.rgbToHsl(purpleDarkened[0],
purpleDarkened[1],
purpleDarkened[2]);
assertTrue('Purple that\'s darkened has less luminance than purple.',
purpleDarkenedHsl[2] < purpleHsl[2]);
// Call darken() with factors outside the expected range.
var darkGrayTurnedBlack = goog.color.darken(darkGray, 2.1);
assertTrue('Darkening dark gray by 2.1 returns black.',
rgbColorsAreEqual(black, darkGrayTurnedBlack));
var whiteNotDarkened = goog.color.darken(white, -0.62);
assertTrue('Darkening white by -0.62 returns white.',
rgbColorsAreEqual(white, whiteNotDarkened));
}
/**
* This method runs unit tests against goog.color.lighten(). Test cases
* include lightening white with arbitrary factors, edge cases (using 0 and 1),
* lightening colors using various factors, and lightening colors using factors
* outside the expected range.
*/
function testColorLighten() {
// Define some RGB colors
var black = [0, 0, 0];
var brown = [165, 42, 42];
var navy = [0, 0, 128];
var orange = [255, 165, 0];
var white = [255, 255, 255];
// Lighten white by an arbitrary factor, which should still return white.
var lightWhite = goog.color.lighten(white, .41);
assertTrue('white lightened by .41 is still white.',
rgbColorsAreEqual(white, lightWhite));
// Call lighten() with edge-case factors(0 and 1).
var navyNotLightened = goog.color.lighten(navy, 0);
assertTrue('navy lightened by 0 is still navy.',
rgbColorsAreEqual(navy, navyNotLightened));
var orangeFullyLightened = goog.color.lighten(orange, 1);
assertTrue('orange lightened by 1 is white.',
rgbColorsAreEqual(white, orangeFullyLightened));
// Call lighten() with various colors and factors. The result should be
// a color with greater luminance.
var blackHsl = goog.color.rgbToHsl(black[0],
black[1],
black[2]);
var blackLightened = goog.color.lighten(black, .33);
var blackLightenedHsl = goog.color.rgbToHsl(blackLightened[0],
blackLightened[1],
blackLightened[2]);
assertTrue('Black that\'s lightened has more luminance than black.',
blackLightenedHsl[2] >= blackHsl[2]);
var orangeHsl = goog.color.rgbToHsl(orange[0],
orange[1],
orange[2]);
var orangeLightened = goog.color.lighten(orange, .91);
var orangeLightenedHsl = goog.color.rgbToHsl(orangeLightened[0],
orangeLightened[1],
orangeLightened[2]);
assertTrue('Orange that\'s lightened has more luminance than orange.',
orangeLightenedHsl[2] >= orangeHsl[2]);
// Call lighten() with factors outside the expected range.
var navyTurnedWhite = goog.color.lighten(navy, 1.01);
assertTrue('Lightening navy by 1.01 returns white.',
rgbColorsAreEqual(white, navyTurnedWhite));
var brownNotLightened = goog.color.lighten(brown, -0.0000001);
assertTrue('Lightening brown by -0.0000001 returns brown.',
rgbColorsAreEqual(brown, brownNotLightened));
}
/**
* This method runs unit tests against goog.color.hslDistance().
*/
function testHslDistance() {
// Define some HSL colors
var aliceBlueHsl = goog.color.rgbToHsl(240, 248, 255);
var blackHsl = goog.color.rgbToHsl(0, 0, 0);
var ghostWhiteHsl = goog.color.rgbToHsl(248, 248, 255);
var navyHsl = goog.color.rgbToHsl(0, 0, 128);
var redHsl = goog.color.rgbToHsl(255, 0, 0);
var whiteHsl = goog.color.rgbToHsl(255, 255, 255);
// The distance between the same colors should be 0.
assertTrue('There is no HSL distance between white and white.',
goog.color.hslDistance(whiteHsl, whiteHsl) == 0);
assertTrue('There is no HSL distance between red and red.',
goog.color.hslDistance(redHsl, redHsl) == 0);
// The distance between various colors should be within certain thresholds.
var hslDistance = goog.color.hslDistance(whiteHsl, ghostWhiteHsl);
assertTrue('The HSL distance between white and ghost white is > 0.',
hslDistance > 0);
assertTrue('The HSL distance between white and ghost white is <= 0.02.',
hslDistance <= 0.02);
hslDistance = goog.color.hslDistance(whiteHsl, redHsl);
assertTrue('The HSL distance betwen white and red is > 0.02.',
hslDistance > 0.02);
hslDistance = goog.color.hslDistance(navyHsl, aliceBlueHsl);
assertTrue('The HSL distance between navy and alice blue is > 0.02.',
hslDistance > 0.02);
hslDistance = goog.color.hslDistance(blackHsl, whiteHsl);
assertTrue('The HSL distance between white and black is 1.',
hslDistance == 1);
}
/**
* This method runs unit tests against goog.color.yiqBrightness_().
*/
function testYiqBrightness() {
var white = [255, 255, 255];
var black = [0, 0, 0];
var coral = [255, 127, 80];
var lightgreen = [144, 238, 144];
var whiteBrightness = goog.color.yiqBrightness_(white);
var blackBrightness = goog.color.yiqBrightness_(black);
var coralBrightness = goog.color.yiqBrightness_(coral);
var lightgreenBrightness = goog.color.yiqBrightness_(lightgreen);
// brightness should be a number
assertTrue('White brightness is a number.',
typeof whiteBrightness == 'number');
assertTrue('Coral brightness is a number.',
typeof coralBrightness == 'number');
// brightness for known colors should match known values
assertEquals('White brightness is 255', whiteBrightness, 255);
assertEquals('Black brightness is 0', blackBrightness, 0);
assertEquals('Coral brightness is 160', coralBrightness, 160);
assertEquals('Lightgreen brightness is 199', lightgreenBrightness, 199);
}
/**
* This method runs unit tests against goog.color.yiqBrightnessDiff_().
*/
function testYiqBrightnessDiff() {
var colors = {
'deeppink': [255, 20, 147],
'indigo': [75, 0, 130],
'saddlebrown': [139, 69, 19]
};
var diffs = new Object();
for (name1 in colors) {
for (name2 in colors) {
diffs[name1 + '-' + name2] =
goog.color.yiqBrightnessDiff_(colors[name1], colors[name2]);
}
}
for (pair in diffs) {
// each brightness diff should be a number
assertTrue(pair + ' diff is a number.', typeof diffs[pair] == 'number');
// each brightness diff should be greater than or equal to 0
assertTrue(pair + ' diff is greater than or equal to 0.', diffs[pair] >= 0);
}
// brightness diff for same-color pairs should be 0
assertEquals('deeppink-deeppink is 0.', diffs['deeppink-deeppink'], 0);
assertEquals('indigo-indigo is 0.', diffs['indigo-indigo'], 0);
// brightness diff for known pairs should match known values
assertEquals('deeppink-indigo is 68.', diffs['deeppink-indigo'], 68);
assertEquals('saddlebrown-deeppink is 21.',
diffs['saddlebrown-deeppink'], 21);
// reversed pairs should have equal values
assertEquals('indigo-saddlebrown is 47.', diffs['indigo-saddlebrown'], 47);
assertEquals('saddlebrown-indigo is also 47.',
diffs['saddlebrown-indigo'], 47);
}
/**
* This method runs unit tests against goog.color.colorDiff_().
*/
function testColorDiff() {
var colors = {
'mediumblue': [0, 0, 205],
'oldlace': [253, 245, 230],
'orchid': [218, 112, 214]
};
var diffs = new Object();
for (name1 in colors) {
for (name2 in colors) {
diffs[name1 + '-' + name2] =
goog.color.colorDiff_(colors[name1], colors[name2]);
}
}
for (pair in diffs) {
// each color diff should be a number
assertTrue(pair + ' diff is a number.', typeof diffs[pair] == 'number');
// each color diff should be greater than or equal to 0
assertTrue(pair + ' diff is greater than or equal to 0.', diffs[pair] >= 0);
}
// color diff for same-color pairs should be 0
assertEquals('mediumblue-mediumblue is 0.',
diffs['mediumblue-mediumblue'], 0);
assertEquals('oldlace-oldlace is 0.', diffs['oldlace-oldlace'], 0);
// color diff for known pairs should match known values
assertEquals('mediumblue-oldlace is 523.', diffs['mediumblue-oldlace'], 523);
assertEquals('oldlace-orchid is 184.', diffs['oldlace-orchid'], 184);
// reversed pairs should have equal values
assertEquals('orchid-mediumblue is 339.', diffs['orchid-mediumblue'], 339);
assertEquals('mediumblue-orchid is also 339.',
diffs['mediumblue-orchid'], 339);
}
/**
* This method runs unit tests against goog.color.highContrast().
*/
function testHighContrast() {
white = [255, 255, 255];
black = [0, 0, 0];
lemonchiffron = [255, 250, 205];
sienna = [160, 82, 45];
var suggestion = goog.color.highContrast(
black, [white, black, sienna, lemonchiffron]);
// should return an array of three numbers
assertTrue('Return value is an array.', typeof suggestion == 'object');
assertTrue('Return value is 3 long.', suggestion.length == 3);
// known color combos should return a known (i.e. human-verified) suggestion
assertArrayEquals('White is best on sienna.',
goog.color.highContrast(
sienna, [white, black, sienna, lemonchiffron]), white);
assertArrayEquals('Black is best on lemonchiffron.',
goog.color.highContrast(
white, [white, black, sienna, lemonchiffron]), black);
}
/**
* Helper function for color conversion functions between two colorspaces.
* @param {Function} funcOne Function that converts from 1st colorspace to 2nd
* @param {Function} funcTwo Function that converts from 2nd colorspace to 2nd
* @param {Array<number>} color The color array passed to funcOne
* @param {number} DELTA Margin of error for each element in color
*/
function colorConversionTestHelper(funcOne, funcTwo, color, DELTA) {
var temp = funcOne(color);
if (!goog.color.isValidHexColor_(temp)) {
assertTrue('First conversion had a NaN: ' + temp, !isNaN(temp[0]));
assertTrue('First conversion had a NaN: ' + temp, !isNaN(temp[1]));
assertTrue('First conversion had a NaN: ' + temp, !isNaN(temp[2]));
}
var back = funcTwo(temp);
if (!goog.color.isValidHexColor_(temp)) {
assertTrue('Second conversion had a NaN: ' + back, !isNaN(back[0]));
assertTrue('Second conversion had a NaN: ' + back, !isNaN(back[1]));
assertTrue('Second conversion had a NaN: ' + back, !isNaN(back[2]));
}
assertColorFuzzyEquals('Color was off', color, back, DELTA);
}
/**
* Checks equivalence between two colors' respective values. Accepts +- delta
* for each pair of values
* @param {string} str
* @param {Array<number>} expected
* @param {Array<number>} actual
* @param {number} delta Margin of error for each element in color array
*/
function assertColorFuzzyEquals(str, expected, actual, delta) {
assertTrue(str + ' Expected: ' + expected + ' and got: ' + actual +
' w/ delta: ' + delta,
(Math.abs(expected[0] - actual[0]) <= delta) &&
(Math.abs(expected[1] - actual[1]) <= delta) &&
(Math.abs(expected[2] - actual[2]) <= delta));
}
| {
"content_hash": "2a03904e9a0e2234e80f4adf74812b22",
"timestamp": "",
"source": "github",
"line_count": 671,
"max_line_length": 80,
"avg_line_length": 37.10581222056632,
"alnum_prop": 0.6263153666961202,
"repo_name": "RealTimeWeb/Blockpy-Server",
"id": "fc529ad3fbb4556bec2a65a770acf131d0e24aff",
"size": "24898",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "static/blockly-games/js-read-only/goog/color/color_test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "130070"
},
{
"name": "HTML",
"bytes": "1863474"
},
{
"name": "JavaScript",
"bytes": "26121452"
},
{
"name": "Makefile",
"bytes": "353"
},
{
"name": "POV-Ray SDL",
"bytes": "4775"
},
{
"name": "Python",
"bytes": "307012"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>MutationWatcher tests</title>
<link href="../node_modules/mocha/mocha.css" media="screen" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js" type="text/javascript" charset="utf-8"></script>
<script src="../node_modules/chai/chai.js" type="text/javascript" charset="utf-8"></script>
<script src="../node_modules/mutationobserver-shim/dist/mutationobserver.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
mocha.ui('bdd');
expect = chai.expect;
root = this;
</script>
<script src="../dist/mutationwatcher.min.js"></script>
<script src="test.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
mocha.run();
</script>
</body>
</html> | {
"content_hash": "5ea418300d45f0ebe5e4edbd2eb9e990",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 137,
"avg_line_length": 44.75,
"alnum_prop": 0.595903165735568,
"repo_name": "virtyaluk/mutation-watcher",
"id": "dafebbeeade007fff79d2ccb8b1fd662e052ffb0",
"size": "1074",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1074"
},
{
"name": "JavaScript",
"bytes": "33402"
}
],
"symlink_target": ""
} |
.class Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;
.super Landroid/accounts/IAccountManagerResponse$Stub;
.source "AccountManager.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->run(Landroid/accounts/AccountManagerFuture;)V
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
# direct methods
.method constructor <init>(Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;)V
.locals 0
.param p1, "this$2" # Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
.prologue
.line 2229
iput-object p1, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
invoke-direct {p0}, Landroid/accounts/IAccountManagerResponse$Stub;-><init>()V
return-void
.end method
# virtual methods
.method public onError(ILjava/lang/String;)V
.locals 1
.param p1, "errorCode" # I
.param p2, "errorMessage" # Ljava/lang/String;
.annotation system Ldalvik/annotation/Throws;
value = {
Landroid/os/RemoteException;
}
.end annotation
.prologue
.line 2240
iget-object v0, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v0, v0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v0, v0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mResponse:Landroid/accounts/IAccountManagerResponse;
invoke-interface {v0, p1, p2}, Landroid/accounts/IAccountManagerResponse;->onError(ILjava/lang/String;)V
.line 2239
return-void
.end method
.method public onResult(Landroid/os/Bundle;)V
.locals 8
.param p1, "value" # Landroid/os/Bundle;
.annotation system Ldalvik/annotation/Throws;
value = {
Landroid/os/RemoteException;
}
.end annotation
.prologue
.line 2231
new-instance v1, Landroid/accounts/Account;
.line 2232
const-string/jumbo v0, "authAccount"
invoke-virtual {p1, v0}, Landroid/os/Bundle;->getString(Ljava/lang/String;)Ljava/lang/String;
move-result-object v0
.line 2233
const-string/jumbo v2, "accountType"
invoke-virtual {p1, v2}, Landroid/os/Bundle;->getString(Ljava/lang/String;)Ljava/lang/String;
move-result-object v2
.line 2231
invoke-direct {v1, v0, v2}, Landroid/accounts/Account;-><init>(Ljava/lang/String;Ljava/lang/String;)V
.line 2234
.local v1, "account":Landroid/accounts/Account;
iget-object v0, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v7, v0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v0, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v0, v0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v0, v0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->this$0:Landroid/accounts/AccountManager;
iget-object v2, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v2, v2, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v2, v2, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mAuthTokenType:Ljava/lang/String;
iget-object v3, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v3, v3, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v3, v3, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mLoginOptions:Landroid/os/Bundle;
.line 2235
iget-object v4, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v4, v4, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v4, v4, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mActivity:Landroid/app/Activity;
iget-object v5, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v5, v5, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v5, v5, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mMyCallback:Landroid/accounts/AccountManagerCallback;
iget-object v6, p0, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1;->this$2:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;
iget-object v6, v6, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1;->this$1:Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;
iget-object v6, v6, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mHandler:Landroid/os/Handler;
.line 2234
invoke-virtual/range {v0 .. v6}, Landroid/accounts/AccountManager;->getAuthToken(Landroid/accounts/Account;Ljava/lang/String;Landroid/os/Bundle;Landroid/app/Activity;Landroid/accounts/AccountManagerCallback;Landroid/os/Handler;)Landroid/accounts/AccountManagerFuture;
move-result-object v0
iput-object v0, v7, Landroid/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask;->mFuture:Landroid/accounts/AccountManagerFuture;
.line 2230
return-void
.end method
| {
"content_hash": "0b429535e3cac33ac5b963d471c981c1",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 271,
"avg_line_length": 47.16083916083916,
"alnum_prop": 0.7975978647686833,
"repo_name": "libnijunior/patchrom_angler",
"id": "0f52d015241d2bd2b68135655d94ef64e8078eca",
"size": "6744",
"binary": false,
"copies": "2",
"ref": "refs/heads/mtc20l",
"path": "framework.jar.out/smali/android/accounts/AccountManager$GetAuthTokenByTypeAndFeaturesTask$1$1.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3339"
},
{
"name": "Makefile",
"bytes": "937"
},
{
"name": "Roff",
"bytes": "8687"
},
{
"name": "Shell",
"bytes": "10110"
},
{
"name": "Smali",
"bytes": "172302074"
}
],
"symlink_target": ""
} |
// key: compiler.err.wrong.number.type.args
import java.util.*;
class T {
List<Integer,String> list;
}
| {
"content_hash": "394ca06144cef7d560fc8cb6095ec073",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 43,
"avg_line_length": 12.333333333333334,
"alnum_prop": 0.6666666666666666,
"repo_name": "ceylon/ceylon",
"id": "75819d51d09bb0a6f5b2f803196bc1fe8edfe037",
"size": "1161",
"binary": false,
"copies": "91",
"ref": "refs/heads/master",
"path": "compiler-java/langtools/test/tools/javac/diags/examples/WrongNumberTypeArgs.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3806"
},
{
"name": "CSS",
"bytes": "19001"
},
{
"name": "Ceylon",
"bytes": "6230332"
},
{
"name": "GAP",
"bytes": "178688"
},
{
"name": "Groovy",
"bytes": "28376"
},
{
"name": "HTML",
"bytes": "4562"
},
{
"name": "Java",
"bytes": "24954709"
},
{
"name": "JavaScript",
"bytes": "499145"
},
{
"name": "Makefile",
"bytes": "19934"
},
{
"name": "Perl",
"bytes": "2756"
},
{
"name": "Roff",
"bytes": "47559"
},
{
"name": "Shell",
"bytes": "212436"
},
{
"name": "XSLT",
"bytes": "1992114"
}
],
"symlink_target": ""
} |
package io;
public interface IO {
public String read(String input);
public void write(String output);
}
| {
"content_hash": "2f1297269396d58338d7af2a3736ace7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 37,
"avg_line_length": 12.88888888888889,
"alnum_prop": 0.6896551724137931,
"repo_name": "guardians-of-the-kappa/javacli",
"id": "be2c1f2c14df2df725ebe71f3bb1746c595860d6",
"size": "116",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/IO.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "3594"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2683dc6f3f36c78a0466fb3f25c78a2d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "43d475134f1907d55ef8eeb27ef5dc6862ec2fa9",
"size": "175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Tournefortia/Tournefortia lucida/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import * as React from 'react';
export const Nav = () =>
<nav ClassName='navbar navbar-expand-lg navbar-light bg-light'>
<a ClassName='navbar-brand' href='#'>Memes Inc.</a>
<button ClassName='navbar-toggler' type='button' data-toggle='collapse' data-target='#navbarNavAltMarkup' aria-controls='navbarNavAltMarkup' aria-expanded='false' aria-label='Toggle navigation'>
<span ClassName='navbar-toggler-icon'></span>
</button>
<div ClassName='collapse navbar-collapse' id='navbarNavAltMarkup'>
<div ClassName='navbar-nav'>
<a ClassName='nav-item nav-link active' id='home-link' href='./index.html'>Home <span ClassName='sr-only'>(current)</span></a>
<a ClassName='nav-item nav-link' id='signup-link' href='signup.html'>Signup</a>
<a ClassName='nav-item nav-link' href='rules.html'>Rules</a>
<a ClassName='nav-item nav-link disabled' href='#'>Cool Memes</a>
</div>
</div>
</nav> | {
"content_hash": "84e1dd52005790b94efc53e8b3d261c4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 198,
"avg_line_length": 56,
"alnum_prop": 0.6659663865546218,
"repo_name": "ndomenech/2017fall",
"id": "c233d61790a01bfd4f4dca788141d2d65a33fdb6",
"size": "952",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jquery-mockup/src/_nav.tsx",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "606"
},
{
"name": "HTML",
"bytes": "21614"
},
{
"name": "JavaScript",
"bytes": "10482"
},
{
"name": "TypeScript",
"bytes": "21824"
}
],
"symlink_target": ""
} |
/**
* @file drv_adc.h
*
* ADC driver interface.
*
*/
#pragma once
#include <stdint.h>
#include <sys/ioctl.h>
#include <systemlib/px4_macros.h>
#include <uORB/topics/adc_report.h>
/* Define the PX4 low level format ADC and the maximum
* number of channels that can be returned by a lowlevel
* ADC driver. Drivers may return less than PX4_MAX_ADC_CHANNELS
* but no more than PX4_MAX_ADC_CHANNELS.
*
*/
#define PX4_MAX_ADC_CHANNELS arraySize(adc_report_s::channel_id)
typedef struct __attribute__((packed)) px4_adc_msg_t {
uint8_t am_channel; /* The 8-bit ADC Channel */
int32_t am_data; /* ADC convert result (4 bytes) */
} px4_adc_msg_t;
#define BUILTIN_ADC_DEVID 0xffffffff // TODO: integrate into existing ID management
__BEGIN_DECLS
/**
* Initialize ADC hardware
* @param base_address architecture-specific address to specify the ADC
* @return 0 on success, <0 error otherwise
*/
int px4_arch_adc_init(uint32_t base_address);
/**
* Uninitialize ADC hardware
* @param base_address architecture-specific address to specify the ADC
*/
void px4_arch_adc_uninit(uint32_t base_address);
/**
* Read a sample from the ADC
* @param base_address architecture-specific address to specify the ADC
* @param channel specify the channel
* @return sample, 0xffffffff on error
*/
uint32_t px4_arch_adc_sample(uint32_t base_address, unsigned channel);
/**
* Get the ADC positive reference voltage
* N.B This assume that all ADC channels share the same vref.
* @return v_ref
*/
float px4_arch_adc_reference_v(void);
/**
* Get the temperature sensor channel bitmask
*/
uint32_t px4_arch_adc_temp_sensor_mask(void);
/**
* Get the adc digital number full count
*/
uint32_t px4_arch_adc_dn_fullcount(void);
__END_DECLS
| {
"content_hash": "e0a86ac18168f19e9e9bdf43072808e8",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 83,
"avg_line_length": 24.47945205479452,
"alnum_prop": 0.6989367655288192,
"repo_name": "acfloria/Firmware",
"id": "15d372621ab223639428749845c43981c97e2107",
"size": "3524",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/drivers/drv_adc.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "3738677"
},
{
"name": "C++",
"bytes": "9489997"
},
{
"name": "CMake",
"bytes": "1106585"
},
{
"name": "EmberScript",
"bytes": "93414"
},
{
"name": "GDB",
"bytes": "41"
},
{
"name": "Groovy",
"bytes": "66180"
},
{
"name": "HTML",
"bytes": "5343"
},
{
"name": "MATLAB",
"bytes": "9938"
},
{
"name": "Makefile",
"bytes": "20040"
},
{
"name": "Perl",
"bytes": "11401"
},
{
"name": "Python",
"bytes": "1300486"
},
{
"name": "Shell",
"bytes": "301338"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Species lupinorum 18:277. 1941
#### Original name
null
### Remarks
null | {
"content_hash": "9263ec0ada36673f30d59a9b6ff1a22e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 12.307692307692308,
"alnum_prop": 0.7125,
"repo_name": "mdoering/backbone",
"id": "76e024ad76c3a39fe77ec34596f0285d97fe4ba6",
"size": "211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lupinus/Lupinus chlorolepis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/**
Depth-of-Field post-process effect.
@author xeolabs / http://xeolabs.com
<p>Based on the article at Nutty Software: http://www.nutty.ca/?page_id=352&link=depth_of_field</p>
<p>Usage:</p>
<pre>
// Create depth-of-field effect around a procedurally-generated city
var dof = myScene.addNode({
type: "postprocess/dof",
texelSize: 0.00099, // Size of one texel (1 / width, 1 / height)
blurCoeff: 0.0011, // Calculated from the blur equation, b = ( f * ms / N )
focusDist: 500.0, // The distance to the subject in perfect focus (= Ds)
ppm: 10000, // Pixels per millimetre
nodes: [
// City, implemented by plugin at
// http://scenejs.org/api/latest/plugins/node/models/buildings/city.js
{
type: "models/buildings/city",
width: 600
}
]
});
// Adjust parameters:
dof.setTexelSize(.005);
dof.setBlurCoeff(0.065);
dof.setFocusDist(200.0);
dof.setPPM(5000);
</pre>
<p>Autofocus</p>
<pre>
// When the "postprocess/dof" is under a "lookAt" node, or any node that creates one of those, such as
// "cameras/orbit", then we can use the "autofocus" option to automatically synchronize its "focusDist"
// with the length of the "lookAt" node's eye->look vector.
myScene.addNode({
type: "lookAt",
eye: { x: 0, y: 0, z: -100 },
look: [ x; 0, y; 0, z: 0 },
nodes: [
{
type: "postprocess/dof",
texelSize: 0.00099,
blurCoeff: 0.0011,
focusDist: 500.0,
ppm: 10000,
autofocus: true, // Set true (default) to automatically manage focusDist
nodes: [
// City, implemented by plugin at
// http://scenejs.org/api/latest/plugins/node/models/buildings/city.js
{
type: "models/buildings/city",
width: 600
}
]
}
]
});
</pre>
*/
SceneJS.Types.addType("postprocess/dof", {
construct: function (params) {
// IDs for the render target nodes
var colorTarget = this.id + ".colorTarget";
var colorTarget2 = this.id + ".colorTarget2";
var depthTarget = this.id + ".depthTarget";
this._texelSize = params.texelSize != undefined ? params.texelSize : 0.00099; // Size of one texel (1 / width, 1 / height)
this._blurCoeff = params.blurCoeff != undefined ? params.blurCoeff : 0.0011; // Calculated from the blur equation, b = ( f * ms / N )
this._focusDist = params.focusDist != undefined ? params.focusDist : 500.0; // The distance to the subject in perfect focus (= Ds)
this._ppm = params.ppm || 10000; // Pixels per millimetre
this._near = params.near || 0.1;
this._far = params.far || 10000.0;
this._autofocus = (params.autofocus !== false);
this._autoclip = (params.autoclip !== false);
// Build a three-stage scene sub-graph:
// First stage renders the given child nodes to color and depth targets
// Second stage applies horizontal blur using the color and depth targets, renders to second color target
// Third stage applies vertical blur using the color and depth targets, renders to display
this.addNodes([
// Stage 1
// Render scene to color and depth targets
{
type: "stage",
priority: 1,
pickable: true,
nodes: [
// Output color target
{
type: "colorTarget",
id: colorTarget,
nodes: [
// Output depth target
{
type: "depthTarget",
id: depthTarget,
nodes: [
// Leaf node
{
id: this.id + ".leaf",
// The child nodes we want to render with DOF
nodes: params.nodes
}
]
}
]
}
]
}
// // Debug stage - uncomment this to render the depth buffer to the canvas
// ,
// {
// type: "stage",
// priority: 1.2,
//
// nodes: [
// {
// type: "depthTarget/render",
// target: depthTarget
// }
// ]
// }
]);
// Blur shader shared by stages 2 and 3
this._shader = this.addNode({
type: "shader",
shaders: [
// Vertex stage just passes through the positions and UVs
{
stage: "vertex",
code: [
"attribute vec3 SCENEJS_aVertex;",
"attribute vec2 SCENEJS_aUVCoord0;",
"varying vec2 vUv;",
"void main () {",
" gl_Position = vec4(SCENEJS_aVertex, 1.0);",
" vUv = SCENEJS_aUVCoord0;",
"}"
]
},
// Fragment stage blurs each pixel in color target by amount in proportion to
// corresponding depth in depth buffer
{
stage: "fragment",
code: [
"precision highp float;",
"uniform sampler2D SCENEJS_uSampler0;", // Colour target's texture
"uniform sampler2D SCENEJS_uSampler1;", // Depth target's texture
"uniform vec2 texelSize;", // Size of one texel (1 / width, 1 / height)
"uniform float orientation;", // 0 = horizontal, 1 = vertical
"uniform float blurCoeff;", // Calculated from the blur equation, b = ( f * ms / N )
"uniform float focusDist;", // The distance to the subject in perfect focus (= Ds)
"uniform float near;", // near clipping plane
"uniform float far;", // far clipping plane
"uniform float ppm;", // Pixels per millimetre
"varying vec2 vUv;",
/// Unpacks an RGBA pixel to floating point value.
"float unpack (vec4 colour) {",
" const vec4 bitShifts = vec4(1.0,",
" 1.0 / 255.0,",
" 1.0 / (255.0 * 255.0),",
" 1.0 / (255.0 * 255.0 * 255.0));",
" return dot(colour, bitShifts);",
"}",
// Calculates the blur diameter to apply on the image.
// b = (f * ms / N) * (xd / (Ds +- xd))
// Where:
// (Ds + xd) for background objects
// (Ds - xd) for foreground objects
"float getBlurDiameter (float d) {",
// Convert from linear depth to metres
" float Dd = d * (far - near);",
" float xd = abs(Dd - focusDist);",
" float xdd = (Dd < focusDist) ? (focusDist - xd) : (focusDist + xd);",
" float b = blurCoeff * (xd / xdd);",
" return b * ppm;",
"}",
"void main () {",
// Maximum blur radius to limit hardware requirements.
// Cannot #define this due to a driver issue with some setups
" const float MAX_BLUR_RADIUS = 60.0;",
// Pass the linear depth values recorded in the depth map to the blur
// equation to find out how much each pixel should be blurred with the
// given camera settings.
" float depth = unpack(texture2D(SCENEJS_uSampler1, vUv));",
" float blurAmount = getBlurDiameter(depth);",
" blurAmount = min(floor(blurAmount), MAX_BLUR_RADIUS);",
// Apply the blur
" float count = 0.0;",
" vec4 colour = vec4(0.0);",
" vec2 texelOffset;",
" if ( orientation == 0.0 )",
" texelOffset = vec2(texelSize.x, 0.0);",
" else",
" texelOffset = vec2(0.0, texelSize.y);",
" if ( blurAmount >= 1.0 ) {",
" float halfBlur = blurAmount * 0.5;",
" for (float i = 0.0; i < MAX_BLUR_RADIUS; ++i) {",
" if ( i >= blurAmount )",
" break;",
" float offset = i - halfBlur;",
" vec2 vOffset = vUv + (texelOffset * offset);",
" colour += texture2D(SCENEJS_uSampler0, vOffset);",
" ++count;",
" }",
" }",
// Apply colour
" if ( count > 0.0 )",
" gl_FragColor = colour / count;",
" else",
" gl_FragColor = texture2D(SCENEJS_uSampler0, vUv);",
"}"
]
}
],
// Shader params for both horizontal and vertical blur passes
params: {
"texelSize": [this._texelSize, this._texelSize], // Texel size
"blurCoeff": this._blurCoeff, // Calculated from the blur equation, b = ( f * ms / N )
"focusDist": this._focusDist, // The distance to the subject in perfect focus (= Ds)
"near:": this._near, // near clipping plane
"far": this._far, // far clipping plane
"ppm": this._ppm, // Pixels per millimetre
"orientation": 0.0 // 0 = horizontal, 1 = vertical
}
});
// Stages 2 and 3
this._shader.addNodes([
// Stage 2
// Horizontal blur using color and depth targets,
// rendering to a second color target
{
type: "stage",
priority: 2,
nodes: [
// Output color target
{
type: "colorTarget",
id: colorTarget2,
nodes: [
// Input color target
{
type: "texture",
target: colorTarget,
nodes: [
// Input depth target
{
type: "texture",
target: depthTarget,
nodes: [
// Shader parameters for this stage
{
type: "shaderParams",
params: {
"orientation": 0.0 // 0 = horizontal, 1 = vertical
},
nodes: [
{
type: "geometry/quad"
}
]
}
]
}
]
}
]
}
]
},
// Stage 3
// Vertical blur taking as inputs the depth target and the second color target,
// rendering to the canvas
{
type: "stage",
priority: 3,
nodes: [
// Input second color target
{
type: "texture",
target: colorTarget2,
nodes: [
// Input depth target
{
type: "texture",
target: depthTarget,
nodes: [
// Shader parameters for this stage
{
type: "shaderParams",
params: {
"orientation": 1.0 // 0 = horizontal, 1 = vertical
},
nodes: [
// Quad primitive, implemented by plugin at
// http://scenejs.org/api/latest/plugins/node/geometry/quad.js
{
type: "geometry/quad"
}
]
}
]
}
]
}
]
}
]);
},
/**
* Sets the texel size
* @param {Number} texelSize The texel size
*/
setTexelSize: function (texelSize) {
this._texelSize = texelSize;
this._shader.setParams({
texelSize: [texelSize, texelSize]
});
},
/**
* Gets the texel size
* @returns {Number}
*/
getTexelSize: function () {
return this._texelSize;
},
/**
* Sets the blur coefficient.
* This is calculated from the blur equation, b = ( f * ms / N ).
* @param {Number} blurCoeff The coefficient
*/
setBlurCoeff: function (blurCoeff) {
this._shader.setParams({
blurCoeff: this._blurCoeff = blurCoeff
});
},
/**
* Gets the blur coefficient
* @returns {Number}
*/
getBlurCoeff: function () {
return this._blurCoeff;
},
/**
* Sets the distance to the subject in perfect focus
* @param {Number} focusDist The focus distance
*/
setFocusDist: function (focusDist) {
this._shader.setParams({
focusDist: this._focusDist = focusDist
});
},
/** Gets the distance to the subject in perfect focus
* @returns {Number}
*/
getFocusDist: function () {
return this._focusDist;
},
/**
* Sets the distance to the near plane
* @param {Number} near The near plane distance
*/
setNear: function (near) {
this._shader.setParams({
near: this._near = near
});
},
/** Gets distance to near plane
* @returns {Number}
*/
getNear: function () {
return this._near;
},
/**
* Sets the distance to the far plane
* @param {Number} far The far plane distance
*/
setFar: function (far) {
this._shader.setParams({
far: far
});
},
/** Gets distance to far plane
* @returns {Number}
*/
getFar: function () {
return this._far;
},
/**
* Sets the number of pixels per millimetre
* @param {Number} ppm The pixels per millimetre
*/
setPPM: function (ppm) {
this._shader.setParams({
ppm: this._ppm = ppm
});
},
/**
* Gets the number of pixels per millimeter
* @returns {Number}
*/
getPPM: function () {
return this._ppm;
},
preCompile: function () {
if (this._autofocus) {
this._initLookat();
}
if (this._autoclip) {
this._initCamera();
}
},
// Synchronises near and far DOF planes with first
// camera node we find higher in the scene
_initCamera: function () {
var node = this.parent;
while (node && node.type != "camera") {
node = node.parent
}
if (node && (!this._camera || node.id != this._camera.id)) {
if (this._camera) {
this._camera.off(this._cameraSub);
}
this._camera = node;
var self = this;
function synchWithCamera() {
var optics = self._camera.getOptics();
self.setNear(optics.near);
self.setFar(optics.far);
}
this._cameraSub = (!node) ? null : node.on("matrix", synchWithCamera);
synchWithCamera(); // Immediately synch with camera
}
},
// Synchronises focus depth with length of (eye->look) on the
// first lookat node we find higher in the scene
_initLookat: function () {
var node = this.parent;
while (node && node.type != "lookAt") {
node = node.parent
}
if (node && (!this._lookat || node.id != this._lookat.id)) {
if (this._lookat) {
this._lookat.off(this._lookatSub);
}
this._lookat = node;
var self = this;
// Synchronise focus depth with length of eye->look vector
function synchWithLookat() {
var look = self._lookat.getLook();
var eye = self._lookat.getEye();
self.setFocusDist(SceneJS_math_lenVec3([ look.x - eye.x, look.y - eye.y, look.z - eye.z ]));
}
this._lookatSub = (!node) ? null : node.on("matrix", synchWithLookat);
synchWithLookat(); // Imediately sycnh with lookat
}
}
});
| {
"content_hash": "82e71e99aa4c8431e04140e2a888b417",
"timestamp": "",
"source": "github",
"line_count": 545,
"max_line_length": 142,
"avg_line_length": 34.82385321100917,
"alnum_prop": 0.40449971020601716,
"repo_name": "tsherif/scenejs",
"id": "e2a47bac7978fd85b0cc4018a5fed21b0d307ea8",
"size": "18979",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/plugins/node/postprocess/dof.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25220"
},
{
"name": "HTML",
"bytes": "24036"
},
{
"name": "JavaScript",
"bytes": "5182359"
}
],
"symlink_target": ""
} |
import { Injectable } from "@angular/core";
@Injectable()
export class BlockedUsers {
private blockedUsers: Array<string> = [];
constructor() {}
addUser(name) {
if(this.isBlocked(name))
return name;
else {
this.blockedUsers.push(name);
return name;
}
}
rmUser(name) {
let i = this.blockedUsers.indexOf(name);
if(i === -1) return null;
this.blockedUsers.splice(i, 1);
return name;
}
isBlocked(name) {
return this.blockedUsers.includes(name);
}
} | {
"content_hash": "05d1a7afadcdc1629747cdbc38a5181b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 44,
"avg_line_length": 16.21875,
"alnum_prop": 0.6146435452793835,
"repo_name": "fejs-levelup/js-course",
"id": "6d9935ed566132038b8c038662c2029ed393d6b1",
"size": "519",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/services/blocked-users.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "471"
},
{
"name": "HTML",
"bytes": "855"
},
{
"name": "JavaScript",
"bytes": "1791"
},
{
"name": "TypeScript",
"bytes": "10045"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
<report_format_detail>
<FileFormat>
<FormatID>1222</FormatID>
<FormatName>Drawing Interchange File Format (ASCII)</FormatName>
<FormatVersion>2010/2011/2012</FormatVersion>
<FormatAliases>
</FormatAliases>
<FormatFamilies>
</FormatFamilies>
<FormatTypes>Image (Vector)</FormatTypes>
<FormatDisclosure>
</FormatDisclosure>
<FormatDescription> ASCII DXF format is the ASCII encoded variant of the Drawing Interchange File Format, an exchange format for vector graphics developed by AutoDesk. They are probably the widely-used formats for exchanging vector data, and have become a de-facto industry standard. The format is owned by AutoDesk and typically changes with each release of their AutoCAD family of products. DXF files contain a tagged representation of the vector data. The structure comprises a Header section, followed by sections containing data on Classes, Tables, Blocks, Entities and, optionally, thumbnail images. Each section contains a series of data elements. each preceded by a group code tag, which indicates the type of data element. ASCII DXF version 2010-2012 is the version of the format associated with Releases 2010, 2011 and 2012 of the AutoCAD family of software products.</FormatDescription>
<BinaryFileFormat>
</BinaryFileFormat>
<ByteOrders>
</ByteOrders>
<ReleaseDate>
</ReleaseDate>
<WithdrawnDate>
</WithdrawnDate>
<ProvenanceSourceID>1</ProvenanceSourceID>
<ProvenanceName>Digital Preservation Department / The National Archives</ProvenanceName>
<ProvenanceSourceDate>11 Jun 2012</ProvenanceSourceDate>
<ProvenanceDescription>
</ProvenanceDescription>
<LastUpdatedDate>28 Sep 2020</LastUpdatedDate>
<FormatNote>
</FormatNote>
<FormatRisk>
</FormatRisk>
<TechnicalEnvironment>
</TechnicalEnvironment>
<FileFormatIdentifier>
<Identifier>fmt/435</Identifier>
<IdentifierType>PUID</IdentifierType>
</FileFormatIdentifier>
<FileFormatIdentifier>
<Identifier>image/vnd.dxf</Identifier>
<IdentifierType>MIME</IdentifierType>
</FileFormatIdentifier>
<Developers>
<DeveloperID>18</DeveloperID>
<DeveloperName>
</DeveloperName>
<OrganisationName>Autodesk Corporation</OrganisationName>
<DeveloperCompoundName>Autodesk Corporation</DeveloperCompoundName>
</Developers>
<Support>
<SupportID>18</SupportID>
<SupportName>
</SupportName>
<OrganisationName>Autodesk Corporation</OrganisationName>
<SupportCompoundName>Autodesk Corporation</SupportCompoundName>
</Support>
<ExternalSignature>
<ExternalSignatureID>1223</ExternalSignatureID>
<Signature>dxf</Signature>
<SignatureType>File extension</SignatureType>
</ExternalSignature>
<InternalSignature>
<SignatureID>652</SignatureID>
<SignatureName>Drawing Interchange File Format 2010/2011/2012</SignatureName>
<SignatureNote>Header section with $ACADVER group code (AC1024), EOF marker</SignatureNote>
<ByteSequence>
<ByteSequenceID>797</ByteSequenceID>
<PositionType>Variable</PositionType>
<Offset>
</Offset>
<MaxOffset>
</MaxOffset>
<IndirectOffsetLocation>
</IndirectOffsetLocation>
<IndirectOffsetLength>
</IndirectOffsetLength>
<Endianness>
</Endianness>
<ByteSequenceValue>30(0D0A|0A|0D)53454354494F4E(0D0A|0A|0D)202032(0D0A|0A|0D)484541444552(0D0A|0A|0D)*39(0D0A|0A|0D)2441434144564552(0D0A|0A|0D)202031(0D0A|0A|0D)414331303234(0D0A|0A|0D)*30(0D0A|0A|0D)454E44534543(0D0A|0A|0D)</ByteSequenceValue>
</ByteSequence>
<ByteSequence>
<ByteSequenceID>798</ByteSequenceID>
<PositionType>Absolute from EOF</PositionType>
<Offset>0</Offset>
<MaxOffset>5</MaxOffset>
<IndirectOffsetLocation>
</IndirectOffsetLocation>
<IndirectOffsetLength>
</IndirectOffsetLength>
<Endianness>
</Endianness>
<ByteSequenceValue>30(0D0A|0A|0D)454F46</ByteSequenceValue>
</ByteSequence>
</InternalSignature>
<RelatedFormat>
<RelationshipType>Has priority over</RelationshipType>
<RelatedFormatID>766</RelatedFormatID>
<RelatedFormatName>Drawing Interchange File Format (ASCII)</RelatedFormatName>
<RelatedFormatVersion>Generic</RelatedFormatVersion>
</RelatedFormat>
<RelatedFormat>
<RelationshipType>Is previous version of</RelationshipType>
<RelatedFormatID>1319</RelatedFormatID>
<RelatedFormatName>Drawing Interchange File Format (ASCII)</RelatedFormatName>
<RelatedFormatVersion>2013/2014/2015/2016/2017</RelatedFormatVersion>
</RelatedFormat>
</FileFormat>
<SearchCriteria>Criteria</SearchCriteria>
</report_format_detail>
</PRONOM-Report>
| {
"content_hash": "79c5ac733cc202854def79f969dc22e7",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 903,
"avg_line_length": 47.77477477477478,
"alnum_prop": 0.6798038845936263,
"repo_name": "richardlehane/siegfried",
"id": "2ad78f644e09ba3d5140a1a280a4632acebd8404",
"size": "5303",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "cmd/roy/data/pronom/fmt435.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "887382"
},
{
"name": "Shell",
"bytes": "710"
}
],
"symlink_target": ""
} |
<?php
/* @var $this yii\web\View */
use liuxy\admin\assets\plugins\jquery\JsTreeAsset;
use liuxy\admin\Module;
use liuxy\admin\widgets\ActiveForm;
use liuxy\admin\widgets\Modal;
use liuxy\admin\widgets\Tabs;
use liuxy\admin\widgets\Tools;
use liuxy\admin\widgets\Radio;
JsTreeAsset::register($this);
?>
<div class="row">
<div class="col-md-12">
<div class="portlet box">
<div class="portlet-body">
<div class="tabbable-custom">
<?=Tabs::widget([
'items'=>[
[
'label'=>Module::t('perm.list.title'),
'active' => true,
'content'=>'<div id="perm-tree" class="tree-demo"></div>'
],[
'label'=>Module::t('perm.seq.title'),
'headerOptions'=>[
'onclick'=>'perm.get(this,"node_1");'
],
'content'=>Tools::widget([
'id'=>'tools',
'items'=>[
[
'label'=>Module::t('goback'),
'title'=>Module::t('goback'),
'icon'=>'fa fa-backward',
'options'=>['href'=>'javascript:void(0)']
]
],
'content'=>'<div id="perm-table"></div>'
])
]
]
])?>
</div>
</div>
</div>
</div>
</div>
<?php Modal::begin([
'id'=>'perm-dialog'
]);?>
<div class="scroller" style="height:100%" data-always-visible="1" data-rail-visible1="1">
<div class="row">
<div class="col-md-12">
<div class="portlet-body form">
<?php $form = ActiveForm::begin(['id' => 'perm-form']); ?>
<?= $form->field('parent_id')->hiddenInput(['value'=>1]) ?>
<?= $form->field('name')->textInput(['placeholder'=>Module::t('name')]) ?>
<?= $form->field('link')->textInput(['placeholder'=>Module::t('link'),'value'=>'#']) ?>
<div class="form-group">
<label class="control-label control-label"><?=Module::t('navigation')?></label>
<?php echo Radio::widget([
'name'=>'is_nav',
'items'=>[
\liuxy\admin\models\Permission::NAV_YES=>Module::t('yes'),
\liuxy\admin\models\Permission::NAV_NO=>Module::t('no')
],
'values'=>[\liuxy\admin\models\Permission::NAV_NO]
])?>
</div>
<?= $form->field('description')->textInput(['placeholder'=>Module::t('description')]) ?>
<?= $form->field('icon')->textInput(['placeholder'=>Module::t('description'),
'value'=>'icon-list',
'icon'=>'ace-icon fa fa-external-link',
'icon-link'=>'http://fontawesome.io/icons/',
'typehead'=>true]) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
<?php Modal::end();?>
<script type="text/javascript">
_callbacks.push(function() {
perm.init();
});
</script>
| {
"content_hash": "1435629ffd939623b1bf5aa4f709b55a",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 104,
"avg_line_length": 39.82795698924731,
"alnum_prop": 0.3849892008639309,
"repo_name": "liupdhc/yii2-liuxy-admin",
"id": "7e4fa539e840cbff6dea00225d357fc970412147",
"size": "3704",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/permission/index.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "182769"
}
],
"symlink_target": ""
} |
from .geoid import tract_geoid, tract_census_geoid
__all__ = ["tract_geoid", "tract_census_geoid"] | {
"content_hash": "ac2d495cea50cd51071dc8a7b7dc801c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 50,
"avg_line_length": 33,
"alnum_prop": 0.7070707070707071,
"repo_name": "CivicKnowledge/metatab-packages",
"id": "d63f62f23145c67426f56d5138068344cd201c3d",
"size": "100",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "broken/sangis.org-census_regions/lib/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "163951"
},
{
"name": "Jupyter Notebook",
"bytes": "760451"
},
{
"name": "Makefile",
"bytes": "2603"
},
{
"name": "Python",
"bytes": "34795"
}
],
"symlink_target": ""
} |
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.syntax;
import com.google.devtools.build.lib.skylarkinterface.SkylarkValue;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
/**
* The StarlarkCallable interface is implemented by all Starlark values that may be called from
* Starlark like a function, including built-in functions and methods, Starlark functions, and
* application-defined objects (such as rules, aspects, and providers in Bazel).
*/
public interface StarlarkCallable extends SkylarkValue {
/**
* Call this function with the given arguments.
*
* <p>Neither the callee nor the caller may modify the args List or kwargs Map.
*
* @param args the list of positional arguments
* @param kwargs the mapping of named arguments
* @param call the syntax tree of the function call
* @param thread the StarlarkThread in which the function is called
* @return the result of the call
* @throws EvalException if there was an error invoking this function
*/
// TODO(adonovan):
// - rename StarlarkThread to StarlarkThread and make it the first parameter.
// - eliminate the FuncallExpression parameter (which can be accessed through thread).
public Object call(
List<Object> args,
@Nullable Map<String, Object> kwargs,
@Nullable FuncallExpression call,
StarlarkThread thread)
throws EvalException, InterruptedException;
// TODO(adonovan): add a getName method that defines how this callable appears in a stack trace.
}
| {
"content_hash": "9c88c2dab4158ee44d03e16d26b6cc7b",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 98,
"avg_line_length": 41.09615384615385,
"alnum_prop": 0.7477772578380908,
"repo_name": "aehlig/bazel",
"id": "d721f6d6479777498fce601f810b61d72c04546d",
"size": "2137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/google/devtools/build/lib/syntax/StarlarkCallable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1588"
},
{
"name": "C",
"bytes": "27067"
},
{
"name": "C++",
"bytes": "1513394"
},
{
"name": "Dockerfile",
"bytes": "839"
},
{
"name": "HTML",
"bytes": "21053"
},
{
"name": "Java",
"bytes": "35178923"
},
{
"name": "Makefile",
"bytes": "248"
},
{
"name": "Objective-C",
"bytes": "10369"
},
{
"name": "Objective-C++",
"bytes": "1043"
},
{
"name": "PowerShell",
"bytes": "15438"
},
{
"name": "Python",
"bytes": "2519187"
},
{
"name": "Ruby",
"bytes": "639"
},
{
"name": "Shell",
"bytes": "1916092"
},
{
"name": "Smarty",
"bytes": "18683"
}
],
"symlink_target": ""
} |
package Google::Ads::GoogleAds::V12::Services::ThirdPartyAppAnalyticsLinkService::RegenerateShareableLinkIdResponse;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| {
"content_hash": "318e3da7676a747149f26db0c04879c7",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 116,
"avg_line_length": 23.5,
"alnum_prop": 0.725531914893617,
"repo_name": "googleads/google-ads-perl",
"id": "c04b87573a77d43b7adb02983bc88fd6a835bb12",
"size": "1046",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/Google/Ads/GoogleAds/V12/Services/ThirdPartyAppAnalyticsLinkService/RegenerateShareableLinkIdResponse.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "73"
},
{
"name": "Perl",
"bytes": "5866064"
}
],
"symlink_target": ""
} |
package helpers;
import helpers.Config;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
public class BullshifierException extends Exception {
private static final ConcurrentMap<String, AtomicInteger> hitsCounterMap =
new ConcurrentHashMap<String, AtomicInteger>();
private final Context context;
private final int totalUniqueEvents;
public static BullshifierException build(Context context)
{
int hits = BullshifierException.getHitCount(context);
int invs = Context.getInvCount(context);
double failRate = (double) hits / (double) invs * 100;
int failRateInt = (int)failRate;
String message = String.format("(Event: %s) (Hits: %d) (Invs: %d) (Fail Rate: %d%%)",
context.getRequestId(), hits, invs, failRateInt);
return new BullshifierException(context, message);
}
public BullshifierException(Context context, String message) {
super(message);
this.context = context;
this.totalUniqueEvents = hitsCounterMap.size();
}
public Context getContext()
{
return context;
}
public static void incHitsCount(Context context)
{
String requestId = context.getRequestId();
if (!hitsCounterMap.containsKey(requestId)) {
hitsCounterMap.putIfAbsent(requestId, new AtomicInteger());
}
AtomicInteger hitsCounter = hitsCounterMap.get(requestId);
hitsCounter.addAndGet(1);
}
public static int getHitCount(Context context)
{
AtomicInteger hitsCounter = hitsCounterMap.get(context.getRequestId());
Integer hits = hitsCounter.get();
return hits == null ? -1 : hits;
}
@Override
public String toString() {
return getMessage();
}
}
| {
"content_hash": "50d2304d0c1fd3dc376afe95d442800b",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 87,
"avg_line_length": 26.952380952380953,
"alnum_prop": 0.7432273262661955,
"repo_name": "takipi/java-bullshifier",
"id": "4637fedc129d5d3bb379554cb5fe334cc4c63046",
"size": "1698",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/dist/template/project/src/main/java/helpers/BullshifierException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "52304"
},
{
"name": "Shell",
"bytes": "1156"
}
],
"symlink_target": ""
} |
layout: post
title: "Automating the Deployment and Upload of Snapshot Java Artifacts using Jenkins on Windows"
date: 2014-01-13 16:50
published: true
---
This post will show how to automate the deployment process of a Java Web Application (Student Enrollment Application developed using MYSQL DB with Hibernate ORM in a REST based Jersey2 Spring environment) using Jenkins Continuous Integration - to build the project, run the unit tests, upload the built artifacts to a Sonatype Snapshot repository, run the Cobertura Code Coverage reports and deploy the application to the Amazon EC2. The details of the actual application are explained in the earlier post given by the link [Building Java Web Application Using Jersey REST With Spring](http://meygam.github.io/blog/2013/12/13/student-enrollment-using-jersey-rest-with-spring/).
<!--more-->
1. Install Jenkins as a Windows Service
---------------------------------------
Navigate to jenkins-ci.org website using an Internet browser and download the Windows native package (the link is underlined for easy identification) as shown from the right side pane of the Download Jenkins tab.

Once the download is complete, uncompress the zip file and click on the jenkins-1.xxx.msi file. Proceed through the configuration steps to install the Jenkins as a Windows service.
2. Modify Default Jenkins Port
------------------------------
By default Jenkins runs on the port 8080. In order to avoid conflict with other applications, the default port can be modified by editing the jenkins.xml found under C:\Program Files (x86)\Jenkins location. As shown below, modify the httpPort to 8082.
```
<service>
<id>jenkins</id>
<name>Jenkins</name>
<description>This service runs Jenkins continuous integration system.</description>
<env name="JENKINS_HOME" value="%BASE%"/>
<!--
if you'd like to run Jenkins with a specific version of Java, specify a full path to java.exe.
The following value assumes that you have java in your PATH.
-->
<executable>%BASE%\jre\bin\java</executable>
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8082</arguments>
<!--
interactive flag causes the empty black Java window to be displayed.
I'm still debugging this.
<interactive />
-->
<logmode>rotate</logmode>
<onfailure action="restart" />
</service>
```
Once the modification is saved in jenkins.xml file, restart the Jenkins service from the Windows Task Manager->Services and right clicking on the Jenkins service and choose Stop Service to stop the service as shown below.

Once the status of the service changes to stopped, restart the service by right clicking on the Jenkins service and choose Start Service to start the service again.

Navigate to localhost:8082 to verify if the Jenkins restart was successful as shown below - Jenkins Dashboard will be displayed. Note that it takes a while before the Jenkins service becomes available.

3. Install Plugins
----------------------
On the Jenkins Dashboard, navigate to Manage Jenkins -> Manage Plugins as shown in the snapshot below.

Install the following plugins and restart Jenkins for the changes to take effect.
- GitHub Plugin (for integrating Github with Jenkins)
- Jenkins Cobertura Plugin (for Cobertura support)
- Deploy to Container Plugin (for deploying the WAR to the Tomcat Container on EC2 instance)
- Jenkins Artifactory Plugin (for deploying the built Maven artifacts to the Snapshot repository)
4. Configure System
-------------------
On the Jenkins Dashboard, navigate to Manage Jenkins -> Configure System as shown in the snapshot below.

Navigate to the JDK section and click on "Add JDK" to add the JDK installation as shown in the snapshot below. Specify a JDK Name, choose the JDK Version to install and follow the on-screen instructions to save the Oracle Login credentials. Save the changes.

Next, proceed to the Git section and click on "Add Git" to add the Git installation as shown in the snapshot below. Specify Git Name, specify the path to Git executable and Save the changes.

Next, proceed to the Maven section and click on "Add Maven" to add the Maven installation as shown in the snapshot below. Specify Maven Name, choose the Maven Version to install and Save the changes.

Proceed to the Git plugin section and enter the values for Github Username and Email Address as credentials as shown below. Save the changes.

Proceed to the Artifactory section and click on "Add" to add the information about the artifactory servers. Specify the URL for the snapshot repository and provide the deployer credentials created from the Artifactory server website as shown below. Click on "Test Connection" to test if the connection parameters are good to save and Save the changes.

Next, proceed to the Email Notification section and enter the SMTP Server details as shown below. Click on the Advanced button to add the further details required and Save the changes. Click on "Test configuration by sending test e-mail", enter the test e-mail recipient and click on "Test configuration" to see if the email is successfully sent.

5. Create a New Jenkins Job
---------------------------
From the Jenkins Dashboard, click on "New Job" to create a new job. Enter a name for the job and choose "Build a maven2/3 project" as option and click on OK as shown below.

From the New Job Configuration screen, proceed to the Source Code Management section and specify the Git Repository URL for the project as shown below. Save the changes.

Next, from the Build Triggers section, select the options desired as shown below and Save the changes.

Proceed to the Build section, enter the maven goals for building a snapshot as shown below and Save the changes.

Proceed to the Build Settings section. Select the option for Email Notification and enter the values for the email recipients as shown below. Save the changes.

Under the Post-build Actions, click on "Add post-build action" button and select "Deploy war/ear to a container". In the Amazon EC2, a Tomcat Manager (manager as username) instance has to be configured with roles manager-gui and manager-script to allow the remote deployment of the WAR/EAR to the Tomcat Container. The configuration steps can be found in the link [https://help.ubuntu.com/13.04/serverguide/tomcat.html](https://help.ubuntu.com/13.04/serverguide/tomcat.html) under the section of "Tomcat administration webapps"
Once the Tomcat Manager webapp configuration is complete in the Amazon EC2 instance, enter the details necessary for the deployment as shown below. Save the changes.

Similarly, from the Post-build Actions, click on "Add post-build action" button and select "Publish Cobertura Coverage Report". Enter the Cobertura XML Report Pattern as shown below and save the changes.

6. Configure settings.xml
-------------------------
In order to upload the built Maven artifacts to the artifactory server, configure the Jenkins settings.xml found in C:\Program Files (x86)\Jenkins\tools\hudson.tasks.Maven_MavenInstallation\Maven_3.1\conf folder with the same parameters as found in the default settings.xml (usually found under C:\Program Files\Apache Software Foundation\apache-maven-3.1.0\conf for a Windows machine) of the Maven installation on the system.
Typically, the server section needs to be configured in the settings.xml for Jenkins matching with the details of the Artifactory server.
```
<servers>
<server>
<id>sonatype-nexus-snapshots</id>
<username>username</username>
<password>password</password>
</server>
<server>
<id>sonatype-nexus-staging</id>
<username>username</username>
<password>password</password>
</server>
</servers>
```
7. Update pom.xml
-----------------
The pom.xml file for the project needs to be configured with the following plugins under the build section for the deployment to snapshot repository and for running the Cobertura Coverage report.
- maven-compiler-plugin
- maven-deploy-plugin
- cobertura-maven-plugin
Also add parent, scm and developer section to comply with the requirements put forth by the Artifactory server management as shown below.
```
<parent>
<groupId>org.sonatype.oss</groupId>
<artifactId>oss-parent</artifactId>
<version>7</version>
</parent>
<scm>
<connection>scm:git:git@github.com:elizabetht/StudentEnrollmentWithREST.git</connection>
<developerConnection>scm:git:git@github.com:elizabetht/StudentEnrollmentWithREST.git</developerConnection>
<url>git@github.com:elizabetht/StudentEnrollmentWithREST.git</url>
<tag>StudentEnrollmentWithREST-1.3</tag>
</scm>
<developers>
<developer>
<id>elizabetht</id>
<name>Elizabeth Thomas</name>
<email>email2eliza@gmail.com</email>
</developer>
</developers>
<build>
<finalName>StudentEnrollmentWithREST</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
<configuration>
<formats>
<format>html</format>
<format>xml</format>
</formats>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>cobertura</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
8. Build Now
-------------
Once the above configuration steps are complete, click on "Build Now" under the Jenkins -> Upload REST Snapshot Artifacts (or the respective Job name) to build the project based on the configuration.
The console output has the detailed logs of what steps were initiated by the configuration and the outcome of the entire build.
The timestamp of the WAR deployed to Amazon EC2 instance can be checked to see if the deployment is successful. In the same way, the snapshot repository can be checked to see if the upload of the artifacts is successful.
Thus the entire process of building the project along with unit tests whenever a SCM change is triggered or under another condition, running code coverage reports, uploading the artifacts built to the snapshot artifactory repository, deploying the WAR to the remote server container and triggering emails to the recipients can be automated with a click of a button through Jenkins.
| {
"content_hash": "afc525f607e644707db1b671e6431036",
"timestamp": "",
"source": "github",
"line_count": 248,
"max_line_length": 677,
"avg_line_length": 52.29838709677419,
"alnum_prop": 0.7597532767925983,
"repo_name": "meygam/meygam.io",
"id": "965742f445cfa40b53d6ecc0cee3430d88b04eb4",
"size": "12974",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/blog/posts/2014-01-13-jenkins-snapshot-upload.markdown",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2393"
},
{
"name": "CSS",
"bytes": "3297"
},
{
"name": "Groovy",
"bytes": "12688"
},
{
"name": "HTML",
"bytes": "16020"
},
{
"name": "Java",
"bytes": "299"
},
{
"name": "Shell",
"bytes": "2629"
}
],
"symlink_target": ""
} |
package org.apache.sis.internal.util;
import java.util.Map;
import java.util.Set;
import java.util.Objects;
import java.util.Iterator;
import java.util.Collection;
import java.util.Collections;
import java.util.NoSuchElementException;
import org.apache.sis.io.TableAppender;
import org.apache.sis.util.resources.Errors;
/**
* An alternative to {@link java.util.AbstractMap java.util.AbstractMap} using different implementation strategies.
* Instead of providing default method implementations on top of {@link #entrySet()}, this base class uses more
* often the {@link #get(Object)} method with the assumption that the map cannot contain null values, or use a
* special-purpose {@link #entryIterator()} which can reduce the amount of object creations.
*
* <p><strong>This base class is for Apache SIS internal purpose only. Do not use!</strong>
* This class is less robust than the JDK one (e.g. does not accept null values), forces subclasses to implement
* more methods, uses a non-standard {@link #entryIterator()}, and may change in any future SIS version.</p>
*
* <p>This {@code AbstractMap} implementation makes the following assumptions.
* <strong>Do not use this class if any of those assumptions do not hold!</strong></p>
* <ul>
* <li>The map cannot contain {@code null} value.</li>
* <li>The map cannot contain references to itself, directly or indirectly, in the keys or in the values.</li>
* </ul>
*
* <p>Read-only subclasses need to implement the following methods:</p>
* <ul>
* <li>{@link #size()} (not mandatory but recommended)</li>
* <li>{@link #get(Object)}</li>
* <li>{@link #entryIterator()} (non-standard method)</li>
* </ul>
*
* <p>Read/write subclasses can implement those additional methods:</p>
* <ul>
* <li>{@link #clear()}</li>
* <li>{@link #remove(Object)}</li>
* <li>{@link #put(Object,Object)}</li>
* <li>{@link #addKey(Object)} (non-standard, optional method)</li>
* <li>{@link #addValue(Object)} (non-standard, optional method)</li>
* </ul>
*
* @author Martin Desruisseaux (Geomatys)
* @version 0.8
*
* @param <K> the type of keys maintained by the map.
* @param <V> the type of mapped values.
*
* @since 0.5
* @module
*/
public abstract class AbstractMap<K,V> implements Map<K,V> {
/**
* An iterator over the entries in the enclosing map. This iterator has two main differences compared
* to the standard {@code Map.entrySet().iterator()}:
* <ul>
* <li>The {@link #next()} method checks if there is more element and moves to the next one in a single step.
* This is exactly the same approach than {@link java.sql.ResultSet#next()}.</li>
* <li>Entry elements are returned by the {@link #getKey()} and {@link #getValue()} methods
* instead of creating new {@code Map.Element} on each iterator.</li>
* </ul>
*
* @param <K> the type of keys maintained by the map.
* @param <V> the type of mapped values.
*
* @see AbstractMap#entryIterator()
*/
protected abstract static class EntryIterator<K,V> {
/**
* Moves the iterator to the next position, and returns {@code true} if there is at least one remaining element.
*
* @return {@code false} if this method reached iteration end.
*/
protected abstract boolean next();
/**
* Returns the key at the current iterator position.
* This method is invoked only after {@link #next()}.
*
* @return the key at the current iterator position.
*/
protected abstract K getKey();
/**
* Returns the value at the current iterator position.
* This method is invoked only after {@link #next()}.
*
* @return the value at the current iterator position.
*/
protected abstract V getValue();
/**
* Returns the entry at the current iterator position.
* This method is invoked only after {@link #next()}.
* The default implementation creates an immutable entry with {@link #getKey()} and {@link #getValue()}.
*
* @return the entry at the current iterator position.
*/
protected Entry<K,V> getEntry() {
return new java.util.AbstractMap.SimpleImmutableEntry<>(getKey(), getValue());
}
/**
* Removes the entry at the current iterator position (optional operation).
* The default implementation throws {@code UnsupportedOperationException}.
*/
protected void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException(message(false));
}
}
/**
* Convenience {@code EntryIterator} implementation which iterates over a list of key candidates.
* All keys associated to a null value will be skipped.
*
* @see AbstractMap#entryIterator()
*
* @since 0.8
*/
protected final class KeyIterator extends EntryIterator<K,V> {
/** The key candidates. */ private final K[] keys;
/** Index of current key. */ private int index = -1;
/** Value associated to current key. */ private V value;
/**
* Creates a new iterator over the given key candidates.
* The given array is not cloned; do not modify.
*
* @param keys all keys that the map may possibly contain.
*/
@SafeVarargs
public KeyIterator(final K... keys) {this.keys = keys;}
/**
* Moves to the next key associated to a non-null value.
*
* @return {@code false} if this method reached iteration end.
*/
@Override
protected boolean next() {
while (++index < keys.length) {
value = get(keys[index]);
if (value != null) {
return true;
}
}
return false;
}
@Override protected K getKey() {return keys[index];}
@Override protected V getValue() {return value;}
}
/**
* An implementation of {@link EntryIterator} which delegates its work to a standard iterator.
* Subclasses can modify the {@link #value} or other properties during iteration.
*
* <p>This method does not implement the {@link #remove()} method, thus assuming an unmodifiable map
* (which is consistent with the default implementation of {@link AbstractMap} methods).
* Modifiable maps should override {@code remove()} themselves.</p>
*
* @param <K> the type of keys maintained by the map.
* @param <V> the type of mapped values.
*
* @see AbstractMap#entryIterator()
*/
protected static class IteratorAdapter<K,V> extends EntryIterator<K,V> {
/**
* The standard iterator on which to delegate the work.
* It is safe to change this value before to invoke {@link #next()}.
*/
protected Iterator<Entry<K,V>> it;
/**
* The entry found by the last call to {@link #next()}.
*/
protected Entry<K,V> entry;
/**
* The value of <code>{@linkplain #entry}.getValue()}</code>.
* It is safe to change this value after {@link #next()} invocation.
*/
protected V value;
/**
* Creates a new adapter initialized to the entry iterator of the given map.
*
* @param map the map from which to return entries.
*/
public IteratorAdapter(final Map<K,V> map) {
it = map.entrySet().iterator();
}
/**
* Moves to the next entry having a non-null value. If this method returns {@code true}, then the
* {@link #entry} and {@link #value} fields are set to the properties of the new current entry.
* Otherwise (if this method returns {@code false}) the {@link #entry} and {@link #value} fields
* are undetermined.
*
* @return {@inheritDoc}
*/
@Override
protected boolean next() {
do {
if (!it.hasNext()) {
return false;
}
entry = it.next();
value = entry.getValue();
} while (value == null);
return true;
}
/**
* Returns <code>{@linkplain #entry}.getKey()}</code>.
*
* @return {@inheritDoc}
*/
@Override
protected K getKey() {
return entry.getKey();
}
/**
* Returns {@link #value}, which was itself initialized to <code>{@linkplain #entry}.getValue()}</code>.
*
* @return {@inheritDoc}
*/
@Override
protected V getValue() {
return value;
}
}
/**
* For subclass constructors.
*/
protected AbstractMap() {
}
/**
* Returns the number of key-value mappings in this map.
* The default implementation count the number of values returned by {@link #entryIterator()}.
* Subclasses should implement a more efficient method.
*/
@Override
public int size() {
int count = 0;
for (final EntryIterator<K,V> it = entryIterator(); it.next();) {
if (++count == Integer.MAX_VALUE) break;
}
return count;
}
/**
* Returns {@code true} if this map contains no element.
*
* @return {@code true} if this map contains no element.
*/
@Override
public boolean isEmpty() {
return !entryIterator().next();
}
/**
* Returns {@code true} if this map contains a value for the given name.
* The default implementation assumes that the map cannot contain {@code null} values.
*
* @param key the key for which to test the presence of a value.
* @return {@code true} if the map contains a non-null value for the given key.
*/
@Override
public boolean containsKey(final Object key) {
return get(key) != null;
}
/**
* Returns {@code true} if this map contains the given value.
* The default implementation iterates over all values using the {@link #entryIterator()}.
*
* @param value the value for which to test the presence.
* @return {@code true} if the map contains the given value.
*/
@Override
public boolean containsValue(final Object value) {
final EntryIterator<K,V> it = entryIterator();
if (it != null) while (it.next()) {
if (it.getValue().equals(value)) {
return true;
}
}
return false;
}
/**
* Returns the value for the given key, or {@code defaultValue} if none.
* The default implementation assumes that the map cannot contain {@code null} values.
*
* @param key the key for which to get the value.
* @param defaultValue the value to return if this map does not have an entry for the given key.
* @return the value for the given key, or {@code defaultValue} if none.
*/
@Override
public V getOrDefault(final Object key, final V defaultValue) {
final V value = get(key);
return (value != null) ? value : defaultValue;
}
/**
* The message to gives to the exception to be thrown in case of unsupported operation.
*
* @param add {@code true} if this method is invoked from {@link #addKey(Object)} or {@link #addValue(Object)}.
*/
static String message(final boolean add) {
return Errors.format(add ? Errors.Keys.UnsupportedOperation_1 : Errors.Keys.UnmodifiableObject_1,
add ? "add" : Map.class);
}
/**
* Removes all entries in this map.
* The default operation throws {@link UnsupportedOperationException}.
*/
@Override
public void clear() throws UnsupportedOperationException {
throw new UnsupportedOperationException(message(false));
}
/**
* Removes the entry for the given key in this map.
* The default operation throws {@link UnsupportedOperationException}.
*
* @param key the key of the entry to remove.
* @return the previous value, or {@code null} if none.
*/
@Override
public V remove(Object key) throws UnsupportedOperationException {
throw new UnsupportedOperationException(message(false));
}
/**
* Adds an entry for the given key in this map.
* The default operation throws {@link UnsupportedOperationException}.
*
* @param key the key of the entry to remove.
* @param value the value to associate to the given key.
* @return the previous value, or {@code null} if none.
*/
@Override
public V put(K key, V value) throws UnsupportedOperationException {
throw new UnsupportedOperationException(message(false));
}
/**
* Puts all entries of the given map in this map.
*
* @param map the other map from which to copy the entries.
*/
@Override
public void putAll(final Map<? extends K, ? extends V> map) throws UnsupportedOperationException {
for (final Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
/**
* Adds the given key in this map. Implementation of this method shall generate a corresponding value.
* The default operation throws {@link UnsupportedOperationException}.
*
* @param key the key to add.
* @return {@code true} if this map changed as a result of this operation.
*/
protected boolean addKey(final K key) throws UnsupportedOperationException {
throw new UnsupportedOperationException(message(true));
}
/**
* Adds the given value in this map. Implementation of this method shall generate a corresponding key.
* The default operation throws {@link UnsupportedOperationException}.
*
* @param value the value to add.
* @return {@code true} if this map changed as a result of this operation.
*/
protected boolean addValue(final V value) throws UnsupportedOperationException {
throw new UnsupportedOperationException(message(true));
}
/**
* Returns a view over the keys in this map. The returned set supports the {@link Set#add(Object)} operation
* if the enclosing map implements the {@link #addKey(Object)} method.
*
* <p>The default implementation does not cache the set on the assumption that it is very quick to create
* and usually not retained for a long time (we often want only its iterator). Caching the set would require
* a {@code volatile} field for thread safety, which also has cost.</p>
*
* @return a view of the keys in this map.
*/
@Override
public Set<K> keySet() {
return new SetOfUnknownSize<K>() {
@Override public void clear() { AbstractMap.this.clear();}
@Override public boolean isEmpty() {return AbstractMap.this.isEmpty();}
@Override public int size() {return AbstractMap.this.size();}
@Override public boolean contains(Object e) {return AbstractMap.this.containsKey(e);}
@Override public boolean remove(Object e) {return AbstractMap.this.remove(e) != null;}
@Override public boolean add(K e) {return AbstractMap.this.addKey(e);}
@Override public Iterator<K> iterator() {
final EntryIterator<K,V> it = entryIterator();
return (it != null) ? new Keys<>(it) : Collections.emptyIterator();
}
/** Overridden for the same reason than {@link AbstractMap#equals(Object). */
@Override public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Set<?>)) {
return false;
}
final Set<?> that = (Set<?>) object;
final EntryIterator<K,V> it = entryIterator();
if (it == null) {
return that.isEmpty();
}
int size = 0;
while (it.next()) {
if (!that.contains(it.getKey())) {
return false;
}
size++;
}
return size == that.size();
}
};
}
/**
* Returns a view over the values in this map. The returned collection supports the {@link Collection#add(Object)}
* operation if the enclosing map implements the {@link #addValue(Object)} method.
*
* <p>The default implementation does not cache the collection on the assumption that it is very quick to create
* and usually not retained for a long time.</p>
*
* @return a view of the values in this map.
*/
@Override
public Collection<V> values() {
return new Bag<V>() {
@Override public void clear() { AbstractMap.this.clear();}
@Override public boolean isEmpty() {return AbstractMap.this.isEmpty();}
@Override public int size() {return AbstractMap.this.size();}
@Override public boolean contains(Object e) {return AbstractMap.this.containsValue(e);}
@Override public boolean add(V e) {return AbstractMap.this.addValue(e);}
@Override public Iterator<V> iterator() {
final EntryIterator<K,V> it = entryIterator();
return (it != null) ? new Values<>(it) : Collections.emptyIterator();
}
};
}
/**
* Returns a view over the entries in this map.
*
* <p>The default implementation does not cache the set on the assumption that it is very quick to create
* and usually not retained for a long time.</p>
*
* @return a view of the entries in this map.
*/
@Override
public Set<Entry<K,V>> entrySet() {
return new SetOfUnknownSize<Entry<K,V>>() {
@Override public void clear() { AbstractMap.this.clear();}
@Override public boolean isEmpty() {return AbstractMap.this.isEmpty();}
@Override public int size() {return AbstractMap.this.size();}
/** Returns {@code true} if the map contains the given (key, value) pair. */
@Override public boolean contains(final Object e) {
if (e instanceof Entry<?,?>) {
final Entry<?,?> entry = (Entry<?,?>) e;
final Object value = get(entry.getKey());
if (value != null) {
return value.equals(entry.getValue());
}
}
return false;
}
/** Returns an iterator compliant to the Map contract. */
@Override public Iterator<Entry<K,V>> iterator() {
final EntryIterator<K,V> it = entryIterator();
return (it != null) ? new Entries<>(it) : Collections.emptyIterator();
}
/** Overridden for the same reason than {@link AbstractMap#equals(Object). */
@Override public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Set<?>)) {
return false;
}
final Set<?> that = (Set<?>) object;
final EntryIterator<K,V> it = entryIterator();
if (it == null) {
return that.isEmpty();
}
int size = 0;
while (it.next()) {
if (!that.contains(it.getEntry())) {
return false;
}
size++;
}
return size == that.size();
}
};
}
/**
* Returns an iterator over the entries in this map.
* It is okay (but not required) to return {@code null} if the map is empty.
*
* <div class="note"><b>Tip:</b>
* {@link KeyIterator} provides a convenient implementation for simple cases.</div>
*
* @return an iterator over the entries in this map, or {@code null}.
*/
protected abstract EntryIterator<K,V> entryIterator();
/**
* Base class of iterators overs keys, values or entries.
* Those iterators wrap an {@link EntryIterator} instance.
*/
private abstract static class Iter<K,V> {
/** The wrapped entry iterator. */
private final EntryIterator<K,V> iterator;
/** {@link #TRUE}, {@link #FALSE} or {@link #AFTER_NEXT}, or 0 if not yet determined. */
private byte hasNext;
/** Possible values for {@link #hasNext}. */
private static final byte TRUE=1, FALSE=2, AFTER_NEXT=3;
/**
* Creates a new standard iterator wrapping the given entry iterator.
*
* @param iterator {@link AbstractMap#entryIterator()}.
*/
Iter(final EntryIterator<K,V> iterator) {
this.iterator = iterator;
}
/**
* Returns {@code true} if there is at least one more element to return.
*/
public final boolean hasNext() {
switch (hasNext) {
case TRUE: return true;
case FALSE: return false;
default: {
final boolean c = iterator.next();
hasNext = c ? TRUE : FALSE;
return c;
}
}
}
/**
* Ensures that the entry iterator is positioned on a valid entry, and returns it.
* This method shall be invoked by implementations of {@link Iterator#next()}.
*/
final EntryIterator<K,V> entry() {
if (hasNext()) {
hasNext = AFTER_NEXT;
return iterator;
}
throw new NoSuchElementException();
}
/**
* Removes the current entry.
*/
public final void remove() {
if (hasNext == AFTER_NEXT) {
hasNext = 0;
iterator.remove();
} else {
throw new IllegalStateException();
}
}
}
/**
* Iterator over the keys.
*/
private static final class Keys<K,V> extends Iter<K,V> implements Iterator<K> {
Keys(final EntryIterator<K,V> it) {super(it);}
@Override public K next() {return entry().getKey();}
}
/**
* Iterator over the values.
*/
private static final class Values<K,V> extends Iter<K,V> implements Iterator<V> {
Values(EntryIterator<K,V> it) {super(it);}
@Override public V next() {return entry().getValue();}
}
/**
* Iterator over the entries, used only when {@link #entryIterator()} perform recycling.
* This iterator copies each entry in an {@code SimpleImmutableEntry} instance.
*/
private static final class Entries<K,V> extends Iter<K,V> implements Iterator<Entry<K,V>> {
Entries(EntryIterator<K,V> it) {super(it);}
@Override public Entry<K,V> next() {return entry().getEntry();}
}
/**
* Compares this map with the given object for equality.
*
* @param object the other object to compare with this map.
* @return {@code true} if both objects are equal.
*/
@Override
public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Map<?,?>)) {
return false;
}
final Map<?,?> that = (Map<?,?>) object;
final EntryIterator<K,V> it = entryIterator();
if (it == null) {
return that.isEmpty();
}
/*
* We do not check if map.size() == size() because in some Apache SIS implementations,
* the size() method have to scan through all map entries. We presume that if the maps
* are not equal, we will find a mismatched entry soon anyway.
*/
int size = 0;
while (it.next()) {
if (!it.getValue().equals(that.get(it.getKey()))) {
return false;
}
size++;
}
return size == that.size();
}
/**
* Computes a hash code value for this map.
*
* @return a hash code value.
*/
@Override
public int hashCode() {
int code = 0;
final EntryIterator<K,V> it = entryIterator();
if (it != null) while (it.next()) {
code += (Objects.hashCode(it.getKey()) ^ Objects.hashCode(it.getValue()));
}
return code;
}
/**
* Returns a string representation of this map. The default implementation is different than the
* {@code java.util.AbstractMap} one, as it uses a tabular format rather than formatting all entries
* on a single line.
*
* @return a string representation of this map.
*/
@Override
public String toString() {
final TableAppender buffer = new TableAppender(" = ");
buffer.setMultiLinesCells(true);
final EntryIterator<K,V> it = entryIterator();
if (it != null) while (it.next()) {
buffer.append(String.valueOf(it.getKey()));
buffer.nextColumn();
buffer.append(AbstractMapEntry.firstLine(it.getValue()));
buffer.nextLine();
}
return buffer.toString();
}
}
| {
"content_hash": "d5304ae380190fef2979371d2bcab729",
"timestamp": "",
"source": "github",
"line_count": 691,
"max_line_length": 120,
"avg_line_length": 37.43849493487699,
"alnum_prop": 0.5720139157325087,
"repo_name": "apache/sis",
"id": "949a245858f9a16cd78f19db70a3fcf36b77d6d4",
"size": "26671",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/sis-utility/src/main/java/org/apache/sis/internal/util/AbstractMap.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1667"
},
{
"name": "CSS",
"bytes": "152"
},
{
"name": "HTML",
"bytes": "76446"
},
{
"name": "Java",
"bytes": "32802649"
},
{
"name": "Shell",
"bytes": "3379"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Fungal Diversity 3: 148 (1999)
#### Original name
Hypoxylon fuhreri G.J.D. Sm., K.D. Hyde & Whalley, 1999
### Remarks
null | {
"content_hash": "5a194edf548f0a561dd431fc3a497a61",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 55,
"avg_line_length": 16.23076923076923,
"alnum_prop": 0.6919431279620853,
"repo_name": "mdoering/backbone",
"id": "7b9a4c6506b84c1f213b226911e73f4d83a2fdad",
"size": "290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Hypoxylon/Hypoxylon fuhreri/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Tournay-sur-Odon est
un village
géographiquement positionné dans le département des Calvados en Basse-Normandie. Elle totalisait 366 habitants en 2008.</p>
<p>Si vous pensez emmenager à Tournay-sur-Odon, vous pourrez facilement trouver une maison à acheter. </p>
<p>À proximité de Tournay-sur-Odon sont localisées les communes de
<a href="{{VLROOT}}/immobilier/parfouru-sur-odon_14491/">Parfouru-sur-Odon</a> localisée à 1 km, 152 habitants,
<a href="{{VLROOT}}/immobilier/monts-en-bessin_14449/">Monts-en-Bessin</a> à 1 km, 395 habitants,
<a href="{{VLROOT}}/immobilier/locheur_14373/">Le Locheur</a> localisée à 2 km, 277 habitants,
<a href="{{VLROOT}}/immobilier/banneville-sur-ajon_14037/">Banneville-sur-Ajon</a> située à 4 km, 393 habitants,
<a href="{{VLROOT}}/immobilier/missy_14432/">Missy</a> localisée à 3 km, 555 habitants,
<a href="{{VLROOT}}/immobilier/noyers-bocage_14475/">Noyers-Bocage</a> située à 2 km, 1 137 habitants,
entre autres. De plus, Tournay-sur-Odon est située à seulement 18 km de <a href="{{VLROOT}}/immobilier/caen_14118/">Caen</a>.</p>
<p>Le nombre de logements, à Tournay-sur-Odon, se décomposait en 2011 en un appartements et 145 maisons soit
un marché plutôt équilibré.</p>
</div>
| {
"content_hash": "6ee11548c22c53a7a24bde058e8db1c1",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 135,
"avg_line_length": 77.6470588235294,
"alnum_prop": 0.7371212121212121,
"repo_name": "donaldinou/frontend",
"id": "2ec569bee874a21e5143bbb944c43dcbcfddb400",
"size": "1347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/14702.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.