code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
class Commit < ApplicationRecord has_many :contributions, dependent: :destroy has_many :contributors, through: :contributions belongs_to :release, optional: true scope :with_no_contributors, -> { select('commits.*'). # otherwise we get read-only records left_joins(:contributions). where(contributions: { commit_id: nil }) } scope :in_time_window, ->(since, upto) { if upto where(committer_date: since..upto) else where('commits.committer_date >= ?', since) end } scope :release, ->(release) { where(release_id: release.id) } scope :edge, -> { where(release_id: nil) } scope :sorted, -> { order(committer_date: :desc) } validates :sha1, presence: true, uniqueness: true nfc :author_name, :committer_name, :message, :diff # Constructor that initializes the object from a Rugged commit. def self.import!(rugged_commit) commit = new_from_rugged_commit(rugged_commit) commit.save! commit end def self.new_from_rugged_commit(rugged_commit) new( sha1: rugged_commit.oid, author_name: rugged_commit.author[:name].force_encoding('UTF-8'), author_email: rugged_commit.author[:email].force_encoding('UTF-8'), author_date: rugged_commit.author[:time], committer_name: rugged_commit.committer[:name].force_encoding('UTF-8'), committer_email: rugged_commit.committer[:email].force_encoding('UTF-8'), committer_date: rugged_commit.committer[:time], message: rugged_commit.message.force_encoding('UTF-8'), merge: rugged_commit.parents.size > 1 ) end # Returns a shortened sha1 for this commit. Length is 7 by default. def short_sha1(length=7) sha1[0, length] end # Returns the URL of this commit in GitHub. def github_url "https://github.com/rails/rails/commit/#{sha1}" end def short_message @short_message ||= message ? message.split("\n").first : nil end # Returns the list of canonical contributor names of this commit. def extract_contributor_names(repo) names = extract_candidates(repo) names = canonicalize(names) names.uniq end protected def imported_from_svn? message.include?('git-svn-id: http://svn-commit.rubyonrails.org/rails') end # Both svn and git may have the name of the author in the message using the [...] # convention. If none is found we check the changelog entry for svn commits. # If that fails as well the contributor is the git author by definition. def extract_candidates(repo) names = hard_coded_authors if names.nil? names = extract_contributor_names_from_message if names.empty? names = extract_svn_contributor_names_diffing(repo) if imported_from_svn? if names.empty? sanitized = sanitize([author_name]) names = handle_false_positives(sanitized) if names.empty? # This is an edge case, some rare commits have an empty author name. names = sanitized end end end end # In modern times we are counting merge commits, because behind a merge # commit there is work by the core team member in the pull request. To # be fair, we are going to do what would be analogous for commits in # Subversion, where each commit has to be considered a merge commit. # # Note we do a uniq later in case normalization yields a clash. if imported_from_svn? && !names.include?(author_name) names << author_name end names.map(&:nfc) end def hard_coded_authors NamesManager.hard_coded_authors(self) end def sanitize(names) names.map {|name| NamesManager.sanitize(name)} end def handle_false_positives(names) names.map {|name| NamesManager.handle_false_positives(name)}.flatten.compact end def canonicalize(names) names.map {|name| NamesManager.canonical_name_for(name, author_email)}.flatten end def extract_contributor_names_from_message subject, body = message.split("\n\n", 2) # Check the end of subject first. contributor_names = extract_contributor_names_from_text(subject) return contributor_names if contributor_names.any? return [] if body.nil? # Some modern commits have an isolated body line with the credit. body.scan(/^\[[^\]]+\]$/) do |match| contributor_names = extract_contributor_names_from_text(match) return contributor_names if contributor_names.any? end # See https://help.github.com/en/articles/creating-a-commit-with-multiple-authors. co_authors = body.scan(/^Co-authored-by:(.*)$/i) return sanitize([author_name] + co_authors.flatten) if co_authors.any? # Check the end of the body as last option. if imported_from_svn? return extract_contributor_names_from_text(body.sub(/git-svn-id:.*/m, '')) end [] end # When Rails had a svn repo there was a convention for authors: the committer # put their name between brackets at the end of the commit or changelog message. # For example: # # Fix case-sensitive validates_uniqueness_of. Closes #11366 [miloops] # # Sometimes there's a "Closes #tiquet" after it, as in: # # Correct documentation for dom_id [jbarnette] Closes #10775 # Models with no attributes should just have empty hash fixtures [Sam] (Closes #3563) # # Of course this is not robust, but it is the best we can get. def extract_contributor_names_from_text(text) names = text =~ /\[([^\]]+)\](?:\s+\(?Closes\s+#\d+\)?)?\s*\z/ ? [$1] : [] names = sanitize(names) handle_false_positives(names) end # Looks for contributor names in changelogs. There are +1600 commits with credit here. def extract_svn_contributor_names_diffing(repo) cache_diff(repo) unless diff return [] if only_modifies_changelogs? extract_changelog.split("\n").map do |line| extract_contributor_names_from_text(line) end.flatten rescue # There are 10 diffs that have invalid UTF-8 and we get an exception, just # ignore them. See f0753992ab8cc9bbbf9b047fdc56f8899df5635e for example. update_column(:diff, $!.message) [] end def cache_diff(repo) update(diff: repo.diff(sha1).force_encoding('UTF-8')) end # Extracts any changelog entry for this commit. This is done by diffing with # git show, and is an expensive operation. So, we do this only for those # commits where this is needed, and cache the result in the database. def extract_changelog changelog = '' in_changelog = false diff.each_line do |line| if line =~ /^diff --git/ in_changelog = false elsif line =~ /^\+\+\+.*changelog$/i in_changelog = true elsif in_changelog && line =~ /^\+\s*\*/ changelog << line end end changelog end # Some commits only touch CHANGELOGs, for example # # https://github.com/rails/rails/commit/f18356edb728522fcd3b6a00f11b29fd3bff0577 # # Note we need this only for commits coming from Subversion, where # CHANGELOGs had no extension. def only_modifies_changelogs? diff.scan(/^diff --git(.*)$/) do |fname| return false unless fname.first.strip.ends_with?('CHANGELOG') end true end end
fxn/rails-contributors
app/models/commit.rb
Ruby
mit
7,250
<div class="footer"> <img src="{{asset('images/pay.png')}}" class="img-responsive" alt=""/> <ul class="footer_nav"> <li><a href="#">Inicio</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Tienda</a></li> <li><a href="#">Acerca de nosotros</a></li> <li><a href="contact.html">Contactanos</a></li> <li><a href="{{url('/panel/login')}}">Panel Administrativo</a></li> </ul> <p class="copy">Copyright&copy; 2017 Chocoburbujas </p> <p class="copy"> <small>Template by <a href="http://w3layouts.com" target="_blank"> w3layouts</a></small> </p> </div>
SoftTecnologias/chocoburbujas
resources/views/partials/footer.blade.php
PHP
mit
630
'use strict'; require('mocha'); const assert = require('assert'); const Generator = require('..'); let base; describe('.task', () => { beforeEach(() => { base = new Generator(); }); it('should register a task', () => { const fn = cb => cb(); base.task('default', fn); assert.equal(typeof base.tasks.get('default'), 'object'); assert.equal(base.tasks.get('default').callback, fn); }); it('should register a task with an array of dependencies', cb => { let count = 0; base.task('foo', next => { count++; next(); }); base.task('bar', next => { count++; next(); }); base.task('default', ['foo', 'bar'], next => { count++; next(); }); assert.equal(typeof base.tasks.get('default'), 'object'); assert.deepEqual(base.tasks.get('default').deps, ['foo', 'bar']); base.build('default', err => { if (err) return cb(err); assert.equal(count, 3); cb(); }); }); it('should run a glob of tasks', cb => { let count = 0; base.task('foo', next => { count++; next(); }); base.task('bar', next => { count++; next(); }); base.task('baz', next => { count++; next(); }); base.task('qux', next => { count++; next(); }); base.task('default', ['b*']); assert.equal(typeof base.tasks.get('default'), 'object'); base.build('default', err => { if (err) return cb(err); assert.equal(count, 2); cb(); }); }); it('should register a task with a list of strings as dependencies', () => { base.task('default', 'foo', 'bar', cb => { cb(); }); assert.equal(typeof base.tasks.get('default'), 'object'); assert.deepEqual(base.tasks.get('default').deps, ['foo', 'bar']); }); it('should run a task', cb => { let count = 0; base.task('default', cb => { count++; cb(); }); base.build('default', err => { if (err) return cb(err); assert.equal(count, 1); cb(); }); }); it('should throw an error when a task with unregistered dependencies is run', cb => { base.task('default', ['foo', 'bar']); base.build('default', err => { assert(err); cb(); }); }); it('should throw an error when a task does not exist', () => { return base.build('default') .then(() => { throw new Error('expected an error'); }) .catch(err => { assert(/registered/.test(err.message)); }); }); it('should emit task events', () => { const expected = []; base.on('task-registered', function(task) { expected.push(task.status + '.' + task.name); }); base.on('task-preparing', function(task) { expected.push(task.status + '.' + task.name); }); base.on('task', function(task) { expected.push(task.status + '.' + task.name); }); base.task('foo', cb => cb()); base.task('bar', ['foo'], cb => cb()); base.task('default', ['bar']); return base.build('default') .then(() => { assert.deepEqual(expected, [ 'registered.foo', 'registered.bar', 'registered.default', 'preparing.default', 'starting.default', 'preparing.bar', 'starting.bar', 'preparing.foo', 'starting.foo', 'finished.foo', 'finished.bar', 'finished.default' ]); }); }); it('should emit an error event when an error is returned in a task callback', cb => { base.on('error', err => { assert(err); assert.equal(err.message, 'This is an error'); }); base.task('default', cb => { return cb(new Error('This is an error')); }); base.build('default', err => { if (err) return cb(); cb(new Error('Expected an error')); }); }); it('should emit an error event when an error is thrown in a task', cb => { base.on('error', err => { assert(err); assert.equal(err.message, 'This is an error'); }); base.task('default', cb => { cb(new Error('This is an error')); }); base.build('default', err => { assert(err); cb(); }); }); it('should run dependencies before running the dependent task', cb => { const expected = []; base.task('foo', cb => { expected.push('foo'); cb(); }); base.task('bar', cb => { expected.push('bar'); cb(); }); base.task('default', ['foo', 'bar'], cb => { expected.push('default'); cb(); }); base.build('default', err => { if (err) return cb(err); assert.deepEqual(expected, ['foo', 'bar', 'default']); cb(); }); }); });
doowb/composer
test/app.task.js
JavaScript
mit
4,755
package creationalPattern.builder; public abstract class ColdDrink implements Item { public Packing packing() { return new Bottle(); } public abstract float price(); }
ajil/Java-Patterns
src/main/java/creationalPattern/builder/ColdDrink.java
Java
mit
192
using System; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; namespace SMH { public sealed class VAO : IDisposable { private const int InvalidHandle = -1; public int Handle { get; private set; } public int VertexCount { get; private set; } // Число вершин для отрисовки public VAO(int vertexCount) { VertexCount = vertexCount; AcquireHandle(); } private void AcquireHandle() { Handle = GL.GenVertexArray(); } public void Use() { GL.BindVertexArray(Handle); } public void AttachVBO(int index, VBO vbo, int elementsPerVertex, VertexAttribPointerType pointerType, int stride, int offset) { Use(); vbo.Use(); GL.EnableVertexAttribArray(index); GL.VertexAttribPointer(index, elementsPerVertex, pointerType, false, stride, offset); } public void Draw() { Use(); GL.DrawArrays(PrimitiveType.Triangles, 0, VertexCount); } private void ReleaseHandle() { if (Handle == InvalidHandle) return; GL.DeleteVertexArray(Handle); Handle = InvalidHandle; } public void Dispose() { ReleaseHandle(); GC.SuppressFinalize(this); } ~VAO() { if (GraphicsContext.CurrentContext != null && !GraphicsContext.CurrentContext.IsDisposed) ReleaseHandle(); } } }
Yeyti/Stellaris-Moding-Helper
SMH/GL/VAO.cs
C#
mit
1,627
require 'unicode_japanese' class Text class TextDecodeError < StandardError ; end class TextEncodeError < StandardError ; end NDS_SPECIAL_CHARACTERS = "・¡¢£¨©®°±´¸¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýŒœˆ˜‐‗‘’‚“”„•…′″›※€™«»⁰" AOS_SPECIAL_CHARACTERS = { 0x90 => "Œ", 0x91 => "œ", 0xA7 => "§", 0xAA => "ᵃ", 0xAB => "«", 0xBA => "°", 0xBB => "»", 0xC0 => "À", 0xC1 => "Á", 0xC2 => "Â", 0xC4 => "Ä", 0xC7 => "Ç", 0xC8 => "È", 0xC9 => "É", 0xCA => "Ê", 0xCB => "Ë", 0xD6 => "Ö", 0xD8 => "Œ", 0xDB => "Û", 0xDC => "Ü", 0xDF => "ß", 0xE0 => "à", 0xE2 => "â", 0xE4 => "ä", 0xE7 => "ç", 0xE8 => "è", 0xE9 => "é", 0xEA => "ê", 0xEB => "ë", 0xEE => "î", 0xEF => "ï", 0xF4 => "ô", 0xF6 => "ö", 0xF9 => "ù", 0xFB => "û", 0xFC => "ü", } attr_reader :text_id, :text_ram_pointer, :fs, :original_encoded_string_length attr_accessor :string_ram_pointer, :decoded_string, :encoded_string def initialize(text_id, fs) @text_id = text_id @fs = fs read_from_rom() end def read_from_rom if overlay_id fs.load_overlay(overlay_id) end @text_ram_pointer = TEXT_LIST_START_OFFSET + 4*text_id @string_ram_pointer = fs.read(@text_ram_pointer, 4).unpack("V").first if GAME == "hod" @encoded_string = fs.read_until_end_marker(string_ram_pointer+2, [0x0A, 0xF0]) # Skip the first 2 bytes which are always 00 00. elsif SYSTEM == :gba @encoded_string = fs.read_until_end_marker(string_ram_pointer+2, [0x0A]) # Skip the first 2 bytes which are always 01 00. elsif REGION == :jp @encoded_string = fs.read_until_end_marker(string_ram_pointer+2, [0x0A, 0xF0]) # Skip the first 2 bytes which are always 00 00. else @encoded_string = fs.read_until_end_marker(string_ram_pointer+2, [0xEA]) # Skip the first 2 bytes which are always 01 00. end @original_encoded_string_length = @encoded_string.length @decoded_string = decode_string(@encoded_string) end def write_to_rom fs.write(text_ram_pointer, [string_ram_pointer].pack("V")) if GAME == "hod" data = [0].pack("v") + encoded_string + [0x0A, 0xF0].pack("CC") elsif SYSTEM == :gba data = [1].pack("v") + encoded_string + [0x0A].pack("C") elsif REGION == :jp data = [0].pack("v") + encoded_string + [0x0A, 0xF0].pack("CC") else data = [1].pack("v") + encoded_string + [0xEA].pack("C") end fs.write(string_ram_pointer, data) @original_encoded_string_length = @encoded_string.length end def overlay_id if SYSTEM == :nds region_name = TEXT_REGIONS.find{|name, range| range.include?(text_id)}[0] TEXT_REGIONS_OVERLAYS[region_name] else nil end end def decoded_string=(new_str) @decoded_string = new_str @encoded_string = encode_string(new_str) end def encoded_string=(new_str) @encoded_string = new_str @decoded_string = decode_string(new_str) end def font_character_mapping_jp(index) offset = (((index & 0xFF00) >> 8) - 0x81) * 0xBC * 0xA index = index & 0x00FF if index > 0x7E index -= 1 end offset += (index - 0x40) * 0xA file_path = "/font/LD937728.DAT" char_number = fs.read_by_file(file_path, offset, 2).unpack("n").first # big endian return char_number end def reverse_font_character_mapping_jp(shift_jis) offset = 0 file_path = "/font/LD937728.DAT" file_size = fs.files_by_path[file_path][:size] found_offset = nil while offset < file_size char_number = fs.read_by_file(file_path, offset, 2).unpack("n").first # big endian if char_number == shift_jis found_offset = offset break end offset += 0xA end if found_offset.nil? raise TextEncodeError.new("Invalid shift jis character: %04X" % shift_jis) end index = offset / 0xA high_byte = ((index / 0xBC) + 0x81) << 8 low_byte = (index % 0xBC) + 0x40 if low_byte >= 0x7F low_byte += 1 end halfword = high_byte | low_byte return halfword end def font_character_mapping_hod(index) index -= 0x8540 shift_jis = fs.read(SHIFT_JIS_MAPPING_LIST + index*4, 2).unpack("v").first return shift_jis end def reverse_font_character_mapping_hod(shift_jis) found_index = nil (0..0x25).each do |char_index| possible_shift_jis = fs.read(SHIFT_JIS_MAPPING_LIST + char_index*4, 2).unpack("v").first if shift_jis == possible_shift_jis found_index = char_index break end end if found_index.nil? return nil end halfword = 0x8540 + found_index return halfword end def decode_string(string) if GAME == "hod" decode_string_hod(string) elsif SYSTEM == :gba decode_string_aos(string) elsif REGION == :jp decode_string_jp(string) else decode_string_usa(string) end end def encode_string(string) string.force_encoding("UTF-8") encoded_string = string.scan(/(?<!\\){(?:(?!}).|\\})+(?<!\\)}|\\{|\\}|\\n|./m).map do |str| if str.length > 1 if str == "\\n" command = str else str =~ /{([A-Z0-9_]+)(?: (?:0x)?([^}]+))?}/ command = $1 data = $2 end if GAME == "hod" encode_command_hod(command, data) elsif SYSTEM == :gba encode_command_aos(command, data) elsif REGION == :jp encode_command_jp(command, data) else encode_command_usa(command, data) end else if GAME == "hod" encode_char_hod(str) elsif SYSTEM == :gba encode_char_aos(str) elsif REGION == :jp encode_char_jp(str) else encode_char_usa(str) end end end.join return encoded_string end def decode_string_usa(string) data_format_string = "0x%02X" previous_byte = nil multipart = false skip_next = false curr_is_command = nil prev_was_command = nil i = 0 decoded_string = string.each_char.map do |char| byte = char.unpack("C").first char = if skip_next skip_next = false "" elsif multipart curr_is_command = true multipart = false command_number = previous_byte - 0xE0 if command_number == 1 # ENDCHOICE # Needs halfword data even in the US version. The halfword data is big endian. skip_next = true decode_multipart_command(command_number, string[i,2].unpack("n"), "0x%04X") else decode_multipart_command(command_number, byte, data_format_string) end elsif byte >= 0xE0 curr_is_command = true command_number = byte - 0xE0 command = decode_command(command_number, data_format_string) if (0x0B..0x1A).include?(command_number) # BUTTON curr_is_command = false end if command == :multipart multipart = true "" else command end else curr_is_command = false case byte when 0x00..0x5E # Ascii text char = [byte + 0x20].pack("C") if char == "{" || char == "}" char = "\\" + char end char when 0x5F..0xBE NDS_SPECIAL_CHARACTERS[byte-0x5F] else "{RAW #{data_format_string}}" % byte end end if curr_is_command != prev_was_command && !prev_was_command.nil? && previous_byte != 0xE6 && byte != 0xE6 # Add a newline between a block of commands and some text for readability. char = "\n#{char}" end previous_byte = byte prev_was_command = curr_is_command i += 1 char end.join return decoded_string end def decode_string_jp(string) data_format_string = "0x%04X" previous_halfword = nil multipart = false curr_is_command = nil prev_was_command = nil decoded_string = string.unpack("v*").map do |char| halfword = char char = if multipart curr_is_command = true multipart = false command_number = previous_halfword & 0x00FF decode_multipart_command(command_number, halfword, data_format_string) elsif halfword & 0xFF00 == 0xF000 curr_is_command = true command_number = halfword & 0x00FF command = decode_command(command_number, data_format_string) if (0x0B..0x1A).include?(command_number) # BUTTON curr_is_command = false end if command == :multipart multipart = true "" else command end elsif halfword >= 0x8140 curr_is_command = false shift_jis = font_character_mapping_jp(halfword) shift_jis.chr(Encoding::SHIFT_JIS).encode("UTF-8") else prev_was_command = false "{RAW #{data_format_string}}" % halfword end if curr_is_command != prev_was_command && !prev_was_command.nil? && previous_halfword != 0xF006 && halfword != 0xF006 # Add a newline between a block of commands and some text for readability. char = "\n#{char}" end previous_halfword = halfword prev_was_command = curr_is_command char end.join return decoded_string end def decode_string_aos(string) data_format_string = "0x%02X" previous_byte = nil multipart = false skip_next = false curr_is_command = nil prev_was_command = nil i = 0 decoded_string = string.each_char.map do |char| byte = char.unpack("C").first char = if multipart curr_is_command = true multipart = false command_number = previous_byte decode_multipart_command(command_number, byte, data_format_string) elsif byte < 0x20 curr_is_command = true command_number = byte command = decode_command(command_number, data_format_string) if (0x0B..0x1A).include?(command_number) # BUTTON curr_is_command = false end if command == :multipart multipart = true "" else command end else curr_is_command = false if (0x20..0x7E).include?(byte) # Ascii text char = [byte].pack("C") if char == "{" || char == "}" char = "\\" + char end char elsif AOS_SPECIAL_CHARACTERS.key?(byte) AOS_SPECIAL_CHARACTERS[byte] else "{RAW #{data_format_string}}" % byte end end if curr_is_command != prev_was_command && !prev_was_command.nil? && previous_byte != 0x06 && byte != 0x06 # Add a newline between a block of commands and some text for readability. char = "\n#{char}" end previous_byte = byte prev_was_command = curr_is_command i += 1 char end.join return decoded_string end def decode_string_hod(string) data_format_string = "0x%04X" previous_halfword = nil multipart = false curr_is_command = nil prev_was_command = nil decoded_string = string.unpack("v*").map do |char| halfword = char char = if multipart curr_is_command = true multipart = false command_number = previous_halfword & 0x00FF if command_number == 1 # NAMEINSERT curr_is_command = false end decode_multipart_command(command_number, halfword, data_format_string) elsif halfword & 0xFF00 == 0xF000 curr_is_command = true command_number = halfword & 0x00FF command = decode_command(command_number, data_format_string) if (0x0B..0x1A).include?(command_number) # BUTTON curr_is_command = false end if command == :multipart multipart = true if command_number == 1 # NAMEINSERT curr_is_command = false end "" else command end elsif halfword >= 0x8140 && halfword <= 0x853F curr_is_command = false shift_jis = halfword shift_jis.chr(Encoding::SHIFT_JIS).encode("UTF-8") elsif halfword >= 0x8540 # lowercase letter curr_is_command = false shift_jis = font_character_mapping_hod(halfword) shift_jis.chr(Encoding::SHIFT_JIS).encode("UTF-8") else prev_was_command = false "{RAW #{data_format_string}}" % halfword end if curr_is_command != prev_was_command && !prev_was_command.nil? && previous_halfword != 0xF006 && halfword != 0xF006 && halfword != 0xF001 # Add a newline between a block of commands and some text for readability. char = "\n#{char}" end previous_halfword = halfword prev_was_command = curr_is_command char end.join decoded_string = Unicode::Japanese.z2h(decoded_string) # Convert fullwidth to halfwidth text return decoded_string end def decode_command(command_number, data_format_string) case command_number when 0x00 "{RAW #{data_format_string}}" % command_number when 0x01, 0x02, 0x03, 0x07, 0x08 :multipart when 0x04 "{NEWCHAR}" when 0x05 "{WAITINPUT}" when 0x06 "\\n\n" when 0x09 "{SAMECHAR}" when 0x0B..0x14 if GAME == "aos" if command_number == 0x13 "{CURRENT_SAVE_FILE}" elsif command_number == 0x14 # Seems to be unused "{RAW #{data_format_string}}" % command_number else button = %w(B A L R UP DOWN RIGHT LEFT)[command_number-0x0B] "{BUTTON #{button}}" end elsif GAME == "hod" # No button commands in HoD "{RAW #{data_format_string}}" % command_number else button = %w(L R A B X Y LEFT RIGHT UP DOWN)[command_number-0x0B] "{BUTTON #{button}}" end else # Note: For AoS, commands 0x15-0x1A won't render anything at all. "{RAW #{data_format_string}}" % command_number end end def decode_multipart_command(command_number, data, data_format_string) case command_number when 0x01 if GAME == "hod" "{NAMEINSERT #{data_format_string}}" % data else "{ENDCHOICE #{data_format_string}}" % data end when 0x02 case data when 0x01 "{NEXTACTION}" when 0x03 "{CHOICE}" else "{COMMAND2 #{data_format_string}}" % data end when 0x03 "{PORTRAIT #{data_format_string}}" % data when 0x07 "{NAME #{data_format_string}}" % data when 0x08 color_name = TEXT_COLOR_NAMES[data] if color_name.nil? "{TEXTCOLOR #{data_format_string}}" % data else "{TEXTCOLOR %s}" % color_name end else raise TextDecodeError.new("Failed to decode command: #{data_format_string} #{data_format_string}" % [command_number, data]) end end def encode_char_usa(str) if NDS_SPECIAL_CHARACTERS.include?(str) index = NDS_SPECIAL_CHARACTERS.index(str) return [index+0x5F].pack("C") end byte = str.unpack("C").first char = case byte when 0x20..0x7A # Ascii text [byte - 0x20].pack("C") when 0x0A # Newline # Ignore "" end char end def encode_command_usa(command, data) case command when "RAW" byte = data.to_i(16) [byte].pack("C") when "BUTTON" button_index = %w(L R A B X Y LEFT RIGHT UP DOWN).index(data) if button_index.nil? raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end [0xEB + button_index].pack("C") when "PORTRAIT" byte = data.to_i(16) [0xE3, byte].pack("CC") when "NEWCHAR" [0xE4].pack("C") when "SAMECHAR" [0xE9].pack("C") when "WAITINPUT" [0xE5].pack("C") when "NAME" byte = data.to_i(16) [0xE7, byte].pack("CC") when "NEXTACTION" [0xE2, 0x01].pack("CC") when "CHOICE" [0xE2, 0x03].pack("CC") when "COMMAND2" byte = data.to_i(16) [0xE2, byte].pack("CC") when "ENDCHOICE" byte = data.to_i(16) [0xE1, byte].pack("Cn") when "TEXTCOLOR" color_name = data byte = TEXT_COLOR_NAMES.key(color_name) if byte [0xE8, byte].pack("CC") else [0xE8, data.to_i(16)].pack("CC") end when "\\n" [0xE6].pack("C") else raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end end def encode_command_hod(command, data) case command when "RAW" halfword = data.to_i(16) [halfword].pack("v") when "PORTRAIT" halfword = data.to_i(16) [0xF003, halfword].pack("vv") when "NEWCHAR" [0xF004].pack("v") when "SAMECHAR" [0xF009].pack("v") when "WAITINPUT" [0xF005].pack("v") when "NAME" halfword = data.to_i(16) [0xF007, halfword].pack("vv") when "NEXTACTION" [0xF002, 0x0001].pack("vv") when "CHOICE" [0xF002, 0x0003].pack("vv") when "COMMAND2" halfword = data.to_i(16) [0xF002, halfword].pack("vv") when "NAMEINSERT" halfword = data.to_i(16) [0xF001, halfword].pack("vv") when "TEXTCOLOR" color_name = data halfword = TEXT_COLOR_NAMES.key(color_name) if halfword [0xF008, halfword].pack("vv") else [0xF008, data.to_i(16)].pack("vv") end when "\\n" [0xF006].pack("v") else raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end end def encode_char_hod(input_char) if input_char == "\n" return "" # Ignore newlines end if input_char == "-" # Shift JIS does not have normal ASCII hyphen-minus signs. # To avoid a conversion error, convert any of those the user typed into a type of minus sign supported by Shift JIS. input_char = "−" end fullwidth_char = Unicode::Japanese.h2z(input_char) # Convert halfwidth text back to fullwidth before writing it shift_jis = fullwidth_char.encode("SHIFT_JIS").ord index = reverse_font_character_mapping_hod(shift_jis) if index.nil? index = shift_jis end return [index].pack("v") end def encode_char_aos(str) if AOS_SPECIAL_CHARACTERS.value?(str) return [AOS_SPECIAL_CHARACTERS.invert[str]].pack("C") end byte = str.unpack("C").first char = case byte when 0x20..0x7E # Ascii text [byte].pack("C") when 0x0A # Newline # Ignore "" end char end def encode_command_aos(command, data) case command when "RAW" byte = data.to_i(16) [byte].pack("C") when "BUTTON" button_index = %w(B A L R UP DOWN RIGHT LEFT).index(data) if button_index.nil? raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end [0xB + button_index].pack("C") when "CURRENT_SAVE_FILE" [0x13].pack("C") when "PORTRAIT" byte = data.to_i(16) [0x3, byte].pack("CC") when "NEWCHAR" [0x4].pack("C") when "SAMECHAR" [0x9].pack("C") when "WAITINPUT" [0x5].pack("C") when "NAME" byte = data.to_i(16) [0x7, byte].pack("CC") when "NEXTACTION" [0x2, 0x01].pack("CC") when "CHOICE" [0x2, 0x03].pack("CC") when "COMMAND2" byte = data.to_i(16) [0x2, byte].pack("CC") when "ENDCHOICE" byte = data.to_i(16) [0x1, byte].pack("Cn") when "TEXTCOLOR" color_name = data byte = TEXT_COLOR_NAMES.key(color_name) if byte [0x8, byte].pack("CC") else [0x8, data.to_i(16)].pack("CC") end when "\\n" [0x6].pack("C") else raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end end def encode_char_jp(input_char) if input_char == "\n" return "" # Ignore newlines end shift_jis = input_char.encode("SHIFT_JIS").ord index = reverse_font_character_mapping_jp(shift_jis) return [index].pack("v") end def encode_command_jp(command, data) case command when "RAW" halfword = data.to_i(16) [halfword].pack("v") when "BUTTON" button_index = %w(L R A B X Y LEFT RIGHT UP DOWN).index(data) if button_index.nil? raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end if button_index [0xF00B + button_index].pack("v") elsif (0x15..0x1A).include?(data.to_i(16)) [0xF000 + data.to_i(16)].pack("v") else raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end when "PORTRAIT" halfword = data.to_i(16) [0xF003, halfword].pack("vv") when "NEWCHAR" [0xF004].pack("v") when "SAMECHAR" [0xF009].pack("v") when "WAITINPUT" [0xF005].pack("v") when "NAME" halfword = data.to_i(16) [0xF007, halfword].pack("vv") when "NEXTACTION" [0xF002, 0x0001].pack("vv") when "CHOICE" [0xF002, 0x0003].pack("vv") when "COMMAND2" halfword = data.to_i(16) [0xF002, halfword].pack("vv") when "ENDCHOICE" halfword = data.to_i(16) [0xF001, halfword].pack("vv") when "TEXTCOLOR" color_name = data halfword = TEXT_COLOR_NAMES.key(color_name) if halfword [0xF008, halfword].pack("vv") else [0xF008, data.to_i(16)].pack("vv") end when "\\n" [0xF006].pack("v") else raise TextEncodeError.new("Failed to encode command: #{command} #{data}") end end end
LagoLunatic/DSVEdit
dsvlib/text.rb
Ruby
mit
22,491
<?php namespace Icecave\Pasta\AST\Expr; // @codeCoverageIgnoreStart class BitwiseOr extends PolyadicOperator { }
IcecaveStudios/pasta-ast
src/Expr/BitwiseOr.php
PHP
mit
115
import containers from './containers' import ui from './ui' import App from './App' module.exports = {...containers, ...ui, App}
MoonTahoe/cyber-chat
components/index.js
JavaScript
mit
129
<?php namespace Concrete\Package\AttributePlainText; use Concrete\Core\Backup\ContentImporter; use Package; class Controller extends Package { protected $pkgHandle = 'attribute_plain_text'; protected $appVersionRequired = '5.7.4'; protected $pkgVersion = '1.0.1'; public function getPackageName() { return t('Plain text attribute'); } public function getPackageDescription() { return t('Installs a plain text attribute you can use to add labels and hints'); } protected function installXmlContent() { $pkg = Package::getByHandle($this->pkgHandle); $ci = new ContentImporter(); $ci->importContentFile($pkg->getPackagePath() . '/install.xml'); } public function install() { $pkg = parent::install(); $this->installXmlContent(); } public function upgrade() { parent::upgrade(); $this->installXmlContent(); } }
Remo/concrete5-attribute-plain-text
controller.php
PHP
mit
964
'use strict'; // Production specific configuration // ================================= module.exports = { // Server IP ip: process.env.OPENSHIFT_NODEJS_IP || process.env.IP || undefined, // Server port port: process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8080, // MongoDB connection options mongo: { uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME || 'mongodb://localhost/spicyparty' } };
johnttan/spicybattle
server/config/environment/production.js
JavaScript
mit
597
/* * generated by Xtext */ package co.edu.uniandes.mono.gesco.ui.contentassist.antlr; import java.util.Collection; import java.util.Collections; import org.eclipse.xtext.AbstractRule; import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.IPartialContentAssistParser; import org.eclipse.xtext.ui.editor.contentassist.antlr.FollowElement; import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser; import org.eclipse.xtext.util.PolymorphicDispatcher; /** * @author Sebastian Zarnekow - Initial contribution and API */ @SuppressWarnings("restriction") public class PartialDSLContentAssistParser extends DSLParser implements IPartialContentAssistParser { private AbstractRule rule; public void initializeFor(AbstractRule rule) { this.rule = rule; } @Override protected Collection<FollowElement> getFollowElements(AbstractInternalContentAssistParser parser) { if (rule == null || rule.eIsProxy()) return Collections.emptyList(); String methodName = "entryRule" + rule.getName(); PolymorphicDispatcher<Collection<FollowElement>> dispatcher = new PolymorphicDispatcher<Collection<FollowElement>>(methodName, 0, 0, Collections.singletonList(parser)); dispatcher.invoke(); return parser.getFollowElements(); } }
lfmendivelso10/GescoFinal
DSL/co.edu.uniandes.mono.gesco.ui/src-gen/co/edu/uniandes/mono/gesco/ui/contentassist/antlr/PartialDSLContentAssistParser.java
Java
mit
1,288
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const repl = require('repl'); const program = require('commander'); const esper = require('..'); const Engine = esper.Engine; function enterRepl() { function replEval(cmd, context, fn, cb) { engine.evalDetatched(cmd).then(function(result) { cb(null, result); }, function(err) { console.log(err.stack); cb(null); }); } return repl.start({ prompt: 'js> ', eval: replEval }); } program .version(esper.version) .usage('[options] [script...]') .option('-v, --version', 'print esper version') .option('-i, --interactive', 'enter REPL') .option('-s, --strict', 'force strict mode') .option('-d, --debug', 'turn on performance debugging') .option('-c, --compile <mode>', 'set compileing mode') .option('-e, --eval <script>', 'evaluate script') .option('-p, --print <script>', 'evaluate script and print result') .option('-l, --language <language>', `set langauge (${Object.keys(esper.languages).join(', ')})`) .parse(process.argv); if ( program.language ) esper.plugin('lang-' + program.language); if ( program.v ) { console.log("v" + esper.version); process.exit(); } let engine = new Engine({ strict: !!program.strict, debug: !!program.debug, runtime: true, addInternalStack: !!program.debug, compile: program.compile || 'pre', language: program.language || 'javascript', esposeESHostGlobal: true, esRealms: true, }); let toEval = program.args.slice(0).map((f) => ({type: 'file', value: f})); if ( program.eval ) toEval.push({type: 'str', value: program.eval + '\n'}); if ( program.print ) toEval.push({type: 'str', value: program.print + '\n', print: true}); if ( toEval.length < 1 ) program.interactive = true; function next() { if ( toEval.length === 0 ) { if ( program.interactive ) return enterRepl(); else return process.exit(); } var fn = toEval.shift(); var code; if ( fn.type === 'file' ) { code = fs.readFileSync(fn.value, 'utf8'); } else { code = fn.value; } return engine.evalDetatched(code).then(function(val) { if ( fn.print && val ) console.log(val.debugString); return next(); }).catch(function(e) { if ( e.stack ) { process.stderr.write(e.stack + "\n"); } else { process.stderr.write(`${e.name}: ${e.message}\n`); } }); } next(); /* Usage: node [options] [ -e script | script.js ] [arguments] node debug script.js [arguments] Options: -v, --version print Node.js version -e, --eval script evaluate script -p, --print evaluate script and print result -c, --check syntax check script without executing -i, --interactive always enter the REPL even if stdin does not appear to be a terminal -r, --require module to preload (option can be repeated) --no-deprecation silence deprecation warnings --throw-deprecation throw an exception anytime a deprecated function is used --trace-deprecation show stack traces on deprecations --trace-sync-io show stack trace when use of sync IO is detected after the first tick --track-heap-objects track heap object allocations for heap snapshots --v8-options print v8 command line options --tls-cipher-list=val use an alternative default TLS cipher list --icu-data-dir=dir set ICU data load path to dir (overrides NODE_ICU_DATA) Environment variables: NODE_PATH ':'-separated list of directories prefixed to the module search path. NODE_DISABLE_COLORS set to 1 to disable colors in the REPL NODE_ICU_DATA data path for ICU (Intl object) data NODE_REPL_HISTORY path to the persistent REPL history file Documentation can be found at https://nodejs.org/ */
codecombat/esper.js
contrib/cli.js
JavaScript
mit
3,797
using System.IO; using System.Linq; namespace Moonfish.Guerilla.Tags { partial class StructureBspClusterBlock : IResourceBlock { public ResourcePointer GetResourcePointer(int index = 0) { return GeometryBlockInfo.BlockOffset; } public int GetResourceLength(int index = 0) { return GeometryBlockInfo.BlockSize; } public void SetResourcePointer(ResourcePointer pointer, int index = 0) { GeometryBlockInfo.BlockOffset = pointer; } public void SetResourceLength(int length, int index = 0) { GeometryBlockInfo.BlockSize = length; } public bool IsClusterDataLoaded => ClusterData.Length > 0; public void LoadClusterData() { var resourceStream = GeometryBlockInfo.GetResourceFromCache(); if (resourceStream == null) return; var clusterBlock = new StructureBspClusterDataBlockNew(); using (var binaryReader = new BinaryReader(resourceStream)) { clusterBlock.Read(binaryReader); var vertexBufferResources = GeometryBlockInfo.Resources.Where( x => x.Type == GlobalGeometryBlockResourceBlock.TypeEnum.VertexBuffer).ToArray(); for (var i = 0; i < clusterBlock.Section.VertexBuffers.Length && i < vertexBufferResources.Length; ++i) { clusterBlock.Section.VertexBuffers[i].VertexBuffer.Data = resourceStream.GetResourceData(vertexBufferResources[i]); } } ClusterData = new[] {clusterBlock}; } public void DeleteClusterData() { if ( ClusterData.Length <= 0 ) return; foreach ( var globalGeometrySectionVertexBufferBlock in ClusterData[0].Section.VertexBuffers ) { globalGeometrySectionVertexBufferBlock.VertexBuffer.Data = null; } } } }
jacksoncougar/Moonfxsh
Moonfish/Guerilla/Tags/StructureBspClusterBlock.cs
C#
mit
2,077
<?php if(isset($user)) {?> <table> <tr> <td><?php echo $user->username;?></td> <td><?php echo $user->password;?></td> <td><?php echo $user->email;?></td> </tr> </table> <?php }?> <?php echo validation_errors('<p class="error">');?>
Du-an-Giao-Duc/education
application/views/login/register_confirm.php
PHP
mit
231
package selector; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.util.EventObject; class Barra implements AdjustmentListener { SelectorApplet applet; public Barra(SelectorApplet applet) { this.applet = applet; } public void adjustmentValueChanged(AdjustmentEvent e) { Object obj = e.getSource(); if (obj == this.applet.sbElectrico) this.applet.sbElectrico_adjustmentValueChanged(e); else if (obj == this.applet.sbMagnetico) this.applet.sbMagnetico_adjustmentValueChanged(e); else this.applet.sbVelocidad_adjustmentValueChanged(e); } }
Thaenor/magnetic-and-electric-forces-study
src/selector/Barra.java
Java
mit
659
const express = require('express'); const router = express.Router(); const queries = require('../db/queries'); const knex = require('../db/knex.js'); const request = require('request'); router.get('/clear', (req, res, next) => { queries.clearStationsTable((results) => { console.log(results); }); res.redirect('/homepage'); }); router.get('/', function(req,res,next) { var riverName = req.query.river; queries.getRiverSites(riverName, function(err, results) { var returnObject = {}; if (err) { returnObject.message = err.message || 'Could not find sites'; res.status(400).render('error', returnObject); } else { returnObject.sites = results; res.send(returnObject); } }); }); router.get('/Arkansas', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=07079300,07081200,07083710,07087050,07091200,07094500,07099970,07099973,07109500,07124000,07130500,07133000,07134180&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Arkansas', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); router.get('/Upper%20South%20Platte', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=06700000,06701620,06701700,06701900,06708600,06708690,06708800,06709000,06709530,06709740,06709910,06710150,06710247,06710385,06710605,06711515,06711555,06711565,06711570,06711575,06711618,06711770,06711780&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Upper South Platte', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); router.get('/Blue', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=09041900,09044300,09044800,09046490,09046600,09047500,09047700,09050100,09050700,09051050,09056500,09057500&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Blue', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); router.get('/Roaring%20Fork', function (req, res, next) { const { renderObject } = req; request('http://waterservices.usgs.gov/nwis/iv/?format=json&sites=09072550,09073005,09073300,09073400,09074000,09074500,09075400,09078141,09078475,09079450,09080400,09081000,09081600,09085000&parameterCd=00060', (err, res, body) => { if(!err && res.statusCode === 200) { const usgsPayload = JSON.parse(body); const parsedUSGS = usgsPayload.value.timeSeries; for (var i = 0; i < parsedUSGS.length; i++) { var stationData = { river: 'Roaring Fork', site_name: parsedUSGS[i].sourceInfo.siteName, flow_rate: parsedUSGS[i].values[0].value[0].value, lat: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.latitude, lon: parsedUSGS[i].sourceInfo.geoLocation.geogLocation.longitude, reading_date_time: parsedUSGS[i].values[0].value[0].dateTime }; queries.updateRiverData(stationData, function (req, res, next) { if (err) { var returnObject = {}; returnObject.message = err.message || 'Data not added'; res.render('error', returnObject); } else { let returnObject = {}; returnObject.message = 'Data succesfully added!'; } }); } } }); res.redirect('/homepage'); }); module.exports = router;
gvickstrom/Fishing_App
src/server/routes/sites.js
JavaScript
mit
6,277
//=============================================================================== // TinyIoC // // An easy to use, hassle free, Inversion of Control Container for small projects // and beginners alike. // // https://github.com/grumpydev/TinyIoC //=============================================================================== // Copyright © Steven Robbins. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== #region Preprocessor Directives // Uncomment this line if you want the container to automatically // register the TinyMessenger messenger/event aggregator //#define TINYMESSENGER // PCL profile supports System.Linq.Expressions // PCL profile does not support compiling expressions (due to restriction in MonoTouch) // PCL profile does not support getting all assemblies from the AppDomain object // PCL profile supports GetConstructors on unbound generic types // PCL profile supports GetParameters on open generics // PCL profile supports resolving open generics // MonoTouch does not support compiled exceptions due to the restriction on Reflection.Emit // (http://docs.xamarin.com/guides/ios/advanced_topics/limitations#No_Dynamic_Code_Generation) // Note: This restriction is not enforced on the emulator (at the moment), but on the device. // Note: Comment out the next line to compile a version that can be used with MonoTouch. #define COMPILED_EXPRESSIONS #if MONO_TOUCH #undef COMPILED_EXPRESSIONS #endif #endregion namespace TinyIoC { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Linq.Expressions; using System.Threading; #region SafeDictionary public class SafeDictionary<TKey, TValue> : IDisposable { private readonly object _Padlock = new object(); private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>(); public TValue this[TKey key] { set { lock (_Padlock) { TValue current; if (_Dictionary.TryGetValue(key, out current)) { var disposable = current as IDisposable; if (disposable != null) disposable.Dispose(); } _Dictionary[key] = value; } } } public bool TryGetValue(TKey key, out TValue value) { lock (_Padlock) { return _Dictionary.TryGetValue(key, out value); } } public bool Remove(TKey key) { lock (_Padlock) { return _Dictionary.Remove(key); } } public void Clear() { lock (_Padlock) { _Dictionary.Clear(); } } public IEnumerable<TKey> Keys { get { return _Dictionary.Keys; } } #region IDisposable Members public void Dispose() { lock (_Padlock) { var disposableItems = from item in _Dictionary.Values where item is IDisposable select item as IDisposable; foreach (var item in disposableItems) { item.Dispose(); } } GC.SuppressFinalize(this); } #endregion } #endregion #region Extensions public static class AssemblyExtensions { public static Type[] SafeGetTypes(this Assembly assembly) { Type[] assemblies; try { assemblies = assembly.GetTypes(); } catch (System.IO.FileNotFoundException) { assemblies = new Type[] { }; } catch (NotSupportedException) { assemblies = new Type[] { }; } catch (ReflectionTypeLoadException e) { assemblies = e.Types.Where(t => t != null).ToArray(); } return assemblies; } } public static class TypeExtensions { private static SafeDictionary<GenericMethodCacheKey, MethodInfo> _genericMethodCache; static TypeExtensions() { _genericMethodCache = new SafeDictionary<GenericMethodCacheKey, MethodInfo>(); } /// <summary> /// Gets a generic method from a type given the method name, binding flags, generic types and parameter types /// </summary> /// <param name="sourceType">Source type</param> /// <param name="bindingFlags">Binding flags</param> /// <param name="methodName">Name of the method</param> /// <param name="genericTypes">Generic types to use to make the method generic</param> /// <param name="parameterTypes">Method parameters</param> /// <returns>MethodInfo or null if no matches found</returns> /// <exception cref="System.Reflection.AmbiguousMatchException"/> /// <exception cref="System.ArgumentException"/> public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes) { MethodInfo method; var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); // Shouldn't need any additional locking // we don't care if we do the method info generation // more than once before it gets cached. if (!_genericMethodCache.TryGetValue(cacheKey, out method)) { method = GetMethod(sourceType, bindingFlags, methodName, genericTypes, parameterTypes); _genericMethodCache[cacheKey] = method; } return method; } private static MethodInfo GetMethod(Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes) { var methods = sourceType.GetMethods(bindingFlags).Where( mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where( mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length). Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select( mi => mi.MakeGenericMethod(genericTypes)).Where( mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList(); if (methods.Count > 1) { throw new AmbiguousMatchException(); } return methods.FirstOrDefault(); } private sealed class GenericMethodCacheKey { private readonly Type _sourceType; private readonly string _methodName; private readonly Type[] _genericTypes; private readonly Type[] _parameterTypes; private readonly int _hashCode; public GenericMethodCacheKey(Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) { _sourceType = sourceType; _methodName = methodName; _genericTypes = genericTypes; _parameterTypes = parameterTypes; _hashCode = GenerateHashCode(); } public override bool Equals(object obj) { var cacheKey = obj as GenericMethodCacheKey; if (cacheKey == null) return false; if (_sourceType != cacheKey._sourceType) return false; if (!String.Equals(_methodName, cacheKey._methodName, StringComparison.Ordinal)) return false; if (_genericTypes.Length != cacheKey._genericTypes.Length) return false; if (_parameterTypes.Length != cacheKey._parameterTypes.Length) return false; for (int i = 0; i < _genericTypes.Length; ++i) { if (_genericTypes[i] != cacheKey._genericTypes[i]) return false; } for (int i = 0; i < _parameterTypes.Length; ++i) { if (_parameterTypes[i] != cacheKey._parameterTypes[i]) return false; } return true; } public override int GetHashCode() { return _hashCode; } private int GenerateHashCode() { unchecked { var result = _sourceType.GetHashCode(); result = (result * 397) ^ _methodName.GetHashCode(); for (int i = 0; i < _genericTypes.Length; ++i) { result = (result * 397) ^ _genericTypes[i].GetHashCode(); } for (int i = 0; i < _parameterTypes.Length; ++i) { result = (result * 397) ^ _parameterTypes[i].GetHashCode(); } return result; } } } } #endregion #region TinyIoC Exception Types public class TinyIoCResolutionException : Exception { private const string ERROR_TEXT = "Unable to resolve type: {0}"; public TinyIoCResolutionException(Type type) : base(String.Format(ERROR_TEXT, type.FullName)) { } public TinyIoCResolutionException(Type type, Exception innerException) : base(String.Format(ERROR_TEXT, type.FullName), innerException) { } } public class TinyIoCRegistrationTypeException : Exception { private const string REGISTER_ERROR_TEXT = "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}."; public TinyIoCRegistrationTypeException(Type type, string factory) : base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory)) { } public TinyIoCRegistrationTypeException(Type type, string factory, Exception innerException) : base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory), innerException) { } } public class TinyIoCRegistrationException : Exception { private const string CONVERT_ERROR_TEXT = "Cannot convert current registration of {0} to {1}"; private const string GENERIC_CONSTRAINT_ERROR_TEXT = "Type {1} is not valid for a registration of type {0}"; public TinyIoCRegistrationException(Type type, string method) : base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method)) { } public TinyIoCRegistrationException(Type type, string method, Exception innerException) : base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method), innerException) { } public TinyIoCRegistrationException(Type registerType, Type implementationType) : base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName)) { } public TinyIoCRegistrationException(Type registerType, Type implementationType, Exception innerException) : base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName), innerException) { } } public class TinyIoCWeakReferenceException : Exception { private const string ERROR_TEXT = "Unable to instantiate {0} - referenced object has been reclaimed"; public TinyIoCWeakReferenceException(Type type) : base(String.Format(ERROR_TEXT, type.FullName)) { } public TinyIoCWeakReferenceException(Type type, Exception innerException) : base(String.Format(ERROR_TEXT, type.FullName), innerException) { } } public class TinyIoCConstructorResolutionException : Exception { private const string ERROR_TEXT = "Unable to resolve constructor for {0} using provided Expression."; public TinyIoCConstructorResolutionException(Type type) : base(String.Format(ERROR_TEXT, type.FullName)) { } public TinyIoCConstructorResolutionException(Type type, Exception innerException) : base(String.Format(ERROR_TEXT, type.FullName), innerException) { } public TinyIoCConstructorResolutionException(string message, Exception innerException) : base(message, innerException) { } public TinyIoCConstructorResolutionException(string message) : base(message) { } } public class TinyIoCAutoRegistrationException : Exception { private const string ERROR_TEXT = "Duplicate implementation of type {0} found ({1})."; public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types) : base(String.Format(ERROR_TEXT, registerType, GetTypesString(types))) { } public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types, Exception innerException) : base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)), innerException) { } private static string GetTypesString(IEnumerable<Type> types) { var typeNames = from type in types select type.FullName; return string.Join(",", typeNames.ToArray()); } } #endregion #region Public Setup / Settings Classes /// <summary> /// Name/Value pairs for specifying "user" parameters when resolving /// </summary> public sealed class NamedParameterOverloads : Dictionary<string, object> { public static NamedParameterOverloads FromIDictionary(IDictionary<string, object> data) { return data as NamedParameterOverloads ?? new NamedParameterOverloads(data); } public NamedParameterOverloads() { } public NamedParameterOverloads(IDictionary<string, object> data) : base(data) { } private static readonly NamedParameterOverloads _Default = new NamedParameterOverloads(); public static NamedParameterOverloads Default { get { return _Default; } } } public enum UnregisteredResolutionActions { /// <summary> /// Attempt to resolve type, even if the type isn't registered. /// /// Registered types/options will always take precedence. /// </summary> AttemptResolve, /// <summary> /// Fail resolution if type not explicitly registered /// </summary> Fail, /// <summary> /// Attempt to resolve unregistered type if requested type is generic /// and no registration exists for the specific generic parameters used. /// /// Registered types/options will always take precedence. /// </summary> GenericsOnly } public enum NamedResolutionFailureActions { AttemptUnnamedResolution, Fail } /// <summary> /// Resolution settings /// </summary> public sealed class ResolveOptions { private static readonly ResolveOptions _Default = new ResolveOptions(); private static readonly ResolveOptions _FailUnregisteredAndNameNotFound = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail }; private static readonly ResolveOptions _FailUnregisteredOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.AttemptUnnamedResolution, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail }; private static readonly ResolveOptions _FailNameNotFoundOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve }; private UnregisteredResolutionActions _UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve; public UnregisteredResolutionActions UnregisteredResolutionAction { get { return _UnregisteredResolutionAction; } set { _UnregisteredResolutionAction = value; } } private NamedResolutionFailureActions _NamedResolutionFailureAction = NamedResolutionFailureActions.Fail; public NamedResolutionFailureActions NamedResolutionFailureAction { get { return _NamedResolutionFailureAction; } set { _NamedResolutionFailureAction = value; } } /// <summary> /// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found) /// </summary> public static ResolveOptions Default { get { return _Default; } } /// <summary> /// Preconfigured option for attempting resolution of unregistered types and failing on named resolution if name not found /// </summary> public static ResolveOptions FailNameNotFoundOnly { get { return _FailNameNotFoundOnly; } } /// <summary> /// Preconfigured option for failing on resolving unregistered types and on named resolution if name not found /// </summary> public static ResolveOptions FailUnregisteredAndNameNotFound { get { return _FailUnregisteredAndNameNotFound; } } /// <summary> /// Preconfigured option for failing on resolving unregistered types, but attempting unnamed resolution if name not found /// </summary> public static ResolveOptions FailUnregisteredOnly { get { return _FailUnregisteredOnly; } } } #endregion public sealed partial class TinyIoCContainer : IDisposable { private sealed class MethodAccessException : Exception { } #region "Fluent" API /// <summary> /// Registration options for "fluent" API /// </summary> public sealed class RegisterOptions { private TinyIoCContainer _Container; private TypeRegistration _Registration; public RegisterOptions(TinyIoCContainer container, TypeRegistration registration) { _Container = container; _Registration = registration; } /// <summary> /// Make registration a singleton (single instance) if possible /// </summary> /// <returns>RegisterOptions</returns> /// <exception cref="TinyIoCInstantiationTypeException"></exception> public RegisterOptions AsSingleton() { var currentFactory = _Container.GetCurrentFactory(_Registration); if (currentFactory == null) throw new TinyIoCRegistrationException(_Registration.Type, "singleton"); return _Container.AddUpdateRegistration(_Registration, currentFactory.SingletonVariant); } /// <summary> /// Make registration multi-instance if possible /// </summary> /// <returns>RegisterOptions</returns> /// <exception cref="TinyIoCInstantiationTypeException"></exception> public RegisterOptions AsMultiInstance() { var currentFactory = _Container.GetCurrentFactory(_Registration); if (currentFactory == null) throw new TinyIoCRegistrationException(_Registration.Type, "multi-instance"); return _Container.AddUpdateRegistration(_Registration, currentFactory.MultiInstanceVariant); } /// <summary> /// Make registration hold a weak reference if possible /// </summary> /// <returns>RegisterOptions</returns> /// <exception cref="TinyIoCInstantiationTypeException"></exception> public RegisterOptions WithWeakReference() { var currentFactory = _Container.GetCurrentFactory(_Registration); if (currentFactory == null) throw new TinyIoCRegistrationException(_Registration.Type, "weak reference"); return _Container.AddUpdateRegistration(_Registration, currentFactory.WeakReferenceVariant); } /// <summary> /// Make registration hold a strong reference if possible /// </summary> /// <returns>RegisterOptions</returns> /// <exception cref="TinyIoCInstantiationTypeException"></exception> public RegisterOptions WithStrongReference() { var currentFactory = _Container.GetCurrentFactory(_Registration); if (currentFactory == null) throw new TinyIoCRegistrationException(_Registration.Type, "strong reference"); return _Container.AddUpdateRegistration(_Registration, currentFactory.StrongReferenceVariant); } public RegisterOptions UsingConstructor<RegisterType>(Expression<Func<RegisterType>> constructor) { var lambda = constructor as LambdaExpression; if (lambda == null) throw new TinyIoCConstructorResolutionException(typeof(RegisterType)); var newExpression = lambda.Body as NewExpression; if (newExpression == null) throw new TinyIoCConstructorResolutionException(typeof(RegisterType)); var constructorInfo = newExpression.Constructor; if (constructorInfo == null) throw new TinyIoCConstructorResolutionException(typeof(RegisterType)); var currentFactory = _Container.GetCurrentFactory(_Registration); if (currentFactory == null) throw new TinyIoCConstructorResolutionException(typeof(RegisterType)); currentFactory.SetConstructor(constructorInfo); return this; } /// <summary> /// Switches to a custom lifetime manager factory if possible. /// /// Usually used for RegisterOptions "To*" extension methods such as the ASP.Net per-request one. /// </summary> /// <param name="instance">RegisterOptions instance</param> /// <param name="lifetimeProvider">Custom lifetime manager</param> /// <param name="errorString">Error string to display if switch fails</param> /// <returns>RegisterOptions</returns> public static RegisterOptions ToCustomLifetimeManager(RegisterOptions instance, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { if (instance == null) throw new ArgumentNullException("instance", "instance is null."); if (lifetimeProvider == null) throw new ArgumentNullException("lifetimeProvider", "lifetimeProvider is null."); if (String.IsNullOrEmpty(errorString)) throw new ArgumentException("errorString is null or empty.", "errorString"); var currentFactory = instance._Container.GetCurrentFactory(instance._Registration); if (currentFactory == null) throw new TinyIoCRegistrationException(instance._Registration.Type, errorString); return instance._Container.AddUpdateRegistration(instance._Registration, currentFactory.GetCustomObjectLifetimeVariant(lifetimeProvider, errorString)); } } /// <summary> /// Registration options for "fluent" API when registering multiple implementations /// </summary> public sealed class MultiRegisterOptions { private IEnumerable<RegisterOptions> _RegisterOptions; /// <summary> /// Initializes a new instance of the MultiRegisterOptions class. /// </summary> /// <param name="registerOptions">Registration options</param> public MultiRegisterOptions(IEnumerable<RegisterOptions> registerOptions) { _RegisterOptions = registerOptions; } /// <summary> /// Make registration a singleton (single instance) if possible /// </summary> /// <returns>RegisterOptions</returns> /// <exception cref="TinyIoCInstantiationTypeException"></exception> public MultiRegisterOptions AsSingleton() { _RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton()); return this; } /// <summary> /// Make registration multi-instance if possible /// </summary> /// <returns>MultiRegisterOptions</returns> /// <exception cref="TinyIoCInstantiationTypeException"></exception> public MultiRegisterOptions AsMultiInstance() { _RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance()); return this; } private IEnumerable<RegisterOptions> ExecuteOnAllRegisterOptions(Func<RegisterOptions, RegisterOptions> action) { var newRegisterOptions = new List<RegisterOptions>(); foreach (var registerOption in _RegisterOptions) { newRegisterOptions.Add(action(registerOption)); } return newRegisterOptions; } } #endregion #region Public API #region Child Containers public TinyIoCContainer GetChildContainer() { return new TinyIoCContainer(this); } #endregion #region Registration /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// </summary> public void AutoRegister() { AutoRegisterInternal(new Assembly[] {this.GetType().Assembly()}, true, null); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. /// Types will only be registered if they pass the supplied registration predicate. /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// </summary> /// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param> public void AutoRegister(Func<Type, bool> registrationPredicate) { AutoRegisterInternal(new Assembly[] { this.GetType().Assembly()}, true, registrationPredicate); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. /// </summary> /// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param> /// <exception cref="TinyIoCAutoRegistrationException"/> public void AutoRegister(bool ignoreDuplicateImplementations) { AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, null); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. /// Types will only be registered if they pass the supplied registration predicate. /// </summary> /// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param> /// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param> /// <exception cref="TinyIoCAutoRegistrationException"/> public void AutoRegister(bool ignoreDuplicateImplementations, Func<Type, bool> registrationPredicate) { AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, registrationPredicate); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// </summary> /// <param name="assemblies">Assemblies to process</param> public void AutoRegister(IEnumerable<Assembly> assemblies) { AutoRegisterInternal(assemblies, true, null); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// Types will only be registered if they pass the supplied registration predicate. /// /// If more than one class implements an interface then only one implementation will be registered /// although no error will be thrown. /// </summary> /// <param name="assemblies">Assemblies to process</param> /// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param> public void AutoRegister(IEnumerable<Assembly> assemblies, Func<Type, bool> registrationPredicate) { AutoRegisterInternal(assemblies, true, registrationPredicate); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// </summary> /// <param name="assemblies">Assemblies to process</param> /// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param> /// <exception cref="TinyIoCAutoRegistrationException"/> public void AutoRegister(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations) { AutoRegisterInternal(assemblies, ignoreDuplicateImplementations, null); } /// <summary> /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// Types will only be registered if they pass the supplied registration predicate. /// </summary> /// <param name="assemblies">Assemblies to process</param> /// <param name="ignoreDuplicateImplementations">Whether to ignore duplicate implementations of an interface/base class. False=throw an exception</param> /// <param name="registrationPredicate">Predicate to determine if a particular type should be registered</param> /// <exception cref="TinyIoCAutoRegistrationException"/> public void AutoRegister(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations, Func<Type, bool> registrationPredicate) { AutoRegisterInternal(assemblies, ignoreDuplicateImplementations, registrationPredicate); } /// <summary> /// Creates/replaces a container class registration with default options. /// </summary> /// <param name="registerType">Type to register</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType) { return RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerType)); } /// <summary> /// Creates/replaces a named container class registration with default options. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, string name) { return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType)); } /// <summary> /// Creates/replaces a container class registration with a given implementation and default options. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="registerImplementation">Type to instantiate that implements RegisterType</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, Type registerImplementation) { return this.RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerImplementation)); } /// <summary> /// Creates/replaces a named container class registration with a given implementation and default options. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="registerImplementation">Type to instantiate that implements RegisterType</param> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, Type registerImplementation, string name) { return this.RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation)); } /// <summary> /// Creates/replaces a container class registration with a specific, strong referenced, instance. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="instance">Instance of RegisterType to register</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, object instance) { return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerType, instance)); } /// <summary> /// Creates/replaces a named container class registration with a specific, strong referenced, instance. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="instance">Instance of RegisterType to register</param> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, object instance, string name) { return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerType, instance)); } /// <summary> /// Creates/replaces a container class registration with a specific, strong referenced, instance. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="registerImplementation">Type of instance to register that implements RegisterType</param> /// <param name="instance">Instance of RegisterImplementation to register</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, Type registerImplementation, object instance) { return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerImplementation, instance)); } /// <summary> /// Creates/replaces a named container class registration with a specific, strong referenced, instance. /// </summary> /// <param name="registerType">Type to register</param> /// <param name="registerImplementation">Type of instance to register that implements RegisterType</param> /// <param name="instance">Instance of RegisterImplementation to register</param> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, Type registerImplementation, object instance, string name) { return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerImplementation, instance)); } /// <summary> /// Creates/replaces a container class registration with a user specified factory /// </summary> /// <param name="registerType">Type to register</param> /// <param name="factory">Factory/lambda that returns an instance of RegisterType</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory) { return RegisterInternal(registerType, string.Empty, new DelegateFactory(registerType, factory)); } /// <summary> /// Creates/replaces a container class registration with a user specified factory /// </summary> /// <param name="registerType">Type to register</param> /// <param name="factory">Factory/lambda that returns an instance of RegisterType</param> /// <param name="name">Name of registation</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory, string name) { return RegisterInternal(registerType, name, new DelegateFactory(registerType, factory)); } /// <summary> /// Creates/replaces a container class registration with default options. /// </summary> /// <typeparam name="RegisterImplementation">Type to register</typeparam> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType>() where RegisterType : class { return this.Register(typeof(RegisterType)); } /// <summary> /// Creates/replaces a named container class registration with default options. /// </summary> /// <typeparam name="RegisterImplementation">Type to register</typeparam> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType>(string name) where RegisterType : class { return this.Register(typeof(RegisterType), name); } /// <summary> /// Creates/replaces a container class registration with a given implementation and default options. /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <typeparam name="RegisterImplementation">Type to instantiate that implements RegisterType</typeparam> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType, RegisterImplementation>() where RegisterType : class where RegisterImplementation : class, RegisterType { return this.Register(typeof(RegisterType), typeof(RegisterImplementation)); } /// <summary> /// Creates/replaces a named container class registration with a given implementation and default options. /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <typeparam name="RegisterImplementation">Type to instantiate that implements RegisterType</typeparam> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType, RegisterImplementation>(string name) where RegisterType : class where RegisterImplementation : class, RegisterType { return this.Register(typeof(RegisterType), typeof(RegisterImplementation), name); } /// <summary> /// Creates/replaces a container class registration with a specific, strong referenced, instance. /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <param name="instance">Instance of RegisterType to register</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType>(RegisterType instance) where RegisterType : class { return this.Register(typeof(RegisterType), instance); } /// <summary> /// Creates/replaces a named container class registration with a specific, strong referenced, instance. /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <param name="instance">Instance of RegisterType to register</param> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType>(RegisterType instance, string name) where RegisterType : class { return this.Register(typeof(RegisterType), instance, name); } /// <summary> /// Creates/replaces a container class registration with a specific, strong referenced, instance. /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <typeparam name="RegisterImplementation">Type of instance to register that implements RegisterType</typeparam> /// <param name="instance">Instance of RegisterImplementation to register</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance) where RegisterType : class where RegisterImplementation : class, RegisterType { return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance); } /// <summary> /// Creates/replaces a named container class registration with a specific, strong referenced, instance. /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <typeparam name="RegisterImplementation">Type of instance to register that implements RegisterType</typeparam> /// <param name="instance">Instance of RegisterImplementation to register</param> /// <param name="name">Name of registration</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance, string name) where RegisterType : class where RegisterImplementation : class, RegisterType { return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance, name); } /// <summary> /// Creates/replaces a container class registration with a user specified factory /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <param name="factory">Factory/lambda that returns an instance of RegisterType</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory) where RegisterType : class { if (factory == null) { throw new ArgumentNullException("factory"); } return this.Register(typeof(RegisterType), (c, o) => factory(c, o)); } /// <summary> /// Creates/replaces a named container class registration with a user specified factory /// </summary> /// <typeparam name="RegisterType">Type to register</typeparam> /// <param name="factory">Factory/lambda that returns an instance of RegisterType</param> /// <param name="name">Name of registation</param> /// <returns>RegisterOptions for fluent API</returns> public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory, string name) where RegisterType : class { if (factory == null) { throw new ArgumentNullException("factory"); } return this.Register(typeof(RegisterType), (c, o) => factory(c, o), name); } /// <summary> /// Register multiple implementations of a type. /// /// Internally this registers each implementation using the full name of the class as its registration name. /// </summary> /// <typeparam name="RegisterType">Type that each implementation implements</typeparam> /// <param name="implementationTypes">Types that implement RegisterType</param> /// <returns>MultiRegisterOptions for the fluent API</returns> public MultiRegisterOptions RegisterMultiple<RegisterType>(IEnumerable<Type> implementationTypes) { return RegisterMultiple(typeof(RegisterType), implementationTypes); } /// <summary> /// Register multiple implementations of a type. /// /// Internally this registers each implementation using the full name of the class as its registration name. /// </summary> /// <param name="registrationType">Type that each implementation implements</param> /// <param name="implementationTypes">Types that implement RegisterType</param> /// <returns>MultiRegisterOptions for the fluent API</returns> public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable<Type> implementationTypes) { if (implementationTypes == null) throw new ArgumentNullException("types", "types is null."); foreach (var type in implementationTypes) if (!registrationType.IsAssignableFrom(type)) throw new ArgumentException(String.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName)); if (implementationTypes.Count() != implementationTypes.Distinct().Count()) { var queryForDuplicatedTypes = from i in implementationTypes group i by i into j where j.Count() > 1 select j.Key.FullName; var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray()); var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes); throw new ArgumentException(multipleRegMessage); } var registerOptions = new List<RegisterOptions>(); foreach (var type in implementationTypes) { registerOptions.Add(Register(registrationType, type, type.FullName)); } return new MultiRegisterOptions(registerOptions); } #endregion #region Resolution /// <summary> /// Attempts to resolve a type using default options. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType) { return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default); } /// <summary> /// Attempts to resolve a type using specified options. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, ResolveOptions options) { return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options); } /// <summary> /// Attempts to resolve a type using default options and the supplied name. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, string name) { return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default); } /// <summary> /// Attempts to resolve a type using supplied options and name. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, string name, ResolveOptions options) { return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options); } /// <summary> /// Attempts to resolve a type using default options and the supplied constructor parameters. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="parameters">User specified constructor parameters</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, NamedParameterOverloads parameters) { return ResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default); } /// <summary> /// Attempts to resolve a type using specified options and the supplied constructor parameters. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options) { return ResolveInternal(new TypeRegistration(resolveType), parameters, options); } /// <summary> /// Attempts to resolve a type using default options and the supplied constructor parameters and name. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="name">Name of registration</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters) { return ResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default); } /// <summary> /// Attempts to resolve a named type using specified options and the supplied constructor parameters. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options) { return ResolveInternal(new TypeRegistration(resolveType, name), parameters, options); } /// <summary> /// Attempts to resolve a type using default options. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>() where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType)); } /// <summary> /// Attempts to resolve a type using specified options. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(ResolveOptions options) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), options); } /// <summary> /// Attempts to resolve a type using default options and the supplied name. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(string name) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), name); } /// <summary> /// Attempts to resolve a type using supplied options and name. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(string name, ResolveOptions options) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), name, options); } /// <summary> /// Attempts to resolve a type using default options and the supplied constructor parameters. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="parameters">User specified constructor parameters</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(NamedParameterOverloads parameters) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), parameters); } /// <summary> /// Attempts to resolve a type using specified options and the supplied constructor parameters. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), parameters, options); } /// <summary> /// Attempts to resolve a type using default options and the supplied constructor parameters and name. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="parameters">User specified constructor parameters</param> /// <param name="name">Name of registration</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(string name, NamedParameterOverloads parameters) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), name, parameters); } /// <summary> /// Attempts to resolve a named type using specified options and the supplied constructor parameters. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <returns>Instance of type</returns> /// <exception cref="TinyIoCResolutionException">Unable to resolve the type.</exception> public ResolveType Resolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options) where ResolveType : class { return (ResolveType)Resolve(typeof(ResolveType), name, parameters, options); } /// <summary> /// Attempts to predict whether a given type can be resolved with default options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType) { return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default); } /// <summary> /// Attempts to predict whether a given named type can be resolved with default options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <returns>Bool indicating whether the type can be resolved</returns> private bool CanResolve(Type resolveType, string name) { return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default); } /// <summary> /// Attempts to predict whether a given type can be resolved with the specified options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType, ResolveOptions options) { return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options); } /// <summary> /// Attempts to predict whether a given named type can be resolved with the specified options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType, string name, ResolveOptions options) { return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options); } /// <summary> /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="parameters">User supplied named parameter overloads</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType, NamedParameterOverloads parameters) { return CanResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default); } /// <summary> /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="parameters">User supplied named parameter overloads</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters) { return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default); } /// <summary> /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="parameters">User supplied named parameter overloads</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options) { return CanResolveInternal(new TypeRegistration(resolveType), parameters, options); } /// <summary> /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <param name="resolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="parameters">User supplied named parameter overloads</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options) { return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, options); } /// <summary> /// Attempts to predict whether a given type can be resolved with default options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>() where ResolveType : class { return CanResolve(typeof(ResolveType)); } /// <summary> /// Attempts to predict whether a given named type can be resolved with default options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(string name) where ResolveType : class { return CanResolve(typeof(ResolveType), name); } /// <summary> /// Attempts to predict whether a given type can be resolved with the specified options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(ResolveOptions options) where ResolveType : class { return CanResolve(typeof(ResolveType), options); } /// <summary> /// Attempts to predict whether a given named type can be resolved with the specified options. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(string name, ResolveOptions options) where ResolveType : class { return CanResolve(typeof(ResolveType), name, options); } /// <summary> /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="parameters">User supplied named parameter overloads</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(NamedParameterOverloads parameters) where ResolveType : class { return CanResolve(typeof(ResolveType), parameters); } /// <summary> /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="parameters">User supplied named parameter overloads</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(string name, NamedParameterOverloads parameters) where ResolveType : class { return CanResolve(typeof(ResolveType), name, parameters); } /// <summary> /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="parameters">User supplied named parameter overloads</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options) where ResolveType : class { return CanResolve(typeof(ResolveType), parameters, options); } /// <summary> /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options. /// /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="parameters">User supplied named parameter overloads</param> /// <param name="options">Resolution options</param> /// <returns>Bool indicating whether the type can be resolved</returns> public bool CanResolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options) where ResolveType : class { return CanResolve(typeof(ResolveType), name, parameters, options); } /// <summary> /// Attemps to resolve a type using the default options /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, out object resolvedType) { try { resolvedType = Resolve(resolveType); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the given options /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, ResolveOptions options, out object resolvedType) { try { resolvedType = Resolve(resolveType, options); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the default options and given name /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, string name, out object resolvedType) { try { resolvedType = Resolve(resolveType, name); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the given options and name /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, string name, ResolveOptions options, out object resolvedType) { try { resolvedType = Resolve(resolveType, name, options); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the default options and supplied constructor parameters /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, out object resolvedType) { try { resolvedType = Resolve(resolveType, parameters); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the default options and supplied name and constructor parameters /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, out object resolvedType) { try { resolvedType = Resolve(resolveType, name, parameters); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the supplied options and constructor parameters /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType) { try { resolvedType = Resolve(resolveType, parameters, options); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the supplied name, options and constructor parameters /// </summary> /// <param name="ResolveType">Type to resolve</param> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType) { try { resolvedType = Resolve(resolveType, name, parameters, options); return true; } catch (TinyIoCResolutionException) { resolvedType = null; return false; } } /// <summary> /// Attemps to resolve a type using the default options /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the given options /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(options); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the default options and given name /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(string name, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(name); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the given options and name /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(string name, ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(name, options); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the default options and supplied constructor parameters /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="parameters">User specified constructor parameters</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(NamedParameterOverloads parameters, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(parameters); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the default options and supplied name and constructor parameters /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(string name, NamedParameterOverloads parameters, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(name, parameters); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the supplied options and constructor parameters /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(parameters, options); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Attemps to resolve a type using the supplied name, options and constructor parameters /// </summary> /// <typeparam name="ResolveType">Type to resolve</typeparam> /// <param name="name">Name of registration</param> /// <param name="parameters">User specified constructor parameters</param> /// <param name="options">Resolution options</param> /// <param name="resolvedType">Resolved type or default if resolve fails</param> /// <returns>True if resolved sucessfully, false otherwise</returns> public bool TryResolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { try { resolvedType = Resolve<ResolveType>(name, parameters, options); return true; } catch (TinyIoCResolutionException) { resolvedType = default(ResolveType); return false; } } /// <summary> /// Returns all registrations of a type /// </summary> /// <param name="ResolveType">Type to resolveAll</param> /// <param name="includeUnnamed">Whether to include un-named (default) registrations</param> /// <returns>IEnumerable</returns> public IEnumerable<object> ResolveAll(Type resolveType, bool includeUnnamed) { return ResolveAllInternal(resolveType, includeUnnamed); } /// <summary> /// Returns all registrations of a type, both named and unnamed /// </summary> /// <param name="ResolveType">Type to resolveAll</param> /// <returns>IEnumerable</returns> public IEnumerable<object> ResolveAll(Type resolveType) { return ResolveAll(resolveType, false); } /// <summary> /// Returns all registrations of a type /// </summary> /// <typeparam name="ResolveType">Type to resolveAll</typeparam> /// <param name="includeUnnamed">Whether to include un-named (default) registrations</param> /// <returns>IEnumerable</returns> public IEnumerable<ResolveType> ResolveAll<ResolveType>(bool includeUnnamed) where ResolveType : class { return this.ResolveAll(typeof(ResolveType), includeUnnamed).Cast<ResolveType>(); } /// <summary> /// Returns all registrations of a type, both named and unnamed /// </summary> /// <typeparam name="ResolveType">Type to resolveAll</typeparam> /// <param name="includeUnnamed">Whether to include un-named (default) registrations</param> /// <returns>IEnumerable</returns> public IEnumerable<ResolveType> ResolveAll<ResolveType>() where ResolveType : class { return ResolveAll<ResolveType>(true); } /// <summary> /// Attempts to resolve all public property dependencies on the given object. /// </summary> /// <param name="input">Object to "build up"</param> public void BuildUp(object input) { BuildUpInternal(input, ResolveOptions.Default); } /// <summary> /// Attempts to resolve all public property dependencies on the given object using the given resolve options. /// </summary> /// <param name="input">Object to "build up"</param> /// <param name="resolveOptions">Resolve options to use</param> public void BuildUp(object input, ResolveOptions resolveOptions) { BuildUpInternal(input, resolveOptions); } #endregion #endregion #region Object Factories /// <summary> /// Provides custom lifetime management for ASP.Net per-request lifetimes etc. /// </summary> public interface ITinyIoCObjectLifetimeProvider { /// <summary> /// Gets the stored object if it exists, or null if not /// </summary> /// <returns>Object instance or null</returns> object GetObject(); /// <summary> /// Store the object /// </summary> /// <param name="value">Object to store</param> void SetObject(object value); /// <summary> /// Release the object /// </summary> void ReleaseObject(); } private abstract class ObjectFactoryBase { /// <summary> /// Whether to assume this factory sucessfully constructs its objects /// /// Generally set to true for delegate style factories as CanResolve cannot delve /// into the delegates they contain. /// </summary> public virtual bool AssumeConstruction { get { return false; } } /// <summary> /// The type the factory instantiates /// </summary> public abstract Type CreatesType { get; } /// <summary> /// Constructor to use, if specified /// </summary> public ConstructorInfo Constructor { get; protected set; } /// <summary> /// Create the type /// </summary> /// <param name="requestedType">Type user requested to be resolved</param> /// <param name="container">Container that requested the creation</param> /// <param name="parameters">Any user parameters passed</param> /// <param name="options"></param> /// <returns></returns> public abstract object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options); public virtual ObjectFactoryBase SingletonVariant { get { throw new TinyIoCRegistrationException(this.GetType(), "singleton"); } } public virtual ObjectFactoryBase MultiInstanceVariant { get { throw new TinyIoCRegistrationException(this.GetType(), "multi-instance"); } } public virtual ObjectFactoryBase StrongReferenceVariant { get { throw new TinyIoCRegistrationException(this.GetType(), "strong reference"); } } public virtual ObjectFactoryBase WeakReferenceVariant { get { throw new TinyIoCRegistrationException(this.GetType(), "weak reference"); } } public virtual ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { throw new TinyIoCRegistrationException(this.GetType(), errorString); } public virtual void SetConstructor(ConstructorInfo constructor) { Constructor = constructor; } public virtual ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child) { return this; } } /// <summary> /// IObjectFactory that creates new instances of types for each resolution /// </summary> private class MultiInstanceFactory : ObjectFactoryBase { private readonly Type registerType; private readonly Type registerImplementation; public override Type CreatesType { get { return this.registerImplementation; } } public MultiInstanceFactory(Type registerType, Type registerImplementation) { if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); this.registerType = registerType; this.registerImplementation = registerImplementation; } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { try { return container.ConstructType(requestedType, this.registerImplementation, Constructor, parameters, options); } catch (TinyIoCResolutionException ex) { throw new TinyIoCResolutionException(this.registerType, ex); } } public override ObjectFactoryBase SingletonVariant { get { return new SingletonFactory(this.registerType, this.registerImplementation); } } public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString); } public override ObjectFactoryBase MultiInstanceVariant { get { return this; } } } /// <summary> /// IObjectFactory that invokes a specified delegate to construct the object /// </summary> private class DelegateFactory : ObjectFactoryBase { private readonly Type registerType; private Func<TinyIoCContainer, NamedParameterOverloads, object> _factory; public override bool AssumeConstruction { get { return true; } } public override Type CreatesType { get { return this.registerType; } } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { try { return _factory.Invoke(container, parameters); } catch (Exception ex) { throw new TinyIoCResolutionException(this.registerType, ex); } } public DelegateFactory( Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory) { if (factory == null) throw new ArgumentNullException("factory"); _factory = factory; this.registerType = registerType; } public override ObjectFactoryBase WeakReferenceVariant { get { return new WeakDelegateFactory(this.registerType, _factory); } } public override ObjectFactoryBase StrongReferenceVariant { get { return this; } } public override void SetConstructor(ConstructorInfo constructor) { throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for delegate factory registrations"); } } /// <summary> /// IObjectFactory that invokes a specified delegate to construct the object /// Holds the delegate using a weak reference /// </summary> private class WeakDelegateFactory : ObjectFactoryBase { private readonly Type registerType; private WeakReference _factory; public override bool AssumeConstruction { get { return true; } } public override Type CreatesType { get { return this.registerType; } } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { var factory = _factory.Target as Func<TinyIoCContainer, NamedParameterOverloads, object>; if (factory == null) throw new TinyIoCWeakReferenceException(this.registerType); try { return factory.Invoke(container, parameters); } catch (Exception ex) { throw new TinyIoCResolutionException(this.registerType, ex); } } public WeakDelegateFactory(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory) { if (factory == null) throw new ArgumentNullException("factory"); _factory = new WeakReference(factory); this.registerType = registerType; } public override ObjectFactoryBase StrongReferenceVariant { get { var factory = _factory.Target as Func<TinyIoCContainer, NamedParameterOverloads, object>; if (factory == null) throw new TinyIoCWeakReferenceException(this.registerType); return new DelegateFactory(this.registerType, factory); } } public override ObjectFactoryBase WeakReferenceVariant { get { return this; } } public override void SetConstructor(ConstructorInfo constructor) { throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for delegate factory registrations"); } } /// <summary> /// Stores an particular instance to return for a type /// </summary> private class InstanceFactory : ObjectFactoryBase, IDisposable { private readonly Type registerType; private readonly Type registerImplementation; private object _instance; public override bool AssumeConstruction { get { return true; } } public InstanceFactory(Type registerType, Type registerImplementation, object instance) { if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "InstanceFactory"); this.registerType = registerType; this.registerImplementation = registerImplementation; _instance = instance; } public override Type CreatesType { get { return this.registerImplementation; } } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { return _instance; } public override ObjectFactoryBase MultiInstanceVariant { get { return new MultiInstanceFactory(this.registerType, this.registerImplementation); } } public override ObjectFactoryBase WeakReferenceVariant { get { return new WeakInstanceFactory(this.registerType, this.registerImplementation, this._instance); } } public override ObjectFactoryBase StrongReferenceVariant { get { return this; } } public override void SetConstructor(ConstructorInfo constructor) { throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for instance factory registrations"); } public void Dispose() { var disposable = _instance as IDisposable; if (disposable != null) disposable.Dispose(); } } /// <summary> /// Stores an particular instance to return for a type /// /// Stores the instance with a weak reference /// </summary> private class WeakInstanceFactory : ObjectFactoryBase, IDisposable { private readonly Type registerType; private readonly Type registerImplementation; private readonly WeakReference _instance; public WeakInstanceFactory(Type registerType, Type registerImplementation, object instance) { if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "WeakInstanceFactory"); this.registerType = registerType; this.registerImplementation = registerImplementation; _instance = new WeakReference(instance); } public override Type CreatesType { get { return this.registerImplementation; } } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { var instance = _instance.Target; if (instance == null) throw new TinyIoCWeakReferenceException(this.registerType); return instance; } public override ObjectFactoryBase MultiInstanceVariant { get { return new MultiInstanceFactory(this.registerType, this.registerImplementation); } } public override ObjectFactoryBase WeakReferenceVariant { get { return this; } } public override ObjectFactoryBase StrongReferenceVariant { get { var instance = _instance.Target; if (instance == null) throw new TinyIoCWeakReferenceException(this.registerType); return new InstanceFactory(this.registerType, this.registerImplementation, instance); } } public override void SetConstructor(ConstructorInfo constructor) { throw new TinyIoCConstructorResolutionException("Constructor selection is not possible for instance factory registrations"); } public void Dispose() { var disposable = _instance.Target as IDisposable; if (disposable != null) disposable.Dispose(); } } /// <summary> /// A factory that lazy instantiates a type and always returns the same instance /// </summary> private class SingletonFactory : ObjectFactoryBase, IDisposable { private readonly Type registerType; private readonly Type registerImplementation; private readonly object SingletonLock = new object(); private object _Current; public SingletonFactory(Type registerType, Type registerImplementation) { if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); this.registerType = registerType; this.registerImplementation = registerImplementation; } public override Type CreatesType { get { return this.registerImplementation; } } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { if (parameters.Count != 0) throw new ArgumentException("Cannot specify parameters for singleton types"); lock (SingletonLock) if (_Current == null) _Current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options); return _Current; } public override ObjectFactoryBase SingletonVariant { get { return this; } } public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString); } public override ObjectFactoryBase MultiInstanceVariant { get { return new MultiInstanceFactory(this.registerType, this.registerImplementation); } } public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child) { // We make sure that the singleton is constructed before the child container takes the factory. // Otherwise the results would vary depending on whether or not the parent container had resolved // the type before the child container does. GetObject(type, parent, NamedParameterOverloads.Default, ResolveOptions.Default); return this; } public void Dispose() { if (this._Current == null) return; var disposable = this._Current as IDisposable; if (disposable != null) disposable.Dispose(); } } /// <summary> /// A factory that offloads lifetime to an external lifetime provider /// </summary> private class CustomObjectLifetimeFactory : ObjectFactoryBase, IDisposable { private readonly object SingletonLock = new object(); private readonly Type registerType; private readonly Type registerImplementation; private readonly ITinyIoCObjectLifetimeProvider _LifetimeProvider; public CustomObjectLifetimeFactory(Type registerType, Type registerImplementation, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorMessage) { if (lifetimeProvider == null) throw new ArgumentNullException("lifetimeProvider", "lifetimeProvider is null."); if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage); this.registerType = registerType; this.registerImplementation = registerImplementation; _LifetimeProvider = lifetimeProvider; } public override Type CreatesType { get { return this.registerImplementation; } } public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options) { object current; lock (SingletonLock) { current = _LifetimeProvider.GetObject(); if (current == null) { current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options); _LifetimeProvider.SetObject(current); } } return current; } public override ObjectFactoryBase SingletonVariant { get { _LifetimeProvider.ReleaseObject(); return new SingletonFactory(this.registerType, this.registerImplementation); } } public override ObjectFactoryBase MultiInstanceVariant { get { _LifetimeProvider.ReleaseObject(); return new MultiInstanceFactory(this.registerType, this.registerImplementation); } } public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString) { _LifetimeProvider.ReleaseObject(); return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString); } public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child) { // We make sure that the singleton is constructed before the child container takes the factory. // Otherwise the results would vary depending on whether or not the parent container had resolved // the type before the child container does. GetObject(type, parent, NamedParameterOverloads.Default, ResolveOptions.Default); return this; } public void Dispose() { _LifetimeProvider.ReleaseObject(); } } #endregion #region Singleton Container private static readonly TinyIoCContainer _Current = new TinyIoCContainer(); static TinyIoCContainer() { } /// <summary> /// Lazy created Singleton instance of the container for simple scenarios /// </summary> public static TinyIoCContainer Current { get { return _Current; } } #endregion #region Type Registrations public sealed class TypeRegistration { private int _hashCode; public Type Type { get; private set; } public string Name { get; private set; } public TypeRegistration(Type type) : this(type, string.Empty) { } public TypeRegistration(Type type, string name) { Type = type; Name = name; _hashCode = String.Concat(Type.FullName, "|", Name).GetHashCode(); } public override bool Equals(object obj) { var typeRegistration = obj as TypeRegistration; if (typeRegistration == null) return false; if (Type != typeRegistration.Type) return false; if (String.Compare(Name, typeRegistration.Name, StringComparison.Ordinal) != 0) return false; return true; } public override int GetHashCode() { return _hashCode; } } private readonly SafeDictionary<TypeRegistration, ObjectFactoryBase> _RegisteredTypes; #if COMPILED_EXPRESSIONS private delegate object ObjectConstructor(params object[] parameters); private static readonly SafeDictionary<ConstructorInfo, ObjectConstructor> _ObjectConstructorCache = new SafeDictionary<ConstructorInfo, ObjectConstructor>(); #endif #endregion #region Constructors public TinyIoCContainer() { _RegisteredTypes = new SafeDictionary<TypeRegistration, ObjectFactoryBase>(); RegisterDefaultTypes(); } TinyIoCContainer _Parent; private TinyIoCContainer(TinyIoCContainer parent) : this() { _Parent = parent; } #endregion #region Internal Methods private readonly object _AutoRegisterLock = new object(); private void AutoRegisterInternal(IEnumerable<Assembly> assemblies, bool ignoreDuplicateImplementations, Func<Type, bool> registrationPredicate) { lock (_AutoRegisterLock) { var types = assemblies.SelectMany(a => a.SafeGetTypes()).Where(t => !IsIgnoredType(t, registrationPredicate)).ToList(); var concreteTypes = from type in types where (type.IsClass() == true) && (type.IsAbstract() == false) && (type != this.GetType() && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition())) select type; foreach (var type in concreteTypes) { try { RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, type)); } catch (MethodAccessException) { // Ignore methods we can't access - added for Silverlight } } var abstractInterfaceTypes = from type in types where ((type.IsInterface() == true || type.IsAbstract() == true) && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition())) select type; foreach (var type in abstractInterfaceTypes) { var implementations = from implementationType in concreteTypes where implementationType.GetInterfaces().Contains(type) || implementationType.BaseType() == type select implementationType; if (!ignoreDuplicateImplementations && implementations.Count() > 1) throw new TinyIoCAutoRegistrationException(type, implementations); var firstImplementation = implementations.FirstOrDefault(); if (firstImplementation != null) { try { RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, firstImplementation)); } catch (MethodAccessException) { // Ignore methods we can't access - added for Silverlight } } } } } private bool IsIgnoredAssembly(Assembly assembly) { // TODO - find a better way to remove "system" assemblies from the auto registration var ignoreChecks = new List<Func<Assembly, bool>>() { asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal), asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal), asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal), asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal), asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal), asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal), asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal), }; foreach (var check in ignoreChecks) { if (check(assembly)) return true; } return false; } private bool IsIgnoredType(Type type, Func<Type, bool> registrationPredicate) { // TODO - find a better way to remove "system" types from the auto registration var ignoreChecks = new List<Func<Type, bool>>() { t => t.FullName.StartsWith("System.", StringComparison.Ordinal), t => t.FullName.StartsWith("Microsoft.", StringComparison.Ordinal), t => t.IsPrimitive(), t => (t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length == 0) && !(t.IsInterface() || t.IsAbstract()), }; if (registrationPredicate != null) { ignoreChecks.Add(t => !registrationPredicate(t)); } foreach (var check in ignoreChecks) { if (check(type)) return true; } return false; } private void RegisterDefaultTypes() { Register<TinyIoCContainer>(this); #if TINYMESSENGER // Only register the TinyMessenger singleton if we are the root container if (_Parent == null) Register<TinyMessenger.ITinyMessengerHub, TinyMessenger.TinyMessengerHub>(); #endif } private ObjectFactoryBase GetCurrentFactory(TypeRegistration registration) { ObjectFactoryBase current = null; _RegisteredTypes.TryGetValue(registration, out current); return current; } private RegisterOptions RegisterInternal(Type registerType, string name, ObjectFactoryBase factory) { var typeRegistration = new TypeRegistration(registerType, name); return AddUpdateRegistration(typeRegistration, factory); } private RegisterOptions AddUpdateRegistration(TypeRegistration typeRegistration, ObjectFactoryBase factory) { _RegisteredTypes[typeRegistration] = factory; return new RegisterOptions(this, typeRegistration); } private void RemoveRegistration(TypeRegistration typeRegistration) { _RegisteredTypes.Remove(typeRegistration); } private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) { if (registerType.IsInterface() || registerType.IsAbstract()) return new SingletonFactory(registerType, registerImplementation); return new MultiInstanceFactory(registerType, registerImplementation); } private bool CanResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options) { if (parameters == null) throw new ArgumentNullException("parameters"); Type checkType = registration.Type; string name = registration.Name; ObjectFactoryBase factory; if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType, name), out factory)) { if (factory.AssumeConstruction) return true; if (factory.Constructor == null) return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false; else return CanConstruct(factory.Constructor, parameters, options); } // Fail if requesting named resolution and settings set to fail if unresolved // Or bubble up if we have a parent if (!String.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail) return (_Parent != null) ? _Parent.CanResolveInternal(registration, parameters, options) : false; // Attemped unnamed fallback container resolution if relevant and requested if (!String.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.AttemptUnnamedResolution) { if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType), out factory)) { if (factory.AssumeConstruction) return true; return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false; } } // Check if type is an automatic lazy factory request if (IsAutomaticLazyFactoryRequest(checkType)) return true; // Check if type is an IEnumerable<ResolveType> if (IsIEnumerableRequest(registration.Type)) return true; // Attempt unregistered construction if possible and requested // If we cant', bubble if we have a parent if ((options.UnregisteredResolutionAction == UnregisteredResolutionActions.AttemptResolve) || (checkType.IsGenericType() && options.UnregisteredResolutionAction == UnregisteredResolutionActions.GenericsOnly)) return (GetBestConstructor(checkType, parameters, options) != null) ? true : (_Parent != null) ? _Parent.CanResolveInternal(registration, parameters, options) : false; // Bubble resolution up the container tree if we have a parent if (_Parent != null) return _Parent.CanResolveInternal(registration, parameters, options); return false; } private bool IsIEnumerableRequest(Type type) { if (!type.IsGenericType()) return false; Type genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IEnumerable<>)) return true; return false; } private bool IsAutomaticLazyFactoryRequest(Type type) { if (!type.IsGenericType()) return false; Type genericType = type.GetGenericTypeDefinition(); // Just a func if (genericType == typeof(Func<>)) return true; // 2 parameter func with string as first parameter (name) if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))) return true; // 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters) if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<String, object>))) return true; return false; } private ObjectFactoryBase GetParentObjectFactory(TypeRegistration registration) { if (_Parent == null) return null; ObjectFactoryBase factory; if (_Parent._RegisteredTypes.TryGetValue(registration, out factory)) { return factory.GetFactoryForChildContainer(registration.Type, _Parent, this); } return _Parent.GetParentObjectFactory(registration); } private object ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options) { ObjectFactoryBase factory; // Attempt container resolution if (_RegisteredTypes.TryGetValue(registration, out factory)) { try { return factory.GetObject(registration.Type, this, parameters, options); } catch (TinyIoCResolutionException) { throw; } catch (Exception ex) { throw new TinyIoCResolutionException(registration.Type, ex); } } // Attempt container resolution of open generic if (registration.Type.IsGenericType()) { var openTypeRegistration = new TypeRegistration(registration.Type.GetGenericTypeDefinition(), registration.Name); if (_RegisteredTypes.TryGetValue(openTypeRegistration, out factory)) { try { return factory.GetObject(registration.Type, this, parameters, options); } catch (TinyIoCResolutionException) { throw; } catch (Exception ex) { throw new TinyIoCResolutionException(registration.Type, ex); } } } // Attempt to get a factory from parent if we can var bubbledObjectFactory = GetParentObjectFactory(registration); if (bubbledObjectFactory != null) { try { return bubbledObjectFactory.GetObject(registration.Type, this, parameters, options); } catch (TinyIoCResolutionException) { throw; } catch (Exception ex) { throw new TinyIoCResolutionException(registration.Type, ex); } } // Fail if requesting named resolution and settings set to fail if unresolved if (!String.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail) throw new TinyIoCResolutionException(registration.Type); // Attemped unnamed fallback container resolution if relevant and requested if (!String.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.AttemptUnnamedResolution) { if (_RegisteredTypes.TryGetValue(new TypeRegistration(registration.Type, string.Empty), out factory)) { try { return factory.GetObject(registration.Type, this, parameters, options); } catch (TinyIoCResolutionException) { throw; } catch (Exception ex) { throw new TinyIoCResolutionException(registration.Type, ex); } } } #if COMPILED_EXPRESSIONS // Attempt to construct an automatic lazy factory if possible if (IsAutomaticLazyFactoryRequest(registration.Type)) return GetLazyAutomaticFactoryRequest(registration.Type); #endif if (IsIEnumerableRequest(registration.Type)) return GetIEnumerableRequest(registration.Type); // Attempt unregistered construction if possible and requested if ((options.UnregisteredResolutionAction == UnregisteredResolutionActions.AttemptResolve) || (registration.Type.IsGenericType() && options.UnregisteredResolutionAction == UnregisteredResolutionActions.GenericsOnly)) { if (!registration.Type.IsAbstract() && !registration.Type.IsInterface()) return ConstructType(null, registration.Type, parameters, options); } // Unable to resolve - throw throw new TinyIoCResolutionException(registration.Type); } #if COMPILED_EXPRESSIONS private object GetLazyAutomaticFactoryRequest(Type type) { if (!type.IsGenericType()) return null; Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); // Just a func if (genericType == typeof(Func<>)) { Type returnType = genericArguments[0]; MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { }); resolveMethod = resolveMethod.MakeGenericMethod(returnType); var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod); var resolveLambda = Expression.Lambda(resolveCall).Compile(); return resolveLambda; } // 2 parameter func with string as first parameter (name) if ((genericType == typeof(Func<,>)) && (genericArguments[0] == typeof(string))) { Type returnType = genericArguments[1]; MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(String) }); resolveMethod = resolveMethod.MakeGenericMethod(returnType); ParameterExpression[] resolveParameters = new ParameterExpression[] { Expression.Parameter(typeof(String), "name") }; var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, resolveParameters); var resolveLambda = Expression.Lambda(resolveCall, resolveParameters).Compile(); return resolveLambda; } // 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters) if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<string, object>))) { Type returnType = genericArguments[2]; var name = Expression.Parameter(typeof(string), "name"); var parameters = Expression.Parameter(typeof(IDictionary<string, object>), "parameters"); MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(String), typeof(NamedParameterOverloads) }); resolveMethod = resolveMethod.MakeGenericMethod(returnType); var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, name, Expression.Call(typeof(NamedParameterOverloads), "FromIDictionary", null, parameters)); var resolveLambda = Expression.Lambda(resolveCall, name, parameters).Compile(); return resolveLambda; } throw new TinyIoCResolutionException(type); } #endif private object GetIEnumerableRequest(Type type) { var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) }); return genericResolveAllMethod.Invoke(this, new object[] { false }); } private bool CanConstruct(ConstructorInfo ctor, NamedParameterOverloads parameters, ResolveOptions options) { if (parameters == null) throw new ArgumentNullException("parameters"); foreach (var parameter in ctor.GetParameters()) { if (string.IsNullOrEmpty(parameter.Name)) return false; var isParameterOverload = parameters.ContainsKey(parameter.Name); if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) return false; if (!isParameterOverload && !CanResolveInternal(new TypeRegistration(parameter.ParameterType), NamedParameterOverloads.Default, options)) return false; } return true; } private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads parameters, ResolveOptions options) { if (parameters == null) throw new ArgumentNullException("parameters"); if (type.IsValueType()) return null; // Get constructors in reverse order based on the number of parameters // i.e. be as "greedy" as possible so we satify the most amount of dependencies possible var ctors = this.GetTypeConstructors(type); foreach (var ctor in ctors) { if (this.CanConstruct(ctor, parameters, options)) return ctor; } return null; } private IEnumerable<ConstructorInfo> GetTypeConstructors(Type type) { return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count()); } private object ConstructType(Type requestedType, Type implementationType, ResolveOptions options) { return ConstructType(requestedType, implementationType, null, NamedParameterOverloads.Default, options); } private object ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, ResolveOptions options) { return ConstructType(requestedType, implementationType, constructor, NamedParameterOverloads.Default, options); } private object ConstructType(Type requestedType, Type implementationType, NamedParameterOverloads parameters, ResolveOptions options) { return ConstructType(requestedType, implementationType, null, parameters, options); } private object ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options) { var typeToConstruct = implementationType; if (implementationType.IsGenericTypeDefinition()) { if (requestedType == null || !requestedType.IsGenericType() || !requestedType.GetGenericArguments().Any()) throw new TinyIoCResolutionException(typeToConstruct); typeToConstruct = typeToConstruct.MakeGenericType(requestedType.GetGenericArguments()); } if (constructor == null) { // Try and get the best constructor that we can construct // if we can't construct any then get the constructor // with the least number of parameters so we can throw a meaningful // resolve exception constructor = GetBestConstructor(typeToConstruct, parameters, options) ?? GetTypeConstructors(typeToConstruct).LastOrDefault(); } if (constructor == null) throw new TinyIoCResolutionException(typeToConstruct); var ctorParams = constructor.GetParameters(); object[] args = new object[ctorParams.Count()]; for (int parameterIndex = 0; parameterIndex < ctorParams.Count(); parameterIndex++) { var currentParam = ctorParams[parameterIndex]; try { args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? parameters[currentParam.Name] : ResolveInternal( new TypeRegistration(currentParam.ParameterType), NamedParameterOverloads.Default, options); } catch (TinyIoCResolutionException ex) { // If a constructor parameter can't be resolved // it will throw, so wrap it and throw that this can't // be resolved. throw new TinyIoCResolutionException(typeToConstruct, ex); } catch (Exception ex) { throw new TinyIoCResolutionException(typeToConstruct, ex); } } try { #if COMPILED_EXPRESSIONS var constructionDelegate = CreateObjectConstructionDelegateWithCache(constructor); return constructionDelegate.Invoke(args); #else return constructor.Invoke(args); #endif } catch (Exception ex) { throw new TinyIoCResolutionException(typeToConstruct, ex); } } #if COMPILED_EXPRESSIONS private static ObjectConstructor CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor) { ObjectConstructor objectConstructor; if (_ObjectConstructorCache.TryGetValue(constructor, out objectConstructor)) return objectConstructor; // We could lock the cache here, but there's no real side // effect to two threads creating the same ObjectConstructor // at the same time, compared to the cost of a lock for // every creation. var constructorParams = constructor.GetParameters(); var lambdaParams = Expression.Parameter(typeof(object[]), "parameters"); var newParams = new Expression[constructorParams.Length]; for (int i = 0; i < constructorParams.Length; i++) { var paramsParameter = Expression.ArrayIndex(lambdaParams, Expression.Constant(i)); newParams[i] = Expression.Convert(paramsParameter, constructorParams[i].ParameterType); } var newExpression = Expression.New(constructor, newParams); var constructionLambda = Expression.Lambda(typeof(ObjectConstructor), newExpression, lambdaParams); objectConstructor = (ObjectConstructor)constructionLambda.Compile(); _ObjectConstructorCache[constructor] = objectConstructor; return objectConstructor; } #endif private void BuildUpInternal(object input, ResolveOptions resolveOptions) { var properties = from property in input.GetType().GetProperties() where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType() select property; foreach (var property in properties) { if (property.GetValue(input, null) == null) { try { property.SetValue(input, ResolveInternal(new TypeRegistration(property.PropertyType), NamedParameterOverloads.Default, resolveOptions), null); } catch (TinyIoCResolutionException) { // Catch any resolution errors and ignore them } } } } private IEnumerable<TypeRegistration> GetParentRegistrationsForType(Type resolveType) { if (_Parent == null) return new TypeRegistration[] { }; var registrations = _Parent._RegisteredTypes.Keys.Where(tr => tr.Type == resolveType); return registrations.Concat(_Parent.GetParentRegistrationsForType(resolveType)); } private IEnumerable<object> ResolveAllInternal(Type resolveType, bool includeUnnamed) { var registrations = _RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(GetParentRegistrationsForType(resolveType)); if (!includeUnnamed) registrations = registrations.Where(tr => tr.Name != string.Empty); return registrations.Select(registration => this.ResolveInternal(registration, NamedParameterOverloads.Default, ResolveOptions.Default)); } private static bool IsValidAssignment(Type registerType, Type registerImplementation) { if (!registerType.IsGenericTypeDefinition()) { if (!registerType.IsAssignableFrom(registerImplementation)) return false; } else { if (registerType.IsInterface()) { if(!registerImplementation.GetInterfaces().Any(t => t.Name == registerType.Name)) return false; } else if (registerType.IsAbstract() && registerImplementation.BaseType() != registerType) { return false; } } return true; } #endregion #region IDisposable Members bool disposed = false; public void Dispose() { if (!disposed) { disposed = true; _RegisteredTypes.Dispose(); GC.SuppressFinalize(this); } } #endregion } } // reverse shim for WinRT SR changes... namespace System.Reflection { public static class ReverseTypeExtender { public static bool IsClass(this Type type) { return type.IsClass; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsPrimitive(this Type type) { return type.IsPrimitive; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericParameter(this Type type) { return type.IsGenericParameter; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } } }
chrisriesgo/making-mobile-click
Demo.IoC/TinyIoC.cs
C#
mit
124,512
class AddStateToSites < ActiveRecord::Migration def self.up add_column :sites, :state, :string end def self.down remove_column :sites, :state end end
techvalidate/portrait
db/migrate/20090619225703_add_state_to_sites.rb
Ruby
mit
167
version https://git-lfs.github.com/spec/v1 oid sha256:8b2c75ae8236614319bbfe99cee3dba6fa2183434deff5a3dd2f69625589c74a size 391
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.15.0/arraylist-filter/arraylist-filter-min.js
JavaScript
mit
128
package org.luaj.vm2; import java.io.ByteArrayOutputStream; import java.io.PrintStream; /** * Debug helper class to pretty-print lua bytecodes. * @see Prototype * @see LuaClosure */ public class Print extends Lua { /** opcode names */ private static final String STRING_FOR_NULL = "null"; private static final String[] OPNAMES = { "MOVE", "LOADK", "LOADBOOL", "LOADNIL", "GETUPVAL", "GETGLOBAL", "GETTABLE", "SETGLOBAL", "SETUPVAL", "SETTABLE", "NEWTABLE", "SELF", "ADD", "SUB", "MUL", "DIV", "MOD", "POW", "UNM", "NOT", "LEN", "CONCAT", "JMP", "EQ", "LT", "LE", "TEST", "TESTSET", "CALL", "TAILCALL", "RETURN", "FORLOOP", "FORPREP", "TFORLOOP", "SETLIST", "CLOSE", "CLOSURE", "VARARG", }; static void printString(PrintStream ps, LuaString s) { ps.print('"'); for(int i = 0, n = s._length; i < n; i++) { int c = s._bytes[s._offset + i]; if(c >= ' ' && c <= '~' && c != '\"' && c != '\\') ps.print((char)c); else { switch(c) { case '"': ps.print("\\\""); break; case '\\': ps.print("\\\\"); break; case 0x0007: /* bell */ ps.print("\\a"); break; case '\b': /* backspace */ ps.print("\\b"); break; case '\f': /* form feed */ ps.print("\\f"); break; case '\t': /* tab */ ps.print("\\t"); break; case '\r': /* carriage return */ ps.print("\\r"); break; case '\n': /* newline */ ps.print("\\n"); break; case 0x000B: /* vertical tab */ ps.print("\\v"); break; default: ps.print('\\'); ps.print(Integer.toString(1000 + 0xff & c).substring(1)); break; } } } ps.print('"'); } static void printValue(PrintStream ps, LuaValue v) { switch(v.type()) { case LuaValue.TSTRING: printString(ps, (LuaString)v); break; default: ps.print(v.tojstring()); } } static void printConstant(PrintStream ps, Prototype f, int i) { printValue(ps, f.k[i]); } /** * Print the code in a prototype * @param f the {@link Prototype} */ public static void printCode(PrintStream ps, Prototype f) { int[] code = f.code; int pc, n = code.length; for(pc = 0; pc < n; pc++) { printOpCode(ps, f, pc); ps.println(); } } /** * Print an opcode in a prototype * @param ps the {@link PrintStream} to print to * @param f the {@link Prototype} * @param pc the program counter to look up and print */ public static void printOpCode(PrintStream ps, Prototype f, int pc) { int[] code = f.code; int i = code[pc]; int o = GET_OPCODE(i); int a = GETARG_A(i); int b = GETARG_B(i); int c = GETARG_C(i); int bx = GETARG_Bx(i); int sbx = GETARG_sBx(i); int line = getline(f, pc); ps.print(" " + (pc + 1) + " "); if(line > 0) ps.print("[" + line + "] "); else ps.print("[-] "); ps.print(OPNAMES[o] + " "); switch(getOpMode(o)) { case iABC: ps.print(a); if(getBMode(o) != OpArgN) ps.print(" " + (ISK(b) ? (-1 - INDEXK(b)) : b)); if(getCMode(o) != OpArgN) ps.print(" " + (ISK(c) ? (-1 - INDEXK(c)) : c)); break; case iABx: if(getBMode(o) == OpArgK) { ps.print(a + " " + (-1 - bx)); } else { ps.print(a + " " + (bx)); } break; case iAsBx: if(o == OP_JMP) ps.print(sbx); else ps.print(a + " " + sbx); break; } switch(o) { case OP_LOADK: ps.print(" ; "); printConstant(ps, f, bx); break; case OP_GETUPVAL: case OP_SETUPVAL: ps.print(" ; "); if(f.upvalues.length > b) printValue(ps, f.upvalues[b]); else ps.print("-"); break; case OP_GETGLOBAL: case OP_SETGLOBAL: ps.print(" ; "); printConstant(ps, f, bx); break; case OP_GETTABLE: case OP_SELF: if(ISK(c)) { ps.print(" ; "); printConstant(ps, f, INDEXK(c)); } break; case OP_SETTABLE: case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_POW: case OP_EQ: case OP_LT: case OP_LE: if(ISK(b) || ISK(c)) { ps.print(" ; "); if(ISK(b)) printConstant(ps, f, INDEXK(b)); else ps.print("-"); ps.print(" "); if(ISK(c)) printConstant(ps, f, INDEXK(c)); else ps.print("-"); } break; case OP_JMP: case OP_FORLOOP: case OP_FORPREP: ps.print(" ; to " + (sbx + pc + 2)); break; case OP_CLOSURE: ps.print(" ; " + f.p[bx].getClass().getName()); break; case OP_SETLIST: if(c == 0) ps.print(" ; " + code[++pc]); else ps.print(" ; " + c); break; case OP_VARARG: ps.print(" ; is_vararg=" + f.is_vararg); break; default: break; } } private static int getline(Prototype f, int pc) { return pc > 0 && f.lineinfo != null && pc < f.lineinfo.length ? f.lineinfo[pc] : -1; } static void printHeader(PrintStream ps, Prototype f) { String s = String.valueOf(f.source); if(s.startsWith("@") || s.startsWith("=")) s = s.substring(1); else if("\033Lua".equals(s)) s = "(bstring)"; else s = "(string)"; String a = (f.linedefined == 0) ? "main" : "function"; ps.print("\n%" + a + " <" + s + ":" + f.linedefined + "," + f.lastlinedefined + "> (" + f.code.length + " instructions, " + f.code.length * 4 + " bytes at " + id() + ")\n"); ps.print(f.numparams + " param, " + f.maxstacksize + " slot, " + f.upvalues.length + " upvalue, "); ps.print(f.locvars.length + " local, " + f.k.length + " constant, " + f.p.length + " function\n"); } static void printConstants(PrintStream ps, Prototype f) { int i, n = f.k.length; ps.print("constants (" + n + ") for " + id() + ":\n"); for(i = 0; i < n; i++) { ps.print(" " + (i + 1) + " "); printValue(ps, f.k[i]); ps.print("\n"); } } static void printLocals(PrintStream ps, Prototype f) { int i, n = f.locvars.length; ps.print("locals (" + n + ") for " + id() + ":\n"); for(i = 0; i < n; i++) { ps.println(" " + i + " " + f.locvars[i]._varname + " " + (f.locvars[i]._startpc + 1) + " " + (f.locvars[i]._endpc + 1)); } } static void printUpValues(PrintStream ps, Prototype f) { int i, n = f.upvalues.length; ps.print("upvalues (" + n + ") for " + id() + ":\n"); for(i = 0; i < n; i++) { ps.print(" " + i + " " + f.upvalues[i] + "\n"); } } public static void print(PrintStream ps, Prototype p) { printFunction(ps, p, true); } public static void printFunction(PrintStream ps, Prototype f, boolean full) { int i, n = f.p.length; printHeader(ps, f); printCode(ps, f); if(full) { printConstants(ps, f); printLocals(ps, f); printUpValues(ps, f); } for(i = 0; i < n; i++) printFunction(ps, f.p[i], full); } private static void format(PrintStream ps, String s, int maxcols) { int n = s.length(); if(n > maxcols) ps.print(s.substring(0, maxcols)); else { ps.print(s); for(int i = maxcols - n; --i >= 0;) ps.print(' '); } } private static String id() { return "Proto"; } /** * Print the state of a {@link LuaClosure} that is being executed * @param cl the {@link LuaClosure} * @param pc the program counter * @param stack the stack of {@link LuaValue} * @param top the top of the stack * @param varargs any {@link Varargs} value that may apply */ public static void printState(LuaClosure cl, int pc, LuaValue[] stack, int top, Varargs varargs) { // print opcode into buffer ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); printOpCode(ps, cl._p, pc); ps.flush(); ps.close(); ps = System.out; format(ps, baos.toString(), 50); // print stack ps.print('['); for(int i = 0; i < stack.length; i++) { LuaValue v = stack[i]; if(v == null) ps.print(STRING_FOR_NULL); else switch(v.type()) { case LuaValue.TSTRING: LuaString s = v.checkstring(); ps.print(s.length() < 48 ? s.tojstring() : s.substring(0, 32).tojstring() + "...+" + (s.length() - 32) + "b"); break; case LuaValue.TFUNCTION: ps.print((v instanceof LuaClosure) ? ((LuaClosure)v)._p.toString() : v.tojstring()); break; case LuaValue.TUSERDATA: Object o = v.touserdata(); if(o != null) { String n = o.getClass().getName(); n = n.substring(n.lastIndexOf('.') + 1); ps.print(n + ": " + Integer.toHexString(o.hashCode())); } else { ps.print(v.toString()); } break; default: ps.print(v.tojstring()); } if(i + 1 == top) ps.print(']'); ps.print(" | "); } ps.print(varargs); ps.println(); } }
dwing4g/luaj
src/org/luaj/vm2/Print.java
Java
mit
10,612
/* * Copyright (c) 2009 WiQuery team * * 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. */ package org.odlabs.wiquery.ui.resizable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Panel; import org.junit.Before; import org.junit.Test; import org.odlabs.wiquery.core.options.LiteralOption; import org.odlabs.wiquery.tester.WiQueryTestCase; import org.odlabs.wiquery.ui.DivTestPanel; import org.odlabs.wiquery.ui.resizable.ResizableContainment.ElementEnum; /** * Test on {@link ResizableBehavior} * * @author Julien Roche */ public class ResizableBehaviorTestCase extends WiQueryTestCase { // Properties private ResizableBehavior resizableBehavior; @Override @Before public void setUp() { super.setUp(); resizableBehavior = new ResizableBehavior(); Panel panel = new DivTestPanel("panelId"); WebMarkupContainer component = new WebMarkupContainer("anId"); component.setMarkupId("anId"); component.add(resizableBehavior); panel.add(component); tester.startComponentInPage(panel); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#destroy()} * . */ @Test public void testDestroy() { assertNotNull(resizableBehavior.destroy()); assertEquals(resizableBehavior.destroy().render().toString(), "$('#anId').resizable('destroy');"); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#disable()} * . */ @Test public void testDisable() { assertNotNull(resizableBehavior.disable()); assertEquals(resizableBehavior.disable().render().toString(), "$('#anId').resizable('disable');"); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#enable()}. */ @Test public void testEnable() { assertNotNull(resizableBehavior.enable()); assertEquals(resizableBehavior.enable().render().toString(), "$('#anId').resizable('enable');"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAlsoResizeComplex()} . */ @Test public void testGetAlsoResizeComplex() { assertNull(resizableBehavior.getAlsoResizeComplex()); resizableBehavior.setAlsoResize(new ResizableAlsoResize(new LiteralOption("div"))); assertNotNull(resizableBehavior.getAlsoResizeComplex()); assertEquals(resizableBehavior.getAlsoResizeComplex().getJavascriptOption().toString(), "'div'"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAnimateEasing()} . */ @Test public void testGetAnimateEasing() { assertEquals(resizableBehavior.getAnimateEasing(), "swing"); resizableBehavior.setAnimateEasing("slide"); assertEquals(resizableBehavior.getAnimateEasing(), "slide"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAnimateDuration()} . */ @Test public void testGetAnimateDuration() { assertNotNull(resizableBehavior.getAnimateDuration()); assertEquals(resizableBehavior.getAnimateDuration().getJavascriptOption().toString(), "'slow'"); resizableBehavior.setAnimateDuration(new ResizableAnimeDuration(1000)); assertEquals(resizableBehavior.getAnimateDuration().getJavascriptOption().toString(), "1000"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getAspectRatio()} . */ @Test public void testGetAspectRatio() { assertNull(resizableBehavior.getAspectRatio()); resizableBehavior.setAspectRatio(new ResizableAspectRatio(true)); assertNotNull(resizableBehavior.getAspectRatio()); assertEquals(resizableBehavior.getAspectRatio().getJavascriptOption().toString(), "true"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getCancel()}. */ @Test public void testGetCancel() { assertEquals(resizableBehavior.getCancel(), "input,option"); resizableBehavior.setCancel("input"); assertEquals(resizableBehavior.getCancel(), "input"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getContainment()} . */ @Test public void testGetContainment() { assertNull(resizableBehavior.getContainment()); resizableBehavior.setContainment(new ResizableContainment(ElementEnum.PARENT)); assertNotNull(resizableBehavior.getContainment()); assertEquals(resizableBehavior.getContainment().getJavascriptOption().toString(), "'parent'"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getDelay()}. */ @Test public void testGetDelay() { assertEquals(resizableBehavior.getDelay(), 0); resizableBehavior.setDelay(5); assertEquals(resizableBehavior.getDelay(), 5); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getDistance()}. */ @Test public void testGetDistance() { assertEquals(resizableBehavior.getDistance(), 1); resizableBehavior.setDistance(5); assertEquals(resizableBehavior.getDistance(), 5); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getGrid()} * . */ @Test public void testGetGrid() { assertNull(resizableBehavior.getGrid()); resizableBehavior.setGrid(5, 6); assertNotNull(resizableBehavior.getGrid()); assertEquals(resizableBehavior.getGrid().getJavascriptOption().toString(), "[5,6]"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getHandles()}. */ @Test public void testGetHandles() { assertNotNull(resizableBehavior.getHandles()); assertEquals(resizableBehavior.getHandles().getJavascriptOption().toString(), "'e,s,se'"); resizableBehavior.setHandles(new ResizableHandles(new LiteralOption("e,s"))); assertEquals(resizableBehavior.getHandles().getJavascriptOption().toString(), "'e,s'"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getHelper()}. */ @Test public void testGetHelper() { assertNull(resizableBehavior.getHelper()); resizableBehavior.setHelper(".aClass"); assertEquals(resizableBehavior.getHelper(), ".aClass"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMaxHeight()}. */ @Test public void testGetMaxHeight() { assertEquals(resizableBehavior.getMaxHeight(), 0); resizableBehavior.setMaxHeight(100); assertEquals(resizableBehavior.getMaxHeight(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMaxWidth()}. */ @Test public void testGetMaxWidth() { assertEquals(resizableBehavior.getMaxWidth(), 0); resizableBehavior.setMaxWidth(100); assertEquals(resizableBehavior.getMaxWidth(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMinHeight()}. */ @Test public void testGetMinHeight() { assertEquals(resizableBehavior.getMinHeight(), 10); resizableBehavior.setMinHeight(100); assertEquals(resizableBehavior.getMinHeight(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getMinWidth()}. */ @Test public void testGetMinWidth() { assertEquals(resizableBehavior.getMinWidth(), 10); resizableBehavior.setMinWidth(100); assertEquals(resizableBehavior.getMinWidth(), 100); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#getOptions()}. */ @Test public void testGetOptions() { assertNotNull(resizableBehavior.getOptions()); assertEquals(resizableBehavior.getOptions().getJavaScriptOptions().toString(), "{}"); resizableBehavior.setAnimate(true); assertEquals(resizableBehavior.getOptions().getJavaScriptOptions().toString(), "{animate: true}"); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isAnimate()}. */ @Test public void testIsAnimate() { assertFalse(resizableBehavior.isAnimate()); resizableBehavior.setAnimate(true); assertTrue(resizableBehavior.isAnimate()); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isAutoHide()}. */ @Test public void testIsAutoHide() { assertFalse(resizableBehavior.isAutoHide()); resizableBehavior.setAutoHide(true); assertTrue(resizableBehavior.isAutoHide()); } /** * Test method for * {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isDisabled()}. */ @Test public void testIsDisabled() { assertFalse(resizableBehavior.isDisabled()); resizableBehavior.setDisabled(true); assertTrue(resizableBehavior.isDisabled()); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#isGhost()} * . */ @Test public void testIsGhost() { assertFalse(resizableBehavior.isGhost()); resizableBehavior.setGhost(true); assertTrue(resizableBehavior.isGhost()); } /** * Test method for {@link org.odlabs.wiquery.ui.resizable.ResizableBehavior#widget()}. */ @Test public void testWidget() { assertNotNull(resizableBehavior.widget()); assertEquals(resizableBehavior.widget().render().toString(), "$('#anId').resizable('widget');"); } }
WiQuery/wiquery
wiquery-jquery-ui/src/test/java/org/odlabs/wiquery/ui/resizable/ResizableBehaviorTestCase.java
Java
mit
10,375
<?php namespace Meling\Cart; /** * Class Totals * @package Meling\Cart */ class Totals { /** * @var Products */ protected $products; /** * @var Actions */ protected $actionsAfter; /** * @var Cards\Card */ protected $card; /** * @var \PHPixie\ORM\Wrappers\Type\Database\Entity */ protected $action; /** * @var array */ protected $instances = array(); /** * Totals constructor. * @param Products $products * @param Actions $actionsAfter * @param Cards\Card $card * @param Actions\Action $action */ public function __construct(Products $products, Actions $actionsAfter, Cards\Card $card, Actions\Action $action) { $this->products = $products; $this->actionsAfter = $actionsAfter; $this->card = $card; $this->action = $action; } /** * @return Totals\Action * @throws \Exception */ public function action() { return $this->instance('action'); } /** * @return Totals\Amount * @throws \Exception */ public function amount() { return $this->instance('amount'); } /** * @return Totals\Bonuses * @throws \Exception */ public function bonuses() { return $this->instance('bonuses'); } /** * @return Totals\Card * @throws \Exception */ public function card() { return $this->instance('card'); } /** * @return Totals\Shipping * @throws \Exception */ public function shipping() { return $this->instance('shipping'); } /** * @return Totals\Total * @throws \Exception */ public function total() { return $this->instance('total'); } protected function buildAction() { return new Totals\Action($this->products, $this->action, $this->card); } protected function buildAmount() { return new Totals\Amount($this->products); } protected function buildBonuses() { return new Totals\Bonuses($this->card); } protected function buildCard() { return new Totals\Card($this->products, $this->action, $this->card); } protected function buildShipping() { return new Totals\Shipping($this->amount(), $this->products); } protected function buildTotal() { return new Totals\Total($this, $this->products, $this->actionsAfter, $this->card); } protected function instance($name) { if(!array_key_exists($name, $this->instances)) { $method = 'build' . ucfirst($name); $this->instances[$name] = $this->$method(); } return $this->instances[$name]; } }
Linfuby/Cart
src/Meling/Cart/Totals.php
PHP
mit
2,866
import DOMUtils from 'tinymce/core/api/dom/DOMUtils'; interface Bookmark { startContainer: Node; startOffset: number; endContainer?: Node; endOffset?: number; } /** * Returns a range bookmark. This will convert indexed bookmarks into temporary span elements with * index 0 so that they can be restored properly after the DOM has been modified. Text bookmarks will not have spans * added to them since they can be restored after a dom operation. * * So this: <p><b>|</b><b>|</b></p> * becomes: <p><b><span data-mce-type="bookmark">|</span></b><b data-mce-type="bookmark">|</span></b></p> * * @param {DOMRange} rng DOM Range to get bookmark on. * @return {Object} Bookmark object. */ const create = (dom: DOMUtils, rng: Range): Bookmark => { const bookmark: Partial<Bookmark> = {}; const setupEndPoint = (start?: boolean) => { let container = rng[start ? 'startContainer' : 'endContainer']; let offset = rng[start ? 'startOffset' : 'endOffset']; if (container.nodeType === 1) { const offsetNode = dom.create('span', { 'data-mce-type': 'bookmark' }); if (container.hasChildNodes()) { offset = Math.min(offset, container.childNodes.length - 1); if (start) { container.insertBefore(offsetNode, container.childNodes[offset]); } else { dom.insertAfter(offsetNode, container.childNodes[offset]); } } else { container.appendChild(offsetNode); } container = offsetNode; offset = 0; } bookmark[start ? 'startContainer' : 'endContainer'] = container; bookmark[start ? 'startOffset' : 'endOffset'] = offset; }; setupEndPoint(true); if (!rng.collapsed) { setupEndPoint(); } return bookmark as Bookmark; }; /** * Moves the selection to the current bookmark and removes any selection container wrappers. * * @param {Object} bookmark Bookmark object to move selection to. */ const resolve = (dom: DOMUtils, bookmark: Bookmark): Range => { const restoreEndPoint = (start?: boolean) => { let node: Node; const nodeIndex = (container: Node) => { let node = container.parentNode.firstChild, idx = 0; while (node) { if (node === container) { return idx; } // Skip data-mce-type=bookmark nodes if (node.nodeType !== 1 || (node as Element).getAttribute('data-mce-type') !== 'bookmark') { idx++; } node = node.nextSibling; } return -1; }; let container = node = bookmark[start ? 'startContainer' : 'endContainer']; let offset = bookmark[start ? 'startOffset' : 'endOffset']; if (!container) { return; } if (container.nodeType === 1) { offset = nodeIndex(container); container = container.parentNode; dom.remove(node); } bookmark[start ? 'startContainer' : 'endContainer'] = container; bookmark[start ? 'startOffset' : 'endOffset'] = offset; }; restoreEndPoint(true); restoreEndPoint(); const rng = dom.createRng(); rng.setStart(bookmark.startContainer, bookmark.startOffset); if (bookmark.endContainer) { rng.setEnd(bookmark.endContainer, bookmark.endOffset); } return rng; }; export { create, resolve };
tinymce/tinymce
modules/tinymce/src/plugins/quickbars/main/ts/selection/Bookmark.ts
TypeScript
mit
3,254
from random import randint, seed, choice, random from numpy import zeros, uint8, cumsum, floor, ceil from math import sqrt, log from collections import namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf): self.leaf = leaf self.lchild = None self.rchild = None def get_leafs(self): if self.lchild == None and self.rchild == None: return [self.leaf] else: return self.lchild.get_leafs()+self.rchild.get_leafs() def get_level(self, level, queue): if queue == None: queue = [] if level == 1: queue.push(self) else: if self.lchild != None: self.lchild.get_level(level-1, queue) if self.rchild != None: self.rchild.get_level(level-1, queue) return queue def paint(self, c): self.leaf.paint(c) if self.lchild != None: self.lchild.paint(c) if self.rchild != None: self.rchild.paint(c) class Container(): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.center = (self.x+int(self.w/2),self.y+int(self.h/2)) self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2) def paint(self, c): c.stroke_rectangle(self.x, self.y, self.w, self.h) def draw_path(self,c,container): c.path(self.center[0],self.center[1],container.center[0],container.center[1]) class Canvas: brushes = {"empty":0, "hallway":1, "room":2} def __init__(self, w, h, color = "empty"): self.board = zeros((h,w), dtype=uint8) self.w = w self.h = h self.set_brush(color) def set_brush(self, code): self.color = self.brushes[code] def stroke_rectangle(self, x, y, w, h): self.line(x,y,w,True) self.line(x,y+h-1,w,True) self.line(x,y,h,False) self.line(x+w-1,y,h,False) def filled_rectangle(self, x, y, w, h): self.board[y:y+h,x:x+w] = self.color def line(self, x, y, length, horizontal): if horizontal: self.board[y,x:x+length] = self.color else: self.board[y:y+length,x] = self.color def path(self,x1,y1,x2,y2): self.board[y1:y2+1,x1:x2+1] = self.color def circle(self,x,y,r): for x_offset in range(-r,r+1): for y_offset in range(-r,r+1): if sqrt(x_offset**2+y_offset**2)<r: self.board[x+x_offset,y+y_offset] = self.color def draw(self): im = Image.fromarray(self.board) im.save(MAP_NAME) def __str__(self): return str(self.board) class Room: environments = ["serene", "calm", "wild", "dangerous", "evil"] biomes = ["rock", "rugged", "sand", "mossy", "muddy", "flooded", "gelid", "gloomy", "magma"] biomes_CDF = cumsum([0.22,0.14,0.12,0.10,0.10,0.07,0.06,0.06,0.04,0.03,0.03,0.03]) def __init__(self, container): self.x = container.x+randint(1, floor(container.w/3)) self.y = container.y+randint(1, floor(container.h/3)) self.w = container.w-(self.x-container.x) self.h = container.h-(self.y-container.y) self.w -= randint(0,floor(self.w/3)) self.h -= randint(0,floor(self.w/3)) self.environment = int(min(4,10*(container.distance_from_center/MAP_WIDTH)+random()*2-1)) roll = random()*0.9+(2*container.distance_from_center/MAP_WIDTH)*0.1 self.biome = next(n for n,b in enumerate(self.biomes_CDF) if roll<b) def paint(self,c): c.filled_rectangle(self.x, self.y,self.w, self.h) def random_split(container): if container.w<MIN_ROOM_SIDE and container.h<MIN_ROOM_SIDE: return None def _split_vertical(container): r1 = None r2 = None min_w = int(W_RATIO*container.h)+1 if container.w < 2*min_w: return None r1 = Container(container.x,container.y,randint(min_w, container.w-min_w),container.h) r2 = Container(container.x+r1.w,container.y,container.w-r1.w,container.h) return [r1, r2] def _split_horizontal(container): r1 = None r2 = None min_h = int(H_RATIO*container.w)+1 if container.h < 2*min_h: return None r1 = Container(container.x,container.y,container.w,randint(min_h, container.h-min_h)) r2 = Container(container.x,container.y+r1.h,container.w,container.h-r1.h) return [r1, r2] if randint(0,1) == 0: res = _split_vertical(container) if res == None: return _split_horizontal(container) return res else: res = _split_horizontal(container) if res == None: return _split_vertical(container) return res def split_container(container, iter): root = Tree(container) if iter != 0: sr = random_split(container) if sr!=None: root.lchild = split_container(sr[0], iter-1) root.rchild = split_container(sr[1], iter-1) return root def draw_paths(c, tree): if tree.lchild == None or tree.rchild == None: return tree.lchild.leaf.draw_path(c, tree.rchild.leaf) draw_paths(c, tree.lchild) draw_paths(c, tree.rchild) MAP_WIDTH = 0 MAP_HEIGHT = 0 N_ITERATIONS = 0 H_RATIO = 0 W_RATIO = 0 MIN_ROOM_SIDE = 0 CENTER_HUB_HOLE = 0 CENTER_HUB_RADIO = 0 MAP_NAME = 0 def init(num_players): global MAP_WIDTH,MAP_HEIGHT,N_ITERATIONS,H_RATIO,W_RATIO,MIN_ROOM_SIDE,CENTER_HUB_HOLE,CENTER_HUB_RADIO,MAP_NAME MAP_WIDTH=int(500*sqrt(num_players)) MAP_HEIGHT=MAP_WIDTH N_ITERATIONS=log(MAP_WIDTH*100,2) H_RATIO=0.49 W_RATIO=H_RATIO MIN_ROOM_SIDE = 32 CENTER_HUB_HOLE = 32 CENTER_HUB_RADIO = CENTER_HUB_HOLE-MIN_ROOM_SIDE/2 MAP_NAME="result%s.png"%MAP_WIDTH def main(num_players, seed_number): logger = getLogger('BSPTree') logger.info("Initialising") init(num_players) seed(seed_number) canvas = Canvas(MAP_WIDTH, MAP_HEIGHT) canvas.set_brush("empty") canvas.filled_rectangle(0,0,MAP_WIDTH,MAP_HEIGHT) logger.info("Generating container tree") # -1 on the main container to remove borders to avoid opened border rooms main_container = Container(0, 0, MAP_WIDTH-1, MAP_HEIGHT-1) container_tree = split_container(main_container, N_ITERATIONS) logger.info("Generating hallways") canvas.set_brush("hallway") draw_paths(canvas, container_tree) logger.info("Generating rooms") canvas.set_brush("room") leafs = container_tree.get_leafs() rooms = [] for i in range(0, len(leafs)): if CENTER_HUB_HOLE < leafs[i].distance_from_center < MAP_WIDTH/2: rooms.append(Room(leafs[i])) rooms[-1].paint(canvas) logger.info("Generating hub") canvas.circle(int(MAP_WIDTH/2),int(MAP_HEIGHT/2),int(CENTER_HUB_RADIO)) #canvas.draw() return (rooms, canvas.board)
juancroldan/derinkuyu
generation/BSPTree.py
Python
mit
6,186
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rx_1 = require("rx"); /* tslint:enable */ function cache(callback) { var cached$ = this.replay(undefined, 1); var subscription = cached$.connect(); callback(function () { return subscription.dispose(); }); return cached$; } rx_1.Observable.prototype.cache = cache; //# sourceMappingURL=Rx.js.map
ZachBray/eye-oh-see-react
dist/Rx.js
JavaScript
mit
392
var chai = require('chai'); var should = chai.should(); var pictogramResponse = require('../../../lib/model/response/pictogramResponse'); describe('pictogramResponse model test', function () { var id = 'id'; var category = 'category'; var url = 'url'; it('should create model', function (done) { var pictogramResponseModel = new pictogramResponse.PictogramResponse( id, category, url ); should.exist(pictogramResponseModel); pictogramResponseModel.id.should.be.equal(id); pictogramResponseModel.category.should.be.equal(category); pictogramResponseModel.url.should.be.equal(url); done(); }); it('should create model by builder', function (done) { var pictogramResponseModel = new pictogramResponse.PictogramResponseBuilder() .withId(id) .withCategory(category) .withUrl(url) .build(); should.exist(pictogramResponseModel); pictogramResponseModel.id.should.be.equal(id); pictogramResponseModel.category.should.be.equal(category); pictogramResponseModel.url.should.be.equal(url); done(); }); });
xclipboard/npm-xclipboard-model
test/model/response/pictogramResponseTest.js
JavaScript
mit
1,113
<?php /** * Choice.php provides additional data access classes for the SurveySez project * * An instance of the Response class will attempt to identify a SurveyID from the srv_responses * database table, and if it exists, will attempt to create all associated Survey, Question & Answer * objects, nearly exactly as the Survey object. * * @package SurveySez * @author William Newman * @version 2.1 2015/05/28 * @link http://newmanix.com/ * @license http://www.apache.org/licenses/LICENSE-2.0 * @see Survey.php * @see Question.php * @see Answer.php * @see Response.php */ namespace SurveySez; /** * Choice Class stores data info for an individual Choice to an Answer * * In the constructor an instance of the Response class creates multiple * instances of the Choice class tacked to the Answer class to store * response data. * * @see Answer * @see Response * @todo none */ class Choice { public $AnswerID = 0; # ID of associated answer public $QuestionID = 0; # ID of associated question public $ChoiceID = 0; # ID of individual choice /** * Constructor for Choice class. * * @param integer $AnswerID ID number of associated answer * @param integer $QuestionID ID number of associated question * @param integer $RQID ID number of choice from srv_response_question table * @return void * @todo none */ function __construct($AnswerID,$QuestionID,$RQID) {# constructor sets stage by adding data to an instance of the object $this->AnswerID = (int)$AnswerID; $this->QuestionID = (int)$QuestionID; $this->ChoiceID = (int)$RQID; }#End Choice constructor }#End Choice class
BrettSpencer/SurveySez
SurveySez/Choice.php
PHP
mit
1,641
"use strict"; /** * @license * Copyright 2017 Google Inc. 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. * ============================================================================= */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var _this = this; Object.defineProperty(exports, "__esModule", { value: true }); var tf = require("./index"); var jasmine_util_1 = require("./jasmine_util"); var tensor_1 = require("./tensor"); var test_util_1 = require("./test_util"); jasmine_util_1.describeWithFlags('variable', jasmine_util_1.ALL_ENVS, function () { it('simple assign', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: v = tf.variable(tf.tensor1d([1, 2, 3])); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [1, 2, 3]]); v.assign(tf.tensor1d([4, 5, 6])); _b = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 2: _b.apply(void 0, [_c.sent(), [4, 5, 6]]); return [2 /*return*/]; } }); }); }); it('simple chain assign', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: v = tf.tensor1d([1, 2, 3]).variable(); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [1, 2, 3]]); v.assign(tf.tensor1d([4, 5, 6])); _b = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 2: _b.apply(void 0, [_c.sent(), [4, 5, 6]]); return [2 /*return*/]; } }); }); }); it('default names are unique', function () { var v = tf.variable(tf.tensor1d([1, 2, 3])); expect(v.name).not.toBeNull(); var v2 = tf.variable(tf.tensor1d([1, 2, 3])); expect(v2.name).not.toBeNull(); expect(v.name).not.toBe(v2.name); }); it('user provided name', function () { var v = tf.variable(tf.tensor1d([1, 2, 3]), true, 'myName'); expect(v.name).toBe('myName'); }); it('if name already used, throw error', function () { tf.variable(tf.tensor1d([1, 2, 3]), true, 'myName'); expect(function () { return tf.variable(tf.tensor1d([1, 2, 3]), true, 'myName'); }) .toThrowError(); }); it('ops can take variables', function () { return __awaiter(_this, void 0, void 0, function () { var value, v, res, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: value = tf.tensor1d([1, 2, 3]); v = tf.variable(value); res = tf.sum(v); _a = test_util_1.expectArraysClose; return [4 /*yield*/, res.data()]; case 1: _a.apply(void 0, [_b.sent(), [6]]); return [2 /*return*/]; } }); }); }); it('chained variables works', function () { return __awaiter(_this, void 0, void 0, function () { var v, res, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: v = tf.tensor1d([1, 2, 3]).variable(); res = tf.sum(v); _a = test_util_1.expectArraysClose; return [4 /*yield*/, res.data()]; case 1: _a.apply(void 0, [_b.sent(), [6]]); return [2 /*return*/]; } }); }); }); it('variables are not affected by tidy', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: expect(tf.memory().numTensors).toBe(0); tf.tidy(function () { var value = tf.tensor1d([1, 2, 3], 'float32'); expect(tf.memory().numTensors).toBe(1); v = tf.variable(value); expect(tf.memory().numTensors).toBe(2); }); expect(tf.memory().numTensors).toBe(1); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_b.sent(), [1, 2, 3]]); v.dispose(); expect(tf.memory().numTensors).toBe(0); return [2 /*return*/]; } }); }); }); it('disposing a named variable allows creating new named variable', function () { var numTensors = tf.memory().numTensors; var t = tf.scalar(1); var varName = 'var'; var v = tf.variable(t, true, varName); expect(tf.memory().numTensors).toBe(numTensors + 2); v.dispose(); t.dispose(); expect(tf.memory().numTensors).toBe(numTensors); // Create another variable with the same name. var t2 = tf.scalar(1); var v2 = tf.variable(t2, true, varName); expect(tf.memory().numTensors).toBe(numTensors + 2); t2.dispose(); v2.dispose(); expect(tf.memory().numTensors).toBe(numTensors); }); it('double disposing a variable works', function () { var numTensors = tf.memory().numTensors; var t = tf.scalar(1); var v = tf.variable(t); expect(tf.memory().numTensors).toBe(numTensors + 2); t.dispose(); v.dispose(); expect(tf.memory().numTensors).toBe(numTensors); // Double dispose the variable. v.dispose(); expect(tf.memory().numTensors).toBe(numTensors); }); it('constructor does not dispose', function () { return __awaiter(_this, void 0, void 0, function () { var a, v, _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: a = tf.scalar(2); v = tf.variable(a); expect(tf.memory().numTensors).toBe(2); expect(tf.memory().numDataBuffers).toBe(1); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [2]]); _b = test_util_1.expectArraysClose; return [4 /*yield*/, a.data()]; case 2: _b.apply(void 0, [_c.sent(), [2]]); return [2 /*return*/]; } }); }); }); it('variables are assignable to tensors', function () { // This test asserts compilation, not doing any run-time assertion. var x0 = null; var y0 = x0; expect(y0).toBeNull(); var x1 = null; var y1 = x1; expect(y1).toBeNull(); var x2 = null; var y2 = x2; expect(y2).toBeNull(); var x3 = null; var y3 = x3; expect(y3).toBeNull(); var x4 = null; var y4 = x4; expect(y4).toBeNull(); var xh = null; var yh = xh; expect(yh).toBeNull(); }); it('assign does not dispose old data', function () { return __awaiter(_this, void 0, void 0, function () { var v, _a, secondArray, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: v = tf.variable(tf.tensor1d([1, 2, 3])); expect(tf.memory().numTensors).toBe(2); expect(tf.memory().numDataBuffers).toBe(1); _a = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 1: _a.apply(void 0, [_c.sent(), [1, 2, 3]]); secondArray = tf.tensor1d([4, 5, 6]); expect(tf.memory().numTensors).toBe(3); expect(tf.memory().numDataBuffers).toBe(2); v.assign(secondArray); _b = test_util_1.expectArraysClose; return [4 /*yield*/, v.data()]; case 2: _b.apply(void 0, [_c.sent(), [4, 5, 6]]); // Assign doesn't dispose the 1st array. expect(tf.memory().numTensors).toBe(3); expect(tf.memory().numDataBuffers).toBe(2); v.dispose(); // Disposing the variable disposes itself. The input to variable and // secondArray are the only remaining tensors. expect(tf.memory().numTensors).toBe(2); expect(tf.memory().numDataBuffers).toBe(2); return [2 /*return*/]; } }); }); }); it('shape must match', function () { var v = tf.variable(tf.tensor1d([1, 2, 3])); expect(function () { return v.assign(tf.tensor1d([1, 2])); }).toThrowError(); // tslint:disable-next-line:no-any expect(function () { return v.assign(tf.tensor2d([3, 4], [1, 2])); }).toThrowError(); }); it('dtype must match', function () { var v = tf.variable(tf.tensor1d([1, 2, 3])); // tslint:disable-next-line:no-any expect(function () { return v.assign(tf.tensor1d([1, 1, 1], 'int32')); }) .toThrowError(); // tslint:disable-next-line:no-any expect(function () { return v.assign(tf.tensor1d([true, false, true], 'bool')); }) .toThrowError(); }); }); jasmine_util_1.describeWithFlags('x instanceof Variable', jasmine_util_1.ALL_ENVS, function () { it('x: Variable', function () { var t = tf.variable(tf.scalar(1)); expect(t instanceof tensor_1.Variable).toBe(true); }); it('x: Variable-like', function () { var t = { assign: function () { }, shape: [2], dtype: 'float32', dataId: {} }; expect(t instanceof tensor_1.Variable).toBe(true); }); it('x: other object, fails', function () { var t = { something: 'else' }; expect(t instanceof tensor_1.Variable).toBe(false); }); it('x: Tensor, fails', function () { var t = tf.scalar(1); expect(t instanceof tensor_1.Variable).toBe(false); }); }); //# sourceMappingURL=variable_test.js.map
ManakCP/NestJs
node_modules/@tensorflow/tfjs-core/dist/variable_test.js
JavaScript
mit
13,815
import React from "react"; import { useResponse } from "@curi/react-dom"; import NavLinks from "./NavLinks"; export default function App() { let { response } = useResponse(); let { body: Body } = response; return ( <div> <NavLinks /> <Body response={response} /> </div> ); }
pshrmn/curi
examples/misc/server-rendering/src/components/App.js
JavaScript
mit
305
import { Tween } from '../core'; import { mat4 } from '../math'; export class MatrixTween extends Tween { action() { for (let i = 0; i < this.from.length; i++) { this.object[i] = this.from[i] + this.current_step * (this.to[i] - this.from[i]); } } pre_start() { super.pre_start(); this.from = mat4.clone(this.object); } }
michalbe/cervus
tweens/matrix-tween.js
JavaScript
mit
355
#include "stdafx.h" #include "model.h" #include "node.h" #include "../manager/resourcemanager.h" #include "mesh.h" #include "bonemgr.h" using namespace graphic; // Bone¸¶´Ù °æ°è¹Ú½º¸¦ »ý¼ºÇÑ´Ù. struct sMinMax { Vector3 Min; Vector3 Max; sMinMax() : Min(Vector3(0,0,0)), Max(Vector3(0,0,0)) {} }; cModel::cModel() : m_bone(NULL) , m_isRenderMesh(true) , m_isRenderBone(false) { } cModel::~cModel() { Clear(); } bool cModel::Create(const string &modelName) { sRawMeshGroup *rawMeshes = cResourceManager::Get()->LoadModel(modelName); RETV(!rawMeshes, false); Clear(); const bool isSkinnedMesh = !rawMeshes->bones.empty(); // ½ºÅ°´× ¾Ö´Ï¸ÞÀ̼ÇÀ̸é BoneÀ» »ý¼ºÇÑ´Ù. if (isSkinnedMesh) { m_bone = new cBoneMgr(0, *rawMeshes); } // ¸Þ½¬ »ý¼º. int id = 0; BOOST_FOREACH (auto &mesh, rawMeshes->meshes) { cMesh *p = NULL; if (isSkinnedMesh) { p = new cSkinnedMesh(id++, m_bone->GetPalette(), mesh); } else { p = new cRigidMesh(id++, mesh); } if (p) m_meshes.push_back(p); } CreateBoneBoundingBox(modelName); return true; } void cModel::SetAnimation( const string &aniFileName) { if (sRawAniGroup *rawAnies = cResourceManager::Get()->LoadAnimation(aniFileName)) { if (m_bone) { m_bone->SetAnimation(*rawAnies, 0); } else { for (u_int i=0; i < m_meshes.size(); ++i) { ((cRigidMesh*)m_meshes[ i])->LoadAnimation(rawAnies->anies[0]); } } } } bool cModel::Move(const float elapseTime) { BOOST_FOREACH (auto node, m_meshes) node->Move(elapseTime); if (m_bone) m_bone->Move(elapseTime); return true; } void cModel::Render() { Matrix44 identity; GetDevice()->SetTransform(D3DTS_WORLD, (D3DXMATRIX*)&identity); if (m_isRenderMesh) { BOOST_FOREACH (auto node, m_meshes) node->Render(m_matTM); } if (m_isRenderBone && m_bone) m_bone->Render(m_matTM); // render bounding Box for (int i=0; i < (int)m_boundingBox.size(); ++i) m_boundingBox[ i].Render( m_bone->GetPalette()[ i] * m_matTM); } // remove all data void cModel::Clear() { BOOST_FOREACH (auto mesh, m_meshes) { SAFE_DELETE(mesh); } m_meshes.clear(); SAFE_DELETE(m_bone); } // ¸Þ½¬¸¦ ã¾Æ¼­ ¸®ÅÏÇÑ´Ù. cMesh* cModel::FindMesh(const string &meshName) { BOOST_FOREACH (auto &mesh, m_meshes) { if (mesh->GetName() == meshName) return (cMesh*)mesh; } return NULL; } // Bone bounding box void cModel::CreateBoneBoundingBox(const string &modelName) { RET(!m_bone); sRawMeshGroup *rawMeshes = cResourceManager::Get()->LoadModel(modelName); RET(!rawMeshes); const int boneCount = rawMeshes->bones.size(); vector<sMinMax> boundingBox(boneCount); vector<Matrix44> boneInvers(boneCount); for (int i=0; i < boneCount; ++i) { boneInvers[ i] = rawMeshes->bones[ i].worldTm.Inverse(); boundingBox[ i] = sMinMax(); } BOOST_FOREACH (const sRawMesh &mesh, rawMeshes->meshes) { BOOST_FOREACH (const sVertexWeight &weight, mesh.weights) { const int vtxIdx = weight.vtxIdx; for( int k=0; k < weight.size; ++k ) { const sWeight *w = &weight.w[ k]; const Vector3 pos = mesh.vertices[ vtxIdx] * boneInvers[ w->bone]; if (boundingBox[ w->bone].Min.x > pos.x) boundingBox[ w->bone].Min.x = pos.x; if (boundingBox[ w->bone].Min.y > pos.y) boundingBox[ w->bone].Min.y = pos.y; if (boundingBox[ w->bone].Min.z > pos.z) boundingBox[ w->bone].Min.z = pos.z; if (boundingBox[ w->bone].Max.x < pos.x) boundingBox[ w->bone].Max.x = pos.x; if (boundingBox[ w->bone].Max.y < pos.y) boundingBox[ w->bone].Max.y = pos.y; if (boundingBox[ w->bone].Max.z < pos.z) boundingBox[ w->bone].Max.z = pos.z; } } } m_boundingBox.resize(boneCount); for (int i=0; i < boneCount; ++i) { // ¿ùµå ÁÂÇ¥°ø°£À¸·Î À̵¿½ÃŲ´Ù. palette ¸¦ Àû¿ëÇϱâ À§Çؼ­´Â ¿ùµå°ø°£¿¡ ÀÖ¾î¾ß ÇÔ. const Vector3 wMin = boundingBox[ i].Min;// * rawMeshes->bones[ i].worldTm; const Vector3 wMax = boundingBox[ i].Max;// * rawMeshes->bones[ i].worldTm; m_boundingBox[ i].SetCube( wMin, wMax ); m_boundingBox[ i].SetTransform(rawMeshes->bones[ i].worldTm); } }
kami36/3Dproject
Graphic/model/model.cpp
C++
mit
4,095
<?php declare(strict_types=1); /** * This file is part of the Netrc package. * * (c) Alex Medvedev <alex.medwedew@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Date: 3/21/14 */ namespace Fduch\Netrc\Exception; use \RuntimeException; /** * ParseException * * @author Alex Medvedev */ class ParseException extends RuntimeException { }
fduch/netrc
src/Exception/ParseException.php
PHP
mit
448
import React from 'react'; import MobileTearSheet from './MobileTearSheet'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import ActionInfo from 'material-ui/lib/svg-icons/action/info'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import FileFolder from 'material-ui/lib/svg-icons/file/folder'; import ActionAssignment from 'material-ui/lib/svg-icons/action/assignment'; import Colors from 'material-ui/lib/styles/colors'; import EditorInsertChart from 'material-ui/lib/svg-icons/editor/insert-chart'; const ListExampleFolder = () => ( <MobileTearSheet> <List subheader="Folders" insetSubheader={true}> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Photos" secondaryText="Jan 9, 2014" /> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Recipes" secondaryText="Jan 17, 2014" /> <ListItem leftAvatar={<Avatar icon={<FileFolder />} />} rightIcon={<ActionInfo />} primaryText="Work" secondaryText="Jan 28, 2014" /> </List> <Divider inset={true} /> <List subheader="Files" insetSubheader={true}> <ListItem leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={Colors.blue500} />} rightIcon={<ActionInfo />} primaryText="Vacation itinerary" secondaryText="Jan 20, 2014" /> <ListItem leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={Colors.yellow600} />} rightIcon={<ActionInfo />} primaryText="Kitchen remodel" secondaryText="Jan 10, 2014" /> </List> </MobileTearSheet> ); export default ListExampleFolder;
PranavRam/pfrally
src/pages/home/ListExampleFolder.js
JavaScript
mit
1,876
module.exports = function Boot(game) { return { preload: function(){ game.load.image('mars', '/assets/images/mars.png'); }, create: function(){ //This is just like any other Phaser create function console.log('Boot was just loaded'); this.mars = game.add.sprite(0, 0, 'mars'); }, update: function(){ //Game logic goes here this.mars.x += 1; this.mars.y += 1; } } };
krzychukula/browserify-phaser
src/states/boot.js
JavaScript
mit
439
var topics = require('../data').topics; console.log(topics); var result = topics.filter(function (topic) { //filter renvoie les 'true' return topic.user.name === 'Leonard'; //? true : false; }); var result2 = topics.filter(topic=>topic.user.name === 'Leonard'); var titles = topics.map(function (topic) { return topic.title; }); var title2 = topics.map(topic=>topic.title); var hasViolence = topics.some(function (topic) { //renvoie true pour les topics avec violence return (topic.tags.includes('violence')); }); var hasViolence2 = topics.some(topic=>topic.tags.includes('violence')); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(result); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(result2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(titles); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log(title2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); console.log('hasViolence ', hasViolence); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var SheldonCom = topics.filter(function (topic) { return (topic.comments.some(function (comment) { return comment.user.name === 'Sheldon'; })); }).map(function (topic) { return (topic.title); }); var SheldonCom2; SheldonCom2 = topics.filter(topic=>topic.comments.some(comment=>comment.user.name === 'Sheldon')).map(topic=>topic.title); console.log('Sheldon has published in ', SheldonCom); console.log('Sheldon has published in ', SheldonCom2); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var idCommPenny = []; topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.user.name === 'Penny') { idCommPenny.push(comment.id); } }) }); var sortFunction = (a, b) => a < b ? -1 : 1; idCommPenny.sort(sortFunction); console.log('Penny has post in : ', idCommPenny); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var Content = []; function getCommentByTag(tag, isAdmin) { topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.tags !== undefined) { if (!comment.user.admin === isAdmin && comment.tags.includes(tag)) { Content.push(comment.content); } } }); }); return Content; }; console.log('Violent tag are present for these non-admin comments : ', getCommentByTag('fun', true)); console.log('_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_/-\\\_'); var searched = []; function search(term) { topics.forEach(function (topic) { topic.comments.forEach(function (comment) { if (comment.content.toLowerCase().includes(term.toLowerCase())) { searched.push(comment.content); } }) }); return searched; } console.log('search is present in :', search('it'));
florianfouchard/javascript-training
src/function/ES5.js
JavaScript
mit
3,573
using System; using System.Collections.Generic; using System.Text; namespace Imml { public interface IElementFactory { ImmlElement Create(string elementName, IImmlElement parentElement); } }
craigomatic/IMML
src/Imml/IElementFactory.cs
C#
mit
215
File.dirname(__FILE__).tap do |supermarket| Dir[File.join(supermarket, 'import', '*.rb')].map do |file| file.split(File::SEPARATOR).last.split('.').first end.each do |name| require "supermarket/import/#{name}" end end require 'supermarket/community_site' module Supermarket module Import def self.debug yield if ENV['SUPERMARKET_DEBUG'] end def self.report(e) raven_options = {} if e.respond_to?(:record) && e.record.is_a?(::CookbookVersion) if e.record.errors[:tarball_content_type] raven_options[:extra] = { tarball_content_type: e.record.tarball_content_type } end end if e.is_a?(CookbookVersionDependencies::UnableToProcessTarball) raven_options[:extra] = { cookbook_name: e.cookbook_name, cookbook_version: e.cookbook_version, messages: e.errors.full_messages.join('; ') } end Raven.capture_exception(e, raven_options) debug do message_header = "#{e.class}: #{e.message}\n #{raven_options.inspect}" relevant_backtrace = e.backtrace.select do |line| line.include?('supermarket') || line.include?('chef-legacy') end message_body = ([message_header] + relevant_backtrace).join("\n ") yield message_body end end end end
gofullstack/chef-legacy
lib/supermarket/import.rb
Ruby
mit
1,365
StatsGopher.PresenceMonitor = function PresenceMonitor (opts) { opts = opts || {}; this.statsGopher = opts.statsGopher; this.key = opts.key; this.send = this.executeNextSend; this.paused = false; } StatsGopher.PresenceMonitor.prototype = { ignoreNextSend: function () { }, queueNextSend: function () { this.request.done(function () { this.send() }.bind(this)) this.send = this.ignoreNextSend }, executeNextSend: function () { var executeNextSend = function () { this.send = this.executeNextSend }.bind(this); if (this.paused) return; this.request = this.statsGopher.send({ code: this.code, key: this.key }).done(executeNextSend).fail(executeNextSend); this.send = this.queueNextSend }, pause: function () { this.paused = true }, resume: function () { this.paused = false } } StatsGopher.Heartbeat = function (opts) { StatsGopher.PresenceMonitor.apply(this, arguments) this.timeout = (typeof opts.timeout) === 'number' ? opts.timeout : 10000; } StatsGopher.Heartbeat.prototype = new StatsGopher.PresenceMonitor() StatsGopher.Heartbeat.prototype.code = 'heartbeat' StatsGopher.Heartbeat.prototype.start = function () { this.send() setTimeout(this.start.bind(this), 10000) } StatsGopher.UserActivity = function () { StatsGopher.PresenceMonitor.apply(this, arguments) } StatsGopher.UserActivity.prototype = new StatsGopher.PresenceMonitor() StatsGopher.UserActivity.prototype.code = 'user-activity' StatsGopher.UserActivity.prototype.listen = function () { var events = [ 'resize', 'click', 'mousedown', 'scroll', 'mousemove', 'keydown' ]; events.forEach(function (eventName) { window.addEventListener(eventName, function () { this.send(); }.bind(this)) }.bind(this)); }
sjltaylor/stats-gopher-js
src/stats_gopher.presence_monitor.js
JavaScript
mit
1,828
app.service('operacoes', function() { this.somar = function(valor1, valor2) { return valor1 + valor2; } this.subtrair = function(valor1, valor2) { return valor1 - valor2; } });
rodriggoarantes/rra-angular
js/aula09.service.js
JavaScript
mit
220
<?php /* * This file is part of the Topycs package. * * (c) Daniel Ribeiro <drgomesp@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Topycs\Discussions\Builder; /** * Defines a fluent builder for threads. * * @author Daniel Ribeiro <drgomesp@gmail.com> * @package Topycs\Discussions\Builder */ interface ThreadBuilderInterface { /** * Builds a thread. * * @param string $title * @param string $content * @return \Topycs\Discussions\Entity\ThreadInterface */ public function buildThread($title, $content); }
adamelso/Topycs
src/Topycs/Discussions/Builder/ThreadBuilderInterface.php
PHP
mit
665
from modelmapper.declarations import Mapper, Field from modelmapper.qt.fields import QLineEditAccessor class String(QLineEditAccessor): def get_value(self): return str(self.widget.text()) def set_value(self, value): self.widget.setText(str(value)) class Integer(QLineEditAccessor): def get_value(self): return int(self.widget.text()) def set_value(self, value): self.widget.setText(int(value)) def get_child_x_mapper(x): return { '{}_link'.format(x): (x, 'val_{}'.format(x)) } def get_d_mapper(): return { 'expediente_link': Mapper('c[0]', 'val_c[0]', get_child_x_mapper('a')), 'masa_bruta_link': Mapper('c[1]', 'val_c[1]', get_child_x_mapper('b')), 'nombre_link': Field('cc', 'val_cc'), } def get_model_mapper(): return { 'expediente_link': Field('expediente', String('expediente')), 'masa_bruta_link': Field('masa_bruta', Integer('masa_bruta')), 'nombre_link': Field('nombre', String('nombre')) }
franramirez688/model-mapper
tests/factory/qt/mapper_data.py
Python
mit
1,040
function paddAppendClear() { jQuery('.append-clear').append('<div class="clear"></div>'); } function paddWrapInner1() { jQuery('.wrap-inner-1').wrapInner('<div class="inner"></div>'); } function paddWrapInner3() { jQuery('.wrap-inner-3').wrapInner('<div class="m"></div>'); jQuery('.wrap-inner-3').prepend('<div class="t"></div>'); jQuery('.wrap-inner-3').append('<div class="b"></div>'); } function paddToggle(classname,value) { jQuery(classname).focus(function() { if (value == jQuery(classname).val()) { jQuery(this).val(''); } }); jQuery(classname).blur(function() { if ('' == jQuery(classname).val()) { jQuery(this).val(value); } }); } jQuery(document).ready(function() { jQuery.noConflict(); jQuery('div#menubar div > ul').superfish({ hoverClass: 'hover', speed: 500, animation: { opacity: 'show', height: 'show' } }); paddAppendClear(); paddWrapInner1(); paddWrapInner3(); jQuery('p.older-articles').titleBoxShadow('#ebebeb'); jQuery('.hentry-large .title').titleBoxShadow('#ebebeb'); jQuery('.hentry-large .thumbnail img').imageBoxShadow('#ebebeb'); jQuery('input#s').val('Search this site'); paddToggle('input#s','Search this site'); jQuery('div.search form').click(function () { jQuery('input#s').focus(); }); });
chin8628/SIC
wp-content/themes/germaniumify/js/main.loading.js
JavaScript
mit
1,282
<?php /** * FurryBear * * PHP Version 5.3 * * @category Congress_API * @package FurryBear * @author lobostome <lobostome@local.dev> * @license http://opensource.org/licenses/MIT MIT License * @link https://github.com/lobostome/FurryBear */ namespace FurryBear\Resource\SunlightCongress\Method; use FurryBear\Resource\SunlightCongress\BaseResource; /** * This class gives access to Sunlight Congress votes resource. * * @category Congress_API * @package FurryBear * @author lobostome <lobostome@local.dev> * @license http://opensource.org/licenses/MIT MIT License * @link https://github.com/lobostome/FurryBear */ class Votes extends BaseResource { /** * The resource method URL. No slashes at the beginning and end of the * string. */ const ENDPOINT_METHOD = 'votes'; /** * Constructs the resource, sets a reference to the FurryBear object, and * sets the resource method URL. * * @param \FurryBear\FurryBear $furryBear A reference to the FurryBear onject. */ public function __construct(\FurryBear\FurryBear $furryBear) { parent::__construct($furryBear); $this->setResourceMethod(self::ENDPOINT_METHOD); } }
lobostome/FurryBear
src/FurryBear/Resource/SunlightCongress/Method/Votes.php
PHP
mit
1,233
/* globals $ */ const modals = window.modals; const footer = window.footer; const notifier = window.notifier; const admin = window.admin; ((scope) => { const modalLogin = modals.get("login"); const modalRegister = modals.get("register"); const helperFuncs = { loginUser(userToLogin) { const url = window.baseUrl + "login"; // loader.show(); // $("#loader .loader-title").html("Creating"); Promise.all([http.postJSON(url, userToLogin), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result.success) { res = resp.result; let html = templateFunc({ res }); $("#nav-wrap").html(html); notifier.success(`Welcome ${userToLogin.username}!`); } else { res = resp.result.success; notifier.error("Wrong username or password!"); } // loader.hide(); modalLogin.hide(); $("#content-wrap").addClass(res.role); }) .then(() => { console.log($("#content-wrap").hasClass("admin")); if ($("#content-wrap").hasClass("admin")) { content.init("admin-content"); admin.init(); } if ($("#content-wrap").hasClass("standart")) { content.init("user-content"); users.init(); } }) .catch((err) => { // loader.hide(); notifier.error(`${userToLogin.username} not created! ${err}`); console.log(JSON.stringify(err)); }); }, registerUser(userToRegister) { const url = window.baseUrl + "register"; // loader.show(); // $("#loader .loader-title").html("Creating Book"); Promise.all([http.postJSON(url, userToRegister), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result.success) { res = false; } else { res = resp.result; console.log(resp); // let html = templateFunc({ // res // }); // $("#nav-wrap").html(html); } // loader.hide(); modalRegister.hide(); }) .catch((err) => { // loader.hide(); notifier.error(`${userToLogin.username} not created! ${err}`); console.log(JSON.stringify(err)); }); }, loginFormEvents() { const $form = $("#form-login"); $form.on("submit", function() { const user = { username: $("#tb-username").val(), password: $("#tb-password").val() }; console.log(user); helperFuncs.loginUser(user); return false; }); }, registerFormEvents() { const $form = $("#form-register"); $form.on("submit", function() { const user = { firstName: $("#tb-firstname").val(), lastName: $("#tb-lastname").val(), username: $("#tb-username").val(), password: $("#tb-password").val() }; helperFuncs.registerUser(user); return false; }); }, menuCollaps() { let pull = $("#pull"); menu = $("nav ul"); link = $("#subMenu"); signUp = $("#signUp"); submenu = $("nav li ul"); console.log(link); menuHeight = menu.height(); $(pull).on("click", function(ev) { ev.preventDefault(); menu.slideToggle(); submenu.hide(); }); $(link).on("click", function(ev) { ev.preventDefault(); signUp.next().hide(); link.next().slideToggle(); }); $(signUp).on("click", function(ev) { ev.preventDefault(); link.next().hide(); signUp.next().slideToggle(); }); $(window).resize(function() { let win = $(window).width(); if (win > 760 && menu.is(":hidden")) { menu.removeAttr("style"); } }); } }; const initial = () => { const url = window.baseUrl + "users"; Promise .all([http.get(url), templates.getPage("nav")]) .then(([resp, templateFunc]) => { if (resp.result === "unauthorized!") { res = false; } else { res = resp.result; } let html = templateFunc({ res }); $("#nav-wrap").html(html); $(".btn-login-modal").on("click", () => { modalLogin.show() .then(() => { helperFuncs.loginFormEvents(); }); }); $("#btn-register-modal").on("click", () => { modalRegister.show() .then(() => { helperFuncs.registerFormEvents(); }); }); }) .then(footer.init()) .then(() => { content.init("no-user-content"); }) .then(() => { helperFuncs.menuCollaps(); }); Handlebars.registerHelper("ifEq", (v1, v2, options) => { if (v1 === v2) { return options.fn(this); } return options.inverse(this); }); Handlebars.registerHelper("mod3", (index, options) => { if ((index + 1) % 3 === 0) { return options.fn(this); } return options.inverse(this); }); }; scope.nav = { initial }; })(window.controllers = window.controllers || {});
VenelinGP/Gemstones
src/public/pages/nav/nav.js
JavaScript
mit
6,675
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateForumOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('forum_orders', function (Blueprint $table) { $table->increments('id'); $table->smallInteger('forum_id'); $table->integer('user_id'); $table->string('section', 50)->nullable(); $table->tinyInteger('is_hidden')->default(0); $table->smallInteger('order'); $table->index('forum_id'); $table->index('user_id'); $table->unique(['forum_id', 'user_id']); $table->foreign('forum_id')->references('id')->on('forums')->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('forum_orders'); } }
adam-boduch/coyote
database/migrations/2015_12_09_212709_create_forum_orders_table.php
PHP
mit
1,086
__author__ = 'bptripp' import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D """ Initialization of CNNs via clustering of inputs and convex optimization of outputs. """ def sigmoid(x, centre, gain): y = 1 / (1 + np.exp(-gain*(x-centre))) return y def gaussian(x, mu, sigma): return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sigma, 2.))) def get_sigmoid_params(false_samples, true_samples, do_plot=False): """ Find gain and bias for sigmoid function that approximates probability of class memberships. Probability based on Bayes' rule & gaussian model of samples from each class. """ false_mu = np.mean(false_samples) false_sigma = np.std(false_samples) true_mu = np.mean(true_samples) true_sigma = np.std(true_samples) lowest = np.minimum(np.min(false_samples), np.min(true_samples)) highest = np.maximum(np.max(false_samples), np.max(true_samples)) a = np.arange(lowest, highest, (highest-lowest)/25) p_x_false = gaussian(a, false_mu, false_sigma) p_x_true = gaussian(a, true_mu, true_sigma) p_x = p_x_true + p_x_false p_true = p_x_true / p_x popt, _ = curve_fit(sigmoid, a, p_true) centre, gain = popt[0], popt[1] if do_plot: plt.hist(false_samples, a) plt.hist(true_samples, a) plt.plot(a, 100*sigmoid(a, centre, gain)) plt.plot(a, 100*p_true) plt.title('centre: ' + str(centre) + ' gain: ' + str(gain)) plt.show() return centre, gain def check_sigmoid(): n = 1000 false_samples = 1 + .3*np.random.randn(n) true_samples = -1 + 1*np.random.randn(n) centre, gain = get_sigmoid_params(false_samples, true_samples, do_plot=True) def get_convolutional_prototypes(samples, shape, patches_per_sample=5): assert len(samples.shape) == 4 assert len(shape) == 4 wiggle = (samples.shape[2]-shape[2], samples.shape[3]-shape[3]) patches = [] for sample in samples: for i in range(patches_per_sample): corner = (np.random.randint(0, wiggle[0]), np.random.randint(0, wiggle[1])) patches.append(sample[:,corner[0]:corner[0]+shape[2],corner[1]:corner[1]+shape[3]]) patches = np.array(patches) flat = np.reshape(patches, (patches.shape[0], -1)) km = KMeans(shape[0]) km.fit(flat) kernels = km.cluster_centers_ # normalize product of centre and corresponding kernel for i in range(kernels.shape[0]): kernels[i,:] = kernels[i,:] / np.linalg.norm(kernels[i,:]) return np.reshape(kernels, shape) def get_dense_prototypes(samples, n): km = KMeans(n) km.fit(samples) return km.cluster_centers_ def check_get_prototypes(): samples = np.random.rand(1000, 2, 28, 28) prototypes = get_convolutional_prototypes(samples, (20,2,5,5)) print(prototypes.shape) samples = np.random.rand(900, 2592) prototypes = get_dense_prototypes(samples, 64) print(prototypes.shape) def get_discriminant(samples, labels): lda = LinearDiscriminantAnalysis(solver='eigen', shrinkage='auto') lda.fit(samples, labels) return lda.coef_[0] def check_discriminant(): n = 1000 labels = np.random.rand(n) < 0.5 samples = np.zeros((n,2)) for i in range(len(labels)): if labels[i] > 0.5: samples[i,:] = np.array([0,1]) + 1*np.random.randn(1,2) else: samples[i,:] = np.array([-2,-1]) + .5*np.random.randn(1,2) coeff = get_discriminant(samples, labels) plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.scatter(samples[labels>.5,0], samples[labels>.5,1], color='g') plt.scatter(samples[labels<.5,0], samples[labels<.5,1], color='r') plt.plot([-coeff[0], coeff[0]], [-coeff[1], coeff[1]], color='k') plt.subplot(1,2,2) get_sigmoid_params(np.dot(samples[labels<.5], coeff), np.dot(samples[labels>.5], coeff), do_plot=True) plt.show() def init_model(model, X_train, Y_train): if not (isinstance(model.layers[-1], Activation) \ and model.layers[-1].activation.__name__ == 'sigmoid'\ and isinstance(model.layers[-2], Dense)): raise Exception('This does not look like an LDA-compatible network, which is all we support') for i in range(len(model.layers)-2): if isinstance(model.layers[i], Convolution2D): inputs = get_inputs(model, X_train, i) w, b = model.layers[i].get_weights() w = get_convolutional_prototypes(inputs, w.shape) b = .1 * np.ones_like(b) model.layers[i].set_weights([w,b]) if isinstance(model.layers[i], Dense): inputs = get_inputs(model, X_train, i) w, b = model.layers[i].get_weights() w = get_dense_prototypes(inputs, w.shape[1]).T b = .1 * np.ones_like(b) model.layers[i].set_weights([w,b]) inputs = get_inputs(model, X_train, len(model.layers)-3) coeff = get_discriminant(inputs, Y_train) centre, gain = get_sigmoid_params(np.dot(inputs[Y_train<.5], coeff), np.dot(inputs[Y_train>.5], coeff)) w = coeff*gain w = w[:,np.newaxis] b = np.array([-centre]) model.layers[-2].set_weights([w,b]) sigmoid_inputs = get_inputs(model, X_train, len(model.layers)-1) plt.figure() plt.subplot(2,1,1) bins = np.arange(np.min(Y_train), np.max(Y_train)) plt.hist(sigmoid_inputs[Y_train<.5]) plt.subplot(2,1,2) plt.hist(sigmoid_inputs[Y_train>.5]) plt.show() def get_inputs(model, X_train, layer): if layer == 0: return X_train else: partial_model = Sequential(layers=model.layers[:layer]) partial_model.compile('sgd', 'mse') return partial_model.predict(X_train) if __name__ == '__main__': # check_sigmoid() # check_get_prototypes() # check_discriminant() import cPickle f = file('../data/bowl-test.pkl', 'rb') # f = file('../data/depths/24_bowl-29-Feb-2016-15-01-53.pkl', 'rb') d, bd, l = cPickle.load(f) f.close() d = d - np.mean(d.flatten()) d = d / np.std(d.flatten()) # n = 900 n = 90 X_train = np.zeros((n,1,80,80)) X_train[:,0,:,:] = d[:n,:,:] Y_train = l[:n] model = Sequential() model.add(Convolution2D(64,9,9,input_shape=(1,80,80))) model.add(Activation('relu')) model.add(MaxPooling2D()) # model.add(Convolution2D(64,3,3)) # model.add(Activation('relu')) # model.add(MaxPooling2D()) model.add(Flatten()) model.add(Dense(64)) model.add(Activation('relu')) model.add(Dense(1)) model.add(Activation('sigmoid')) init_model(model, X_train, Y_train) # from visualize import plot_kernels # plot_kernels(model.layers[0].get_weights()[0])
bptripp/grasp-convnet
py/cninit.py
Python
mit
7,083
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe WeeklyDigestsController do end
hadley/crantastic
spec/controllers/weekly_digests_controller_spec.rb
Ruby
mit
111
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<ii> vii; int pd[110][110] = {}; int choose(int a, int b) { if(pd[a][b]) return pd[a][b]; if(a==b) return 1; if(a<b) return 0; if(b==0) return 1; return pd[a][b] = choose(a-1,b)+choose(a-1,b-1); } int main () { int t; scanf("%d", &t); for(int caso = 1; caso <= t; caso++) { char s[255]; scanf("%s", s); vi m(50,0), M(50,0); int len = strlen(s); for(int i = 0; i < len; i++) { if(s[i] >= 'a' && s[i] <= 'z') m[s[i]-'a']++; if(s[i] >= 'A' && s[i] <= 'Z') M[s[i]-'A']++; } int resp = 1; for(int i = 0; i < 50; i++) { int p = choose(m[i]+M[i],m[i]); resp *= p; } printf("Caso #%d: %d\n", caso, resp-1); } return 0; }
matheuscarius/competitive-programming
maratonando/Seletiva UFPE 2016/e.cpp
C++
mit
839
//============================================================================ // Name : Code.cpp // Author : Yahya Milani // Version : // Copyright : Use as much as you like with author's name for noncommercial cases ONLY // Description : C++, Ansi-style //============================================================================ //#include <stdafx.h> #include <stdio.h> //#include <tchar.h> #include <cmath> #include <iostream> #include <fstream> #include <ctime> using namespace std; //Global Vars const int ele_num = 96; const int node_num = 35; const int bound_num = 4; const int boundary[4] = { 0, 3, 6, 7 }; //{ 2,3,5,6 }; const int DOF = 3; const int length = DOF * (node_num - bound_num); const double Ro = 1000; const double m = 782.7586; const double la = 7866.7; const double tF = 100; const double dt = 0.01; const double dt_save = 1; const int sparse_data = 2619; // Global Arrays //static double V[ele_num]; // // double Volume(double x[4], double y[4], double z[4]); void Jacobi(double x[4], double y[4], double z[4], double Vol, double J[16]); void shape_function(double B[ele_num * 6 * 12], double J[ele_num][4][4]); void transpose(double A[], int row_A, int col_A, double A_T[]); void Mass(double M[length * length], double V[ele_num], int ID_ele[ele_num * 4 * DOF]); void Stiffness(double B_ele[ele_num * 6 * 12], double B_eleT[ele_num * 12 * 6], double C[6][6], int ID_ele[4 * DOF * ele_num], double V[ele_num], double K[length][length]); void Multi(double **x, int Ix, int Jx, double **y, int Iy, int Jy); void SpVec(double *A_sp, int *RA_sp, int *CA_sp, double *b_vec, int length_vec); double VecVec(double *a, double *b, int n); void Solve(double A_sp[],int Col_A_sp[],int Row_A_sp[],double B[],double U[]); //double *Solve(double *A_sp, int *RA_sp, int *CA_sp, double *B, int length); //double **Material() int main() { //Read Nodes=================================================/ ifstream nodes; nodes.open("nodes.txt"); double node[node_num * DOF] = { }; //int row_node = node_num; int col_node = DOF; int i = 0; double data1, data2, data3, data0; while (nodes >> data0 >> data1 >> data2 >> data3) { node[i * col_node + 0] = data1; node[i * col_node + 1] = data2; node[i * col_node + 2] = data3; i += 1; } nodes.close(); //Create Nodes DOF =================================================/ int ID_node[node_num * DOF] = { }; int row_ID_node = node_num; int col_ID_node = DOF; int counter = 1; bool bound; for (int i = 0; i < row_ID_node; i++) { bound = 1; for (int j = 0; j < bound_num; j++) { if (i == boundary[j]) { bound = 0; } } if (bound == 1) { for (int k = 0; k < DOF; k++) ID_node[i * col_ID_node + k] = counter + k; counter += DOF; } else { for (int k = 0; k < DOF; k++) ID_node[i * col_ID_node + k] = 0; } } //Read Elements=================================================/ ifstream element; element.open("elements.txt"); i = 0; int ele[ele_num * 4] = { }; //int row_ele = ele_num; int col_ele = 4; int data4, data5, data6, data7, data00; while (element >> data00 >> data4 >> data5 >> data6 >> data7) { ele[i * col_ele + 0] = data4 - 1; ele[i * col_ele + 1] = data5 - 1; ele[i * col_ele + 2] = data6 - 1; ele[i * col_ele + 3] = data7 - 1; i += 1; } element.close(); //Create Elemental DOF =================================================/ int ID_ele[ele_num * 4 * DOF] = { }; int row_ID_ele = ele_num; int col_ID_ele = 4 * DOF; for (int i = 0; i < row_ID_ele; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < DOF; k++) { ID_ele[i * col_ID_ele + j * DOF + k] = ID_node[(ele[i * col_ele + j]) * col_ID_node + k]; } } } //=================================================/ double x[4], y[4], z[4]; double V[ele_num] = { }; double B[ele_num][4][4] = { }; //set B matrix and voulme for every element for (int i = 0; i < ele_num; i++) { for (int j = 0; j < 4; j++) { x[j] = node[(ele[i * col_ele + j]) * col_node + 0]; y[j] = node[(ele[i * col_ele + j]) * col_node + 1]; z[j] = node[(ele[i * col_ele + j]) * col_node + 2]; } // Compute Voulme of each element so that none has negative volume and change indexes if there is one V[i] = Volume(x, y, z); if (V[i] < 0) { double temp = x[2]; x[2] = x[3]; x[3] = temp; temp = y[2]; y[2] = y[3]; y[3] = temp; temp = z[2]; z[2] = z[3]; z[3] = temp; V[i] = Volume(x, y, z); // Change ID after changing elemnt indexes for (int i2 = 2 * DOF; i2 < 3 * DOF; i2++) { int temp2 = ID_ele[i * col_ID_ele + i2]; ID_ele[i * col_ID_ele + i2] = ID_ele[i * col_ID_ele + i2 + DOF]; ID_ele[i * col_ID_ele + i2 + DOF] = temp2; } } double J[16]; Jacobi(x, y, z, V[i], J); for (int var = 0; var < 4; ++var) { for (int var2 = 0; var2 < 4; ++var2) { B[i][var][var2] = J[var * 4 + var2]; } } } //For end of Geometrical issues======================================================== //===================================================================================== //===========================ALL Shit Happens Here===================================== //===================================================================================== double B_ele[ele_num * 6 * 12] = { }; int row_B_ele = 6; int col_B_ele = 12; shape_function(B_ele, B); double B_eleT[ele_num * 12 * 6] = { }; //int row_B_eleT = 12; //int col_B_eleT = 6; transpose(B_ele, row_B_ele, col_B_ele, B_eleT); double M[length * length] = { }; Mass(M, V, ID_ele); clock_t start; start = clock(); double K[length][length]; for (int n = 0; n < DOF * (node_num - bound_num); n++) { for (int n1 = 0; n1 < DOF * (node_num - bound_num); n1++) { K[n][n1] = 0; } } double C[6][6] = { { la + 2 * m, la, la, 0, 0, 0 }, { la, la + 2 * m, la, 0, 0, 0 }, { la, la, la + 2 * m, 0, 0, 0 }, { 0, 0, 0, m, 0, 0 }, { 0, 0, 0, 0, m, 0 }, { 0, 0, 0, 0, 0, m } }; Stiffness(B_ele, B_eleT, C,ID_ele,V, K); //===================================================================================== //===================================================================================== //===================================================================================== // how to implement counter2??????????????????? VERY IMPORTANT where should I define sparse matrixes double trace = 0; for (int i = 0; i < DOF * (node_num - bound_num); i++) { trace += K[i][i]; } //Sparsize K ============================================================/ /*static double K_sp[2619]; //[51484]; int RK_sp[DOF * (node_num - bound_num) + 1]; static int CK_sp[2619]; // [51484];*/ double K_sp[sparse_data]={}; //[51484]; int RK_sp[DOF * (node_num - bound_num) + 1]={}; int CK_sp[sparse_data]={}; // [51484]; double F[DOF * (node_num - bound_num)]={}; RK_sp[0] = 0; counter = 0; for (int i = 0; i < DOF * (node_num - bound_num); i++) { for (int j = 0; j < DOF * (node_num - bound_num); j++) { if (K[i][j] != 0) { K_sp[counter] = K[i][j]; CK_sp[counter] = j; counter += 1; } RK_sp[i + 1] = counter; } } cout << counter << "\n"; //Force ================================= F[56] = -1000; // F[686] = -1000; //Solve ================================= // for (int j = 0; j < length; j++) { double U[length]={}; Solve(K_sp,CK_sp,RK_sp,F,U); // } cout << "Bye Bye" << "\n"; double duration; duration = (clock() - start) / (double) CLOCKS_PER_SEC; cout << "time: " << duration << endl; return 0; } //===========================================================================================// double Volume(double x[4], double y[4], double z[4]) { double V; V = (x[0] * y[2] * z[1] - x[0] * y[1] * z[2] + x[1] * y[0] * z[2] - x[1] * y[2] * z[0] - x[2] * y[0] * z[1] + x[2] * y[1] * z[0] + x[0] * y[1] * z[3] - x[0] * y[3] * z[1] - x[1] * y[0] * z[3] + x[1] * y[3] * z[0] + x[3] * y[0] * z[1] - x[3] * y[1] * z[0] - x[0] * y[2] * z[3] + x[0] * y[3] * z[2] + x[2] * y[0] * z[3] - x[2] * y[3] * z[0] - x[3] * y[0] * z[2] + x[3] * y[2] * z[0] + x[1] * y[2] * z[3] - x[1] * y[3] * z[2] - x[2] * y[1] * z[3] + x[2] * y[3] * z[1] + x[3] * y[1] * z[2] - x[3] * y[2] * z[1]) / 6; return V; } void Jacobi(double x[4], double y[4], double z[4], double Vol, double J[16]) { J[0] = (x[1] * y[2] * z[3] - x[1] * y[3] * z[2] - x[2] * y[1] * z[3] + x[2] * y[3] * z[1] + x[3] * y[1] * z[2] - x[3] * y[2] * z[1]) / (6 * Vol); J[1] = (y[2] * z[1] - y[1] * z[2] + y[1] * z[3] - y[3] * z[1] - y[2] * z[3] + y[3] * z[2]) / (6 * Vol); J[2] = (x[1] * z[2] - x[2] * z[1] - x[1] * z[3] + x[3] * z[1] + x[2] * z[3] - x[3] * z[2]) / (6 * Vol); J[3] = (x[2] * y[1] - x[1] * y[2] + x[1] * y[3] - x[3] * y[1] - x[2] * y[3] + x[3] * y[2]) / (6 * Vol); J[4] = (x[0] * y[3] * z[2] - x[0] * y[2] * z[3] + x[2] * y[0] * z[3] - x[2] * y[3] * z[0] - x[3] * y[0] * z[2] + x[3] * y[2] * z[0]) / (6 * Vol); J[5] = (y[0] * z[2] - y[2] * z[0] - y[0] * z[3] + y[3] * z[0] + y[2] * z[3] - y[3] * z[2]) / (6 * Vol); J[6] = (x[2] * z[0] - x[0] * z[2] + x[0] * z[3] - x[3] * z[0] - x[2] * z[3] + x[3] * z[2]) / (6 * Vol); J[7] = (x[0] * y[2] - x[2] * y[0] - x[0] * y[3] + x[3] * y[0] + x[2] * y[3] - x[3] * y[2]) / (6 * Vol); J[8] = (x[0] * y[1] * z[3] - x[0] * y[3] * z[1] - x[1] * y[0] * z[3] + x[1] * y[3] * z[0] + x[3] * y[0] * z[1] - x[3] * y[1] * z[0]) / (6 * Vol); J[9] = (y[1] * z[0] - y[0] * z[1] + y[0] * z[3] - y[3] * z[0] - y[1] * z[3] + y[3] * z[1]) / (6 * Vol); J[10] = (x[0] * z[1] - x[1] * z[0] - x[0] * z[3] + x[3] * z[0] + x[1] * z[3] - x[3] * z[1]) / (6 * Vol); J[11] = (x[1] * y[0] - x[0] * y[1] + x[0] * y[3] - x[3] * y[0] - x[1] * y[3] + x[3] * y[1]) / (6 * Vol); J[12] = (x[0] * y[2] * z[1] - x[0] * y[1] * z[2] + x[1] * y[0] * z[2] - x[1] * y[2] * z[0] - x[2] * y[0] * z[1] + x[2] * y[1] * z[0]) / (6 * Vol); J[13] = (y[0] * z[1] - y[1] * z[0] - y[0] * z[2] + y[2] * z[0] + y[1] * z[2] - y[2] * z[1]) / (6 * Vol); J[14] = (x[1] * z[0] - x[0] * z[1] + x[0] * z[2] - x[2] * z[0] - x[1] * z[2] + x[2] * z[1]) / (6 * Vol); J[15] = (x[0] * y[1] - x[1] * y[0] - x[0] * y[2] + x[2] * y[0] + x[1] * y[2] - x[2] * y[1]) / (6 * Vol); } void shape_function(double B[ele_num * 6 * 12], double J[ele_num][4][4]) { int row_B = 6; int col_B = 12; for (int k = 0; k < ele_num; k++) { //B[col_B*row_B*k+col_B*i+j] [k][i][j] B[col_B * row_B * k + col_B * 0 + 0] = J[k][0][1]; B[col_B * row_B * k + col_B * 0 + 3] = J[k][1][1]; B[col_B * row_B * k + col_B * 0 + 6] = J[k][2][1]; B[col_B * row_B * k + col_B * 0 + 9] = J[k][3][1]; B[col_B * row_B * k + col_B * 1 + 1] = J[k][0][2]; B[col_B * row_B * k + col_B * 1 + 4] = J[k][1][2]; B[col_B * row_B * k + col_B * 1 + 7] = J[k][2][2]; B[col_B * row_B * k + col_B * 1 + 10] = J[k][3][2]; B[col_B * row_B * k + col_B * 2 + 2] = J[k][0][3]; B[col_B * row_B * k + col_B * 2 + 5] = J[k][1][3]; B[col_B * row_B * k + col_B * 2 + 8] = J[k][2][3]; B[col_B * row_B * k + col_B * 2 + 11] = J[k][3][3]; B[col_B * row_B * k + col_B * 3 + 0] = J[k][0][2]; B[col_B * row_B * k + col_B * 3 + 3] = J[k][1][2]; B[col_B * row_B * k + col_B * 3 + 6] = J[k][2][2]; B[col_B * row_B * k + col_B * 3 + 9] = J[k][3][2]; B[col_B * row_B * k + col_B * 3 + 1] = J[k][0][1]; B[col_B * row_B * k + col_B * 3 + 4] = J[k][1][1]; B[col_B * row_B * k + col_B * 3 + 7] = J[k][2][1]; B[col_B * row_B * k + col_B * 3 + 10] = J[k][3][1]; B[col_B * row_B * k + col_B * 4 + 1] = J[k][0][3]; B[col_B * row_B * k + col_B * 4 + 4] = J[k][1][3]; B[col_B * row_B * k + col_B * 4 + 7] = J[k][2][3]; B[col_B * row_B * k + col_B * 4 + 10] = J[k][3][3]; B[col_B * row_B * k + col_B * 4 + 2] = J[k][0][2]; B[col_B * row_B * k + col_B * 4 + 5] = J[k][1][2]; B[col_B * row_B * k + col_B * 4 + 8] = J[k][2][2]; B[col_B * row_B * k + col_B * 4 + 11] = J[k][3][2]; B[col_B * row_B * k + col_B * 5 + 0] = J[k][0][3]; B[col_B * row_B * k + col_B * 5 + 3] = J[k][1][3]; B[col_B * row_B * k + col_B * 5 + 6] = J[k][2][3]; B[col_B * row_B * k + col_B * 5 + 9] = J[k][3][3]; B[col_B * row_B * k + col_B * 5 + 2] = J[k][0][1]; B[col_B * row_B * k + col_B * 5 + 5] = J[k][1][1]; B[col_B * row_B * k + col_B * 5 + 8] = J[k][2][1]; B[col_B * row_B * k + col_B * 5 + 11] = J[k][3][1]; } } void transpose(double A[], int row_A, int col_A, double A_T[]) { for (int k = 0; k < ele_num; k++) { for (int i = 0; i < col_A; i++) { for (int j = 0; j < row_A; j++) { A_T[row_A * col_A * k + row_A * i + j] = A[row_A * col_A * k + col_A * j + i]; } } } } void Mass(double M[length * length], double V[ele_num], int ID_ele[ele_num * 4 * DOF]) { int col_ID_ele = 4 * DOF; for (int i = 0; i < ele_num; i++) { double m2[12 * 12] = { }; for (int j = 0; j < 12; j++) { m2[j * 12 + j] = Ro * V[i] / 4; } for (int j = 0; j < DOF * 4; j++) { for (int k = 0; k < DOF * 4; k++) { if (ID_ele[i * col_ID_ele + j] != 0 && ID_ele[i * col_ID_ele + k] != 0) M[(ID_ele[i * col_ID_ele + j] - 1) * length + (ID_ele[i * col_ID_ele + k] - 1)] += m2[j * 12 + k]; } } } } void Stiffness(double B_ele[ele_num * 6 * 12], double B_eleT[ele_num * 12 * 6], double C[6][6], int ID_ele[4 * DOF * ele_num], double V[ele_num], double K[length][length]) { int row_B_ele = 6; int col_B_ele = 12; int row_B_eleT = 12; int col_B_eleT = 6; int col_ID_ele = 4 * DOF; for (int i = 0; i < ele_num; i++) { double K1[12][6]; double sum = 0; for (int i2 = 0; i2 < 12; i2++) { for (int j2 = 0; j2 < 6; j2++) { for (int k2 = 0; k2 < 6; k2++) { sum += B_eleT[col_B_eleT * row_B_eleT * i + col_B_eleT * i2 + k2] * C[k2][j2]; // *(*(*(B_minT + i2) + k2))*(*(*(C + k2) + j2)); } K1[i2][j2] = sum; sum = 0; } } double K2[12][12]; sum = 0; for (int i2 = 0; i2 < 12; i2++) { for (int j2 = 0; j2 < 12; j2++) { for (int k2 = 0; k2 < 6; k2++) { sum += K1[i2][k2] * B_ele[col_B_ele * row_B_ele * i + col_B_ele * k2 + j2] * V[i]; //(*(*(K1 + i2) + k2))*(*(*(B_min + k2) + j2))*V[i]; } K2[i2][j2] = sum; sum = 0; } } for (int n = 0; n < DOF * 4; n++) { for (int n1 = 0; n1 < DOF * 4; n1++) { if (ID_ele[i * col_ID_ele + n] != 0 && ID_ele[i * col_ID_ele + n1] != 0) K[(ID_ele[i * col_ID_ele + n] - 1)][(ID_ele[i * col_ID_ele + n1] - 1)] += K2[n][n1]; } } } int counter2 = 0; for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (K[i][j] != 0) { counter2 += 1; } } } } void Multi2(double **x, int Ix, int Jx, double **y, int Iy, int Jy, double **z) { //Rerurns x*y & Jx=Iy double sum = 0; for (int i = 0; i < Ix; i++) { for (int j = 0; j < Jy; j++) { for (int k = 0; k < Iy; k++) { sum += (*(*(x + i) + k)) * (*(*(y + k) + j)); } // cout<<sum<<"\n"; *(*(z + i) + j) = sum; sum = 0; } } } void Multi(double **x, int Ix, int Jx, double **y, int Iy, int Jy) { //Rerurns x*y & Jx=Iy double sum = 0; double **R; R = new double *[Ix]; for (int i = 0; i < Ix; i++) R[i] = new double[Jy]; for (int i = 0; i < Ix; i++) { for (int j = 0; j < Jy; j++) { for (int k = 0; k < Iy; k++) { sum += (*(*(x + i) + k)) * (*(*(y + k) + j)); } // cout<<sum<<"\n"; *(*(R + i) + j) = sum; sum = 0; } } } void SpVec(double *A_sp, int *RA_sp, int *CA_sp, double *b_vec, int length_vec) { //returns A*b //static double C[1416]; //define it cause it's not a good idea to return local variable adress double sum = 0; for (int i = 0; i < length_vec; i++) { for (int j = *(RA_sp + i); j < *(RA_sp + i + 1); j++) { sum += *(b_vec + *(CA_sp + j)) * (*(A_sp + j)); } //cout<<sum<<"\n"; // C[i] = sum; sum = 0; } //return C; } double VecVec(double *a, double *b, int n) { static double L; L = 0; for (int i = 0; i < n; i++) L += *(a + i) * (*(b + i)); return L; } //==================================================================== void Solve(double A_sp[],int Col_A_sp[],int Row_A_sp[],double B[],double U[]) { double p[length]; double r[length]; // double U[length]; double t[length]; double rho = 0; double rhos; double alpha; double error=0.2; bool solved = 0; for (int i = 0; i < length; i++) { p[i] = B[i]; r[i] = B[i]; // U[i] = 0; } for (int i = 0; i < length; i++) { rho += r[i] * r[i]; } cout << "rho " << rho << "\n"; for (int j = 0; j < length; j++) { if (solved == 0) { double sum = 0; for (int i = 0; i < length; i++) { for (int k = Row_A_sp[i]; k < Row_A_sp[i + 1]; k++) { sum += (p[Col_A_sp[k]]) * (A_sp[k]); } t[i] = sum; sum = 0; } double PT = 0; for (int i = 0; i < length; i++) { PT += p[i] * t[i]; } alpha = rho / PT; for (int i = 0; i < length; i++) { U[i] += alpha * p[i]; r[i] -= alpha * t[i]; } rhos = rho; rho = 0; for (int i = 0; i < length; i++) { rho += r[i] * r[i]; } if ((rho / rhos) < error) { solved = 1; cout<<endl << "Solved in "<< j<<" Steps!" << "\n"; } for (int i = 0; i < length; i++) { p[i] = r[i] + (rho / rhos) * p[i]; } } } cout << "U(56)= " << *(U + 56) << "\n" << "\n"; }
yahya-milani/Parallel-FEM
src/Static.cpp
C++
mit
17,272
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.Cryptography.ECC; namespace Neo.IO.Caching { internal class ECPointCache : FIFOCache<byte[], ECPoint> { public ECPointCache(int max_capacity) : base(max_capacity, ByteArrayEqualityComparer.Default) { } protected override byte[] GetKeyForItem(ECPoint item) { return item.EncodePoint(true); } } }
AntShares/AntShares
src/neo/IO/Caching/ECPointCache.cs
C#
mit
771
(function () { 'use strict'; angular .module('patients') .controller('PatientsListController', PatientsListController); PatientsListController.$inject = ['PatientsService']; function PatientsListController(PatientsService) { var vm = this; vm.patients = PatientsService.query(); } })();
anshuman-singh-93/patient-crud-simple-app
modules/patients/client/controllers/list-patients.client.controller.js
JavaScript
mit
317
// Polyfills // (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here) // import 'ie-shim'; // Internet Explorer // import 'es6-shim'; // import 'es6-promise'; // import 'es7-reflect-metadata'; // Prefer CoreJS over the polyfills above require('core-js'); require('zone.js/dist/zone'); if ('production' === ENV) { } else { // Development Error.stackTraceLimit = Infinity; require('zone.js/dist/long-stack-trace-zone'); } //# sourceMappingURL=polyfills.js.map
karnex47/iaa
src/polyfills.js
JavaScript
mit
508
require 'time_crisis/tzinfo/timezone_definition' module TimeCrisis::TZInfo module Definitions module Asia module Tehran include TimezoneDefinition timezone 'Asia/Tehran' do |tz| tz.offset :o0, 12344, 0, :LMT tz.offset :o1, 12344, 0, :TMT tz.offset :o2, 12600, 0, :IRST tz.offset :o3, 14400, 0, :IRST tz.offset :o4, 14400, 3600, :IRDT tz.offset :o5, 12600, 3600, :IRDT tz.transition 1915, 12, :o1, 26145324257, 10800 tz.transition 1945, 12, :o2, 26263670657, 10800 tz.transition 1977, 10, :o3, 247177800 tz.transition 1978, 3, :o4, 259272000 tz.transition 1978, 10, :o3, 277758000 tz.transition 1978, 12, :o2, 283982400 tz.transition 1979, 3, :o5, 290809800 tz.transition 1979, 9, :o2, 306531000 tz.transition 1980, 3, :o5, 322432200 tz.transition 1980, 9, :o2, 338499000 tz.transition 1991, 5, :o5, 673216200 tz.transition 1991, 9, :o2, 685481400 tz.transition 1992, 3, :o5, 701209800 tz.transition 1992, 9, :o2, 717103800 tz.transition 1993, 3, :o5, 732745800 tz.transition 1993, 9, :o2, 748639800 tz.transition 1994, 3, :o5, 764281800 tz.transition 1994, 9, :o2, 780175800 tz.transition 1995, 3, :o5, 795817800 tz.transition 1995, 9, :o2, 811711800 tz.transition 1996, 3, :o5, 827353800 tz.transition 1996, 9, :o2, 843247800 tz.transition 1997, 3, :o5, 858976200 tz.transition 1997, 9, :o2, 874870200 tz.transition 1998, 3, :o5, 890512200 tz.transition 1998, 9, :o2, 906406200 tz.transition 1999, 3, :o5, 922048200 tz.transition 1999, 9, :o2, 937942200 tz.transition 2000, 3, :o5, 953584200 tz.transition 2000, 9, :o2, 969478200 tz.transition 2001, 3, :o5, 985206600 tz.transition 2001, 9, :o2, 1001100600 tz.transition 2002, 3, :o5, 1016742600 tz.transition 2002, 9, :o2, 1032636600 tz.transition 2003, 3, :o5, 1048278600 tz.transition 2003, 9, :o2, 1064172600 tz.transition 2004, 3, :o5, 1079814600 tz.transition 2004, 9, :o2, 1095708600 tz.transition 2005, 3, :o5, 1111437000 tz.transition 2005, 9, :o2, 1127331000 tz.transition 2008, 3, :o5, 1206045000 tz.transition 2008, 9, :o2, 1221939000 tz.transition 2009, 3, :o5, 1237667400 tz.transition 2009, 9, :o2, 1253561400 tz.transition 2010, 3, :o5, 1269203400 tz.transition 2010, 9, :o2, 1285097400 tz.transition 2011, 3, :o5, 1300739400 tz.transition 2011, 9, :o2, 1316633400 tz.transition 2012, 3, :o5, 1332275400 tz.transition 2012, 9, :o2, 1348169400 tz.transition 2013, 3, :o5, 1363897800 tz.transition 2013, 9, :o2, 1379791800 tz.transition 2014, 3, :o5, 1395433800 tz.transition 2014, 9, :o2, 1411327800 tz.transition 2015, 3, :o5, 1426969800 tz.transition 2015, 9, :o2, 1442863800 tz.transition 2016, 3, :o5, 1458505800 tz.transition 2016, 9, :o2, 1474399800 tz.transition 2017, 3, :o5, 1490128200 tz.transition 2017, 9, :o2, 1506022200 tz.transition 2018, 3, :o5, 1521664200 tz.transition 2018, 9, :o2, 1537558200 tz.transition 2019, 3, :o5, 1553200200 tz.transition 2019, 9, :o2, 1569094200 tz.transition 2020, 3, :o5, 1584736200 tz.transition 2020, 9, :o2, 1600630200 tz.transition 2021, 3, :o5, 1616358600 tz.transition 2021, 9, :o2, 1632252600 tz.transition 2022, 3, :o5, 1647894600 tz.transition 2022, 9, :o2, 1663788600 tz.transition 2023, 3, :o5, 1679430600 tz.transition 2023, 9, :o2, 1695324600 tz.transition 2024, 3, :o5, 1710966600 tz.transition 2024, 9, :o2, 1726860600 tz.transition 2025, 3, :o5, 1742589000 tz.transition 2025, 9, :o2, 1758483000 tz.transition 2026, 3, :o5, 1774125000 tz.transition 2026, 9, :o2, 1790019000 tz.transition 2027, 3, :o5, 1805661000 tz.transition 2027, 9, :o2, 1821555000 tz.transition 2028, 3, :o5, 1837197000 tz.transition 2028, 9, :o2, 1853091000 tz.transition 2029, 3, :o5, 1868733000 tz.transition 2029, 9, :o2, 1884627000 tz.transition 2030, 3, :o5, 1900355400 tz.transition 2030, 9, :o2, 1916249400 tz.transition 2031, 3, :o5, 1931891400 tz.transition 2031, 9, :o2, 1947785400 tz.transition 2032, 3, :o5, 1963427400 tz.transition 2032, 9, :o2, 1979321400 tz.transition 2033, 3, :o5, 1994963400 tz.transition 2033, 9, :o2, 2010857400 tz.transition 2034, 3, :o5, 2026585800 tz.transition 2034, 9, :o2, 2042479800 tz.transition 2035, 3, :o5, 2058121800 tz.transition 2035, 9, :o2, 2074015800 tz.transition 2036, 3, :o5, 2089657800 tz.transition 2036, 9, :o2, 2105551800 tz.transition 2037, 3, :o5, 2121193800 tz.transition 2037, 9, :o2, 2137087800 end end end end end
ttilley/time_crisis
lib/time_crisis/tzinfo/definitions/Asia/Tehran.rb
Ruby
mit
5,409
<script type="text/javascript"> function changeKotaKab(){ var select_provinsi = $("#select_provinsi").val(); $.ajax({ url: "<?php echo base_url('index.php/kecamatan/selectkotakab' ); ?>/" + select_provinsi, success: function(result) { $("#select_kota_kab").html(result); } }); } </script> <div class="content-wrapper"> <section class="content-header"> <h1 style="padding-bottom: 15px;"> Edit Kecamatan </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="#">Wilayah</a></li> <li class="active"><a href="#">Edit Kecamatan</a></li> </ol> </section> <div class="padding-md"> <div class="panel "> <?php if(isset($message)){ ?> <div class="alert alert-danger"> <label><strong><?php echo $message; ?></strong></label> </div> <?php } ?> <div class="panel-heading"> </div> <div class="panel-body"> <?php echo form_open('kecamatan/prosesUpdate', array('class'=>'form-horizontal','method'=>'post'));?> <div class="form-group"> <label class="col-sm-3 control-label">Nama Provinsi</label> <div class="col-lg-5"> <select class="form-control input-sm" id="select_provinsi" onChange="changeKotaKab(this.val);"> <option value="0">-- Pilih Provinsi --</option> <?php foreach ($provinces->result() as $row) { $selected = $row->id_provinsi == $kota_selected['id_provinsi'] ? "selected" : "" ; ?> <option <?php echo $selected; ?> value="<?php echo $row->id_provinsi;?>"><?php echo $row->nama_provinsi;?></option> <?php }?> </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Nama Kota</label> <div class="col-lg-5"> <select class="form-control input-sm" id="select_kota_kab" name="id_kota_kab" > <?php foreach ($kota as $row) { $selected = $row['id_kota_kab'] == $kecamatan_selected['id_kota_kab'] ? "selected" : "" ; ?> <option <?php echo $selected; ?> value="<?php echo $row['id_kota_kab'];?>"><?php echo $row['nama_kota_kab'];?></option> <?php }?> </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Nama Kecamatan</label> <div class="col-lg-5"> <input type="text" name="nama_kecamatan" class="form-control input-sm" value="<?php echo $kecamatan_selected['nama_kecamatan']; ?>" placeholder="Nama Kecamatan"> <input type="hidden" name="id_kecamatan" value="<?php echo $kecamatan_selected['id_kecamatan']; ?>" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label"></label> <div class="col-lg-5"> <button type="submit" class="btn btn-success btn-sm">Tambah</button> </div> </div> </div> </div> </div> </div>
andie87/MOUSystem
application/modules/kecamatan/views/edit.php
PHP
mit
3,133
/* * Nana GUI Programming Interface Implementation * Nana C++ Library(http://www.nanapro.org) * Copyright(C) 2003-2015 Jinhao(cnjinhao@hotmail.com) * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * @file: nana/gui/programming_interface.hpp */ #ifndef NANA_GUI_PROGRAMMING_INTERFACE_HPP #define NANA_GUI_PROGRAMMING_INTERFACE_HPP #include <nana/config.hpp> #include "detail/bedrock.hpp" #include "effects.hpp" #include "detail/general_events.hpp" #include <nana/paint/image.hpp> #include <memory> namespace nana { class drawer_trigger; class widget; namespace dev { /// Traits for widget classes template<typename Widget> struct widget_traits { using event_type = ::nana::general_events; using scheme_type = ::nana::widget_colors; }; } namespace API { void effects_edge_nimbus(window, effects::edge_nimbus); effects::edge_nimbus effects_edge_nimbus(window); void effects_bground(window, const effects::bground_factory_interface&, double fade_rate); bground_mode effects_bground_mode(window); void effects_bground_remove(window); //namespace dev //@brief: The interfaces defined in namespace dev are used for developing the nana.gui namespace dev { bool set_events(window, const std::shared_ptr<general_events>&); template<typename Scheme> std::unique_ptr<Scheme> make_scheme() { return std::unique_ptr<Scheme>( static_cast<Scheme*>(::nana::detail::bedrock::instance().make_scheme(::nana::detail::scheme_factory<Scheme>()).release())); } void set_scheme(window, widget_colors*); widget_colors* get_scheme(window); void attach_drawer(widget&, drawer_trigger&); nana::string window_caption(window) throw(); void window_caption(window, nana::string); window create_window(window, bool nested, const rectangle&, const appearance&, widget* attached); window create_widget(window, const rectangle&, widget* attached); window create_lite_widget(window, const rectangle&, widget* attached); window create_frame(window, const rectangle&, widget* attached); paint::graphics* window_graphics(window); void delay_restore(bool); }//end namespace dev namespace detail { general_events* get_general_events(window); }//end namespace detail void exit(); nana::string transform_shortkey_text(nana::string text, nana::string::value_type &shortkey, nana::string::size_type *skpos); bool register_shortkey(window, unsigned long); void unregister_shortkey(window); nana::point cursor_position(); rectangle make_center(unsigned width, unsigned height); ///< Retrieves a rectangle which is in the center of the screen. rectangle make_center(window, unsigned width, unsigned height); ///< Retrieves a rectangle which is in the center of the window template<typename Widget=::nana::widget, typename EnumFunction> void enum_widgets(window wd, bool recursive, EnumFunction && ef) { static_assert(std::is_convertible<Widget, ::nana::widget>::value, "enum_widgets<Widget>: The specified Widget is not a widget type."); typedef ::nana::detail::basic_window core_window_t; auto & brock = ::nana::detail::bedrock::instance(); internal_scope_guard lock; auto children = brock.wd_manager.get_children(reinterpret_cast<core_window_t*>(wd)); for (auto child : children) { auto wgt = dynamic_cast<Widget*>(brock.wd_manager.get_widget(child)); if (nullptr == wgt) continue; ef(*wgt); if (recursive) enum_widgets<Widget>(wd, recursive, std::forward<EnumFunction>(ef)); } } void window_icon_default(const paint::image& small_icon, const paint::image& big_icon = {}); void window_icon(window, const paint::image& small_icon, const paint::image& big_icon = {}); bool empty_window(window); ///< Determines whether a window is existing. bool is_window(window); ///< Determines whether a window is existing, equal to !empty_window. bool is_destroying(window); ///< Determines whether a window is destroying void enable_dropfiles(window, bool); /// \brief Retrieves the native window of a Nana.GUI window. /// /// The native window type is platform-dependent. Under Microsoft Windows, a conversion can be employed between /// nana::native_window_type and HWND through reinterpret_cast operator. Under X System, a conversion can /// be employed between nana::native_window_type and Window through reinterpret_cast operator. /// \return If the function succeeds, the return value is the native window handle to the Nana.GUI window. If fails return zero. native_window_type root(window); window root(native_window_type); ///< Retrieves the native window of a Nana.GUI window. void fullscreen(window, bool); bool enabled_double_click(window, bool); bool insert_frame(window frame, native_window_type); native_window_type frame_container(window frame); native_window_type frame_element(window frame, unsigned index); void close_window(window); void show_window(window, bool show); ///< Sets a window visible state. void restore_window(window); void zoom_window(window, bool ask_for_max); bool visible(window); window get_parent_window(window); window get_owner_window(window); bool set_parent_window(window, window new_parent); template<typename Widget=::nana::widget> typename ::nana::dev::widget_traits<Widget>::event_type & events(window wd) { using event_type = typename ::nana::dev::widget_traits<Widget>::event_type; internal_scope_guard lock; auto * general_evt = detail::get_general_events(wd); if (nullptr == general_evt) throw std::invalid_argument("API::events(): bad parameter window handle, no events object or invalid window handle."); if (std::is_same<::nana::general_events, event_type>::value) return *static_cast<event_type*>(general_evt); auto * widget_evt = dynamic_cast<event_type*>(general_evt); if (nullptr == widget_evt) throw std::invalid_argument("API::events(): bad template parameter Widget, the widget type and window handle do not match."); return *widget_evt; } template<typename EventArg, typename std::enable_if<std::is_base_of< ::nana::event_arg, EventArg>::value>::type* = nullptr> bool emit_event(event_code evt_code, window wd, const EventArg& arg) { auto & brock = ::nana::detail::bedrock::instance(); return brock.emit(evt_code, reinterpret_cast< ::nana::detail::bedrock::core_window_t*>(wd), arg, true, brock.get_thread_context()); } void umake_event(event_handle); template<typename Widget = ::nana::widget> typename ::nana::dev::widget_traits<Widget>::scheme_type & scheme(window wd) { using scheme_type = typename ::nana::dev::widget_traits<Widget>::scheme_type; internal_scope_guard lock; auto * wdg_colors = dev::get_scheme(wd); if (nullptr == wdg_colors) throw std::invalid_argument("API::scheme(): bad parameter window handle, no events object or invalid window handle."); if (std::is_same<::nana::widget_colors, scheme_type>::value) return *static_cast<scheme_type*>(wdg_colors); auto * comp_wdg_colors = dynamic_cast<scheme_type*>(wdg_colors); if (nullptr == comp_wdg_colors) throw std::invalid_argument("API::scheme(): bad template parameter Widget, the widget type and window handle do not match."); return *comp_wdg_colors; } point window_position(window); void move_window(window, int x, int y); void move_window(window wd, const rectangle&); void bring_top(window, bool activated); bool set_window_z_order(window wd, window wd_after, z_order_action action_if_no_wd_after); void draw_through(window, std::function<void()>); void map_through_widgets(window, native_drawable_type); size window_size(window); void window_size(window, const size&); size window_outline_size(window); void window_outline_size(window, const size&); bool get_window_rectangle(window, rectangle&); bool track_window_size(window, const size&, bool true_for_max); ///< Sets the minimum or maximum tracking size of a window. void window_enabled(window, bool); bool window_enabled(window); /** @brief A widget drawer draws the widget surface in answering an event. * * This function will tell the drawer to copy the graphics into window after event answering. * Tells Nana.GUI to copy the buffer of event window to screen after the event is processed. * This function only works for a drawer_trigger, when a drawer_trigger receives an event, * after drawing, a drawer_trigger should call lazy_refresh to tell the Nana.GUI to refresh * the window to the screen after the event process finished. */ void lazy_refresh(); /** @brief: calls refresh() of a widget's drawer. if currently state is lazy_refresh, Nana.GUI may paste the drawing on the window after an event processing. * @param window: specify a window to be refreshed. */ void refresh_window(window); ///< Refreshs the window and display it immediately calling the refresh method of its drawer_trigger.. void refresh_window_tree(window); ///< Refreshs the specified window and all it’s children windows, then display it immediately void update_window(window); ///< Copies the off-screen buffer to the screen for immediate display. void window_caption(window, const std::string& title_utf8); void window_caption(window, const nana::string& title); nana::string window_caption(window); void window_cursor(window, cursor); cursor window_cursor(window); void activate_window(window); bool is_focus_ready(window); window focus_window(); void focus_window(window); window capture_window(); window capture_window(window, bool); ///< Enables or disables the window to grab the mouse input void capture_ignore_children(bool ignore); ///< Enables or disables the captured window whether redirects the mouse input to its children if the mouse is over its children. void modal_window(window); ///< Blocks the routine til the specified window is closed. void wait_for(window); color fgcolor(window); color fgcolor(window, const color&); color bgcolor(window); color bgcolor(window, const color&); color activated_color(window); color activated_color(window, const color&); void create_caret(window, unsigned width, unsigned height); void destroy_caret(window); void caret_effective_range(window, const rectangle&); void caret_pos(window, const ::nana::point&); nana::point caret_pos(window); nana::size caret_size(window); void caret_size(window, const size&); void caret_visible(window, bool is_show); bool caret_visible(window); void tabstop(window); ///< Sets the window that owns the tabstop. /// treu: The focus is not to be changed when Tab key is pressed, and a key_char event with tab will be generated. void eat_tabstop(window, bool); window move_tabstop(window, bool next); ///< Sets the focus to the window which tabstop is near to the specified window. bool glass_window(window); /// \deprecated bool glass_window(window, bool); /// \deprecated /// Sets the window active state. If a window active state is false, the window will not obtain the focus when a mouse clicks on it wich will be obteined by take_if_has_active_false. void take_active(window, bool has_active, window take_if_has_active_false); bool window_graphics(window, nana::paint::graphics&); bool root_graphics(window, nana::paint::graphics&); bool get_visual_rectangle(window, nana::rectangle&); void typeface(window, const nana::paint::font&); paint::font typeface(window); bool calc_screen_point(window, point&); ///<Converts window coordinates to screen coordinates bool calc_window_point(window, point&); ///<Converts screen coordinates to window coordinates. window find_window(const nana::point& mspos); void register_menu_window(window, bool has_keyboard); bool attach_menubar(window menubar); void detach_menubar(window menubar); bool is_window_zoomed(window, bool ask_for_max); ///<Tests a window whether it is maximized or minimized. void widget_borderless(window, bool); ///<Enables or disables a borderless widget. bool widget_borderless(window); ///<Tests a widget whether it is borderless. nana::mouse_action mouse_action(window); nana::element_state element_state(window); bool ignore_mouse_focus(window, bool ignore); ///< Enables/disables the mouse focus, it returns the previous state bool ignore_mouse_focus(window); ///< Determines whether the mouse focus is enabled }//end namespace API }//end namespace nana #endif
Greentwip/Windy
3rdparty/nana/include/nana/gui/programming_interface.hpp
C++
mit
12,662
<?php use google\appengine\api\users\User; use google\appengine\api\users\UserService; $user = UserService::getCurrentUser(); if (isset($user)) { /* echo sprintf('<li>Welcome, %s! (<a href="%s">sign out</a>)', $user->getNickname(), UserService::createLogoutUrl('/')); */ $url = UserService::createLogoutUrl('index.php'); // แสดงภาพผใู้ช ้โดยการเรยี กฟังกช์ นั userpic จากข ้อที่ 1 ?> <?php if(UserService::isCurrentUserAdmin()){ include("menu_admin.php"); } } else { echo sprintf('<li><a href="%s">Sign in or register</a>', UserService::createLoginUrl('/')); } ?>
Autchariyakk/web592group08
admin.php
PHP
mit
735
<TS language="vi_VN" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Nhấn chuột phải để sửa địa chỉ hoặc nhãn</translation> </message> <message> <source>Create a new address</source> <translation>Tạo một địa chỉ mới</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Tạo mới</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copy địa chỉ được chọn vào clipboard</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copy</translation> </message> <message> <source>C&amp;lose</source> <translation>Đó&amp;ng</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Xóa địa chỉ hiện tại từ danh sách</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Xuất dữ liệu trong mục hiện tại ra file</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Xuất</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Xóa</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Chọn địa chỉ để gửi coin đến</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Chọn địa chỉ để nhận coin</translation> </message> <message> <source>C&amp;hoose</source> <translation>Chọn</translation> </message> <message> <source>Sending addresses</source> <translation>Địa chỉ gửi đến</translation> </message> <message> <source>Receiving addresses</source> <translation>Địa chỉ nhận</translation> </message> <message> <source>These are your Peercoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Đây là các địa chỉ Peercoin để gửi bạn gửi tiền. Trước khi gửi bạn nên kiểm tra lại số tiền bạn muốn gửi và địa chỉ peercoin của người nhận.</translation> </message> <message> <source>These are your Peercoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Đây là các địa chỉ Peercoin để bạn nhận tiền. Với mỗi giao dịch, bạn nên dùng một địa chỉ Peercoin mới để nhận tiền.</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Chép Địa chỉ</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Chép &amp;Nhãn</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Sửa</translation> </message> <message> <source>Export Address List</source> <translation>Xuất Danh Sách Địa Chỉ</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Các tệp tác nhau bằng đấu phẩy (* .csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Xuất không thành công</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Nhãn</translation> </message> <message> <source>Address</source> <translation>Địa chỉ</translation> </message> <message> <source>(no label)</source> <translation>(không nhãn)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Hội thoại Passphrase</translation> </message> <message> <source>Enter passphrase</source> <translation>Điền passphrase</translation> </message> <message> <source>New passphrase</source> <translation>Passphrase mới</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Điền lại passphrase</translation> </message> <message> <source>Show password</source> <translation>Hiện mật khẩu</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Nhập passphrase mới cho Ví của bạn.&lt;br/&gt;Vui long dùng passphrase gồm&lt;b&gt;ít nhất 10 ký tự bất kỳ &lt;/b&gt;, hoặc &lt;b&gt;ít nhất 8 chữ&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Mã hóa ví</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Thao tác này cần cụm từ mật khẩu để mở khóa ví.</translation> </message> <message> <source>Unlock wallet</source> <translation>Mở khóa ví</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Thao tác này cần cụm mật khẩu ví của bạn để giải mã ví.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Giải mã ví</translation> </message> <message> <source>Change passphrase</source> <translation>Đổi cụm mật khẩu</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Nhập cụm từ mật khẩu cũ và cụm mật khẩu mới vào ví.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Xác nhận mã hóa ví</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Bạn có chắc chắn muốn mã hóa ví của bạn?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Ví đã được mã hóa</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>QUAN TRỌNG: Bất kỳ bản sao lưu trước nào bạn đã làm từ tệp ví tiền của bạn phải được thay thế bằng tệp ví tiền mới được tạo và mã hóa. Vì lý do bảo mật, các bản sao lưu trước đó của tệp ví tiền không được mã hóa sẽ trở nên vô dụng ngay khi bạn bắt đầu sử dụng ví đã được mã hóa.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Mã hóa ví không thành công</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Mã hóa ví không thành công do có lỗi bên trong. Ví của bạn chưa được mã hóa.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>Cụm mật khẩu được cung cấp không khớp.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Mở khóa ví không thành công</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Cụm từ mật mã nhập vào không đúng</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Giải mã ví không thành công</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Cụm từ mật khẩu mã hóa của ví đã được thay đổi.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Chú ý: Caps Lock đang được bật!</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Netmask</translation> </message> <message> <source>Banned Until</source> <translation>Bị cấm đến</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Chứ ký &amp; Tin nhắn...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Đồng bộ hóa với mạng</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Tổng quan</translation> </message> <message> <source>Node</source> <translation>Node</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Hiện thỉ thông tin sơ lược chung về Ví</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Giao dịch</translation> </message> <message> <source>Browse transaction history</source> <translation>Duyệt tìm lịch sử giao dịch</translation> </message> <message> <source>E&amp;xit</source> <translation>T&amp;hoát</translation> </message> <message> <source>Quit application</source> <translation>Thoát chương trình</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;Thông tin về %1</translation> </message> <message> <source>Show information about %1</source> <translation>Hiện thông tin về %1</translation> </message> <message> <source>About &amp;Qt</source> <translation>Về &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Xem thông tin về Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Tùy chọn...</translation> </message> <message> <source>Modify configuration options for %1</source> <translation>Chỉnh sửa thiết đặt tùy chọn cho %1</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Mã hóa ví tiền</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Sao lưu ví tiền...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Thay đổi mật khẩu...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Địa chỉ gửi</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Địa chỉ nhận</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Mở &amp;URI...</translation> </message> <message> <source>Click to disable network activity.</source> <translation>Nhấp để vô hiệu hóa kết nối mạng.</translation> </message> <message> <source>Network activity disabled.</source> <translation>Kết nối mạng đã bị ngắt</translation> </message> <message> <source>Click to enable network activity again.</source> <translation>Nhấp để kết nối lại mạng.</translation> </message> <message> <source>Syncing Headers (%1%)...</source> <translation>Đồng bộ hóa các Headers (%1%)...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Đánh chỉ số (indexing) lại các khối (blocks) trên ổ đĩa ...</translation> </message> <message> <source>Send coins to a Peercoin address</source> <translation>Gửi coins đến tài khoản Peercoin</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Sao lưu ví tiền ở vị trí khác</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Thay đổi cụm mật mã dùng cho mã hoá Ví</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Cửa sổ xử lý lỗi (debug)</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Mở trình gỡ lỗi và bảng lệnh chuẩn đoán</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Tin nhắn xác thực</translation> </message> <message> <source>Peercoin</source> <translation>Peercoin</translation> </message> <message> <source>Wallet</source> <translation>Ví</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Gửi</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Nhận</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>Ẩn / H&amp;iện</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Hiện hoặc ẩn cửa sổ chính</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Mã hoá các khoá bí mật trong Ví của bạn.</translation> </message> <message> <source>Sign messages with your Peercoin addresses to prove you own them</source> <translation>Dùng địa chỉ Peercoin của bạn ký các tin nhắn để xác minh những nội dung tin nhắn đó là của bạn.</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Peercoin addresses</source> <translation>Kiểm tra các tin nhắn để chắc chắn rằng chúng được ký bằng các địa chỉ Peercoin xác định.</translation> </message> <message> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Thiết lập</translation> </message> <message> <source>&amp;Help</source> <translation>Trợ &amp;giúp</translation> </message> <message> <source>Tabs toolbar</source> <translation>Thanh công cụ (toolbar)</translation> </message> <message> <source>Request payments (generates QR codes and peercoin: URIs)</source> <translation>Yêu cầu thanh toán(tạo mã QR và địa chỉ Peercoin: URLs)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Hiện thỉ danh sách các địa chỉ và nhãn đã dùng để gửi.</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Hiện thỉ danh sách các địa chỉ và nhãn đã dùng để nhận.</translation> </message> <message> <source>Open a peercoin: URI or payment request</source> <translation>Mở peercoin:URL hoặc yêu cầu thanh toán</translation> </message> <message> <source>&amp;Command-line options</source> <translation>7Tùy chọn dòng lệnh</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Peercoin network</source> <translation><numerusform>%n liên kết hoạt động với mạng lưới Peercoin</numerusform></translation> </message> <message> <source>Indexing blocks on disk...</source> <translation>Đang lập chỉ mục các khối trên ổ đĩa</translation> </message> <message> <source>Processing blocks on disk...</source> <translation>Đang xử lý các khối trên ổ đĩa...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>Đã xử lý %n khối của lịch sử giao dịch.</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 chậm trễ</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Khối (block) cuối cùng nhận được cách đây %1</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Những giao dịch sau đó sẽ không hiện thị.</translation> </message> <message> <source>Error</source> <translation>Lỗi</translation> </message> <message> <source>Warning</source> <translation>Chú ý</translation> </message> <message> <source>Information</source> <translation>Thông tin</translation> </message> <message> <source>Up to date</source> <translation>Đã cập nhật</translation> </message> <message> <source>Show the %1 help message to get a list with possible Peercoin command-line options</source> <translation>Hiển thị tin nhắn trợ giúp %1 để có được danh sách với các tùy chọn dòng lệnh Peercoin.</translation> </message> <message> <source>Connecting to peers...</source> <translation>Kết nối với các máy ngang hàng...</translation> </message> <message> <source>Catching up...</source> <translation>Bắt kịp...</translation> </message> <message> <source>Date: %1 </source> <translation>Ngày: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Số lượng: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Loại: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Nhãn hiệu: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Địa chỉ: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Giao dịch đã gửi</translation> </message> <message> <source>Incoming transaction</source> <translation>Giao dịch đang tới</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Ví tiền &lt;b&gt; đã được mã hóa&lt;/b&gt;và hiện &lt;b&gt;đang mở&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Ví tiền &lt;b&gt; đã được mã hóa&lt;/b&gt;và hiện &lt;b&gt;đang khóa&lt;/b&gt;</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>Lượng:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Lượng:</translation> </message> <message> <source>Fee:</source> <translation>Phí:</translation> </message> <message> <source>After Fee:</source> <translation>Sau thuế, phí:</translation> </message> <message> <source>Change:</source> <translation>Thay đổi:</translation> </message> <message> <source>(un)select all</source> <translation>(bỏ)chọn tất cả</translation> </message> <message> <source>Tree mode</source> <translation>Chế độ cây</translation> </message> <message> <source>List mode</source> <translation>Chế độ danh sách</translation> </message> <message> <source>Amount</source> <translation>Lượng</translation> </message> <message> <source>Date</source> <translation>Ngày tháng</translation> </message> <message> <source>Confirmations</source> <translation>Lần xác nhận</translation> </message> <message> <source>Confirmed</source> <translation>Đã xác nhận</translation> </message> <message> <source>(no label)</source> <translation>(không nhãn)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Thay đổi địa chỉ</translation> </message> <message> <source>&amp;Label</source> <translation>Nhãn</translation> </message> <message> <source>&amp;Address</source> <translation>Địa chỉ</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>name</source> <translation>tên</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>version</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>Command-line options</source> <translation>&amp;Tùy chọn dòng lệnh</translation> </message> <message> <source>Usage:</source> <translation>Mức sử dụng</translation> </message> <message> <source>command-line options</source> <translation>tùy chọn dòng lệnh</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Chọn ngôn ngữ, ví dụ "de_DE" (mặc định: Vị trí hệ thống)</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Đặt chứng nhận SSL gốc cho yêu cầu giao dịch (mặc định: -hệ thống-)</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Chào mừng</translation> </message> <message> <source>Use the default data directory</source> <translation>Sử dụng vị trí dữ liệu mặc định</translation> </message> <message> <source>Peercoin</source> <translation>Peercoin</translation> </message> <message> <source>Error</source> <translation>Lỗi</translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Form</translation> </message> <message> <source>Hide</source> <translation>Ẩn</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Mở URI</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Lựa chọn</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Chính</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Địa chỉ IP của proxy (ví dụ IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>W&amp;allet</source> <translation>Ví</translation> </message> <message> <source>Connect to the Peercoin network through a SOCKS5 proxy.</source> <translation>Kết nối đến máy chủ Peercoin thông qua SOCKS5 proxy.</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Cổng:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Cổng proxy (e.g. 9050) </translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Hiển thị</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>Giao diện người dùng &amp; ngôn ngữ</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Từ chối</translation> </message> <message> <source>default</source> <translation>mặc định</translation> </message> <message> <source>none</source> <translation>Trống</translation> </message> <message> <source>Error</source> <translation>Lỗi</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Form</translation> </message> <message> <source>Available:</source> <translation>Khả dụng</translation> </message> <message> <source>Pending:</source> <translation>Đang chờ</translation> </message> <message> <source>Total:</source> <translation>Tổng:</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Sent</source> <translation>Đã gửi</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Lượng</translation> </message> <message> <source>%1 and %2</source> <translation>%1 và %2</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> <message> <source>&amp;Save Image...</source> <translation>$Lưu hình ảnh...</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>&amp;Information</source> <translation>Thông tin</translation> </message> <message> <source>General</source> <translation>Nhìn Chung</translation> </message> <message> <source>Name</source> <translation>Tên</translation> </message> <message> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <source>Sent</source> <translation>Đã gửi</translation> </message> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>1 &amp;hour</source> <translation>1&amp;giờ</translation> </message> <message> <source>1 &amp;day</source> <translation>1&amp;ngày</translation> </message> <message> <source>1 &amp;week</source> <translation>1&amp;tuần</translation> </message> <message> <source>1 &amp;year</source> <translation>1&amp;năm</translation> </message> <message> <source>never</source> <translation>không bao giờ</translation> </message> <message> <source>Yes</source> <translation>Đồng ý</translation> </message> <message> <source>No</source> <translation>Không</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>Lượng:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Nhãn</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Tin nhắn:</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Sử dụng form này để yêu cầu thanh toán. Tất cả các trường &lt;b&gt;không bắt buộc&lt;b&gt;</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Xóa tất cả các trường trong biểu mẫu</translation> </message> <message> <source>Clear</source> <translation>Xóa</translation> </message> <message> <source>Requested payments history</source> <translation>Lịch sử yêu cầu thanh toán</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Yêu cầu thanh toán</translation> </message> <message> <source>Show</source> <translation>Hiển thị</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Xóa khỏi danh sách</translation> </message> <message> <source>Remove</source> <translation>Xóa</translation> </message> <message> <source>Copy message</source> <translation>Copy tin nhắn</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>QR Code</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copy &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>&amp;Copy Địa Chỉ</translation> </message> <message> <source>&amp;Save Image...</source> <translation>$Lưu hình ảnh...</translation> </message> <message> <source>Request payment to %1</source> <translation>Yêu cầu thanh toán cho %1</translation> </message> <message> <source>Payment information</source> <translation>Thông tin thanh toán</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Địa chỉ</translation> </message> <message> <source>Amount</source> <translation>Lượng</translation> </message> <message> <source>Label</source> <translation>Nhãn</translation> </message> <message> <source>Message</source> <translation>Tin nhắn</translation> </message> <message> <source>Error encoding URI into QR Code.</source> <translation>Lỗi khi encode từ URI thành QR Code</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Label</source> <translation>Nhãn</translation> </message> <message> <source>Message</source> <translation>Tin nhắn</translation> </message> <message> <source>(no label)</source> <translation>(không nhãn)</translation> </message> <message> <source>(no message)</source> <translation>(không tin nhắn)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Gửi Coins</translation> </message> <message> <source>Coin Control Features</source> <translation>Tính năng Control Coin</translation> </message> <message> <source>Inputs...</source> <translation>Nhập...</translation> </message> <message> <source>automatically selected</source> <translation>Tự động chọn</translation> </message> <message> <source>Insufficient funds!</source> <translation>Không đủ tiền</translation> </message> <message> <source>Quantity:</source> <translation>Lượng:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Lượng:</translation> </message> <message> <source>Fee:</source> <translation>Phí:</translation> </message> <message> <source>After Fee:</source> <translation>Sau thuế, phí:</translation> </message> <message> <source>Change:</source> <translation>Thay đổi:</translation> </message> <message> <source>Transaction Fee:</source> <translation>Phí giao dịch</translation> </message> <message> <source>Choose...</source> <translation>Chọn...</translation> </message> <message> <source>collapse fee-settings</source> <translation>Thu gọn fee-settings</translation> </message> <message> <source>per kilobyte</source> <translation>trên KB</translation> </message> <message> <source>Hide</source> <translation>Ẩn</translation> </message> <message> <source>(read the tooltip)</source> <translation>(Đọc hướng dẫn)</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Gửi đến nhiều người nhận trong một lần</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Thêm &amp;Người nhận</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Xóa tất cả các trường trong biểu mẫu</translation> </message> <message> <source>Clear &amp;All</source> <translation>Xóa &amp;Tất cả</translation> </message> <message> <source>Balance:</source> <translation>Tài khoản</translation> </message> <message> <source>Confirm the send action</source> <translation>Xác nhận sự gửi</translation> </message> <message> <source>%1 to %2</source> <translation>%1 đến %2</translation> </message> <message> <source>Total Amount %1</source> <translation>Tổng cộng %1</translation> </message> <message> <source>or</source> <translation>hoặc</translation> </message> <message> <source>Confirm send coins</source> <translation>Xác nhận gửi coins</translation> </message> <message> <source>(no label)</source> <translation>(không nhãn)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>Lượng:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Nhãn</translation> </message> </context> <context> <name>SendConfirmationDialog</name> <message> <source>Yes</source> <translation>Đồng ý</translation> </message> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Clear &amp;All</source> <translation>Xóa &amp;Tất cả</translation> </message> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Message</source> <translation>Tin nhắn</translation> </message> <message> <source>Amount</source> <translation>Lượng</translation> </message> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> <message> <source>Label</source> <translation>Nhãn</translation> </message> <message> <source>(no label)</source> <translation>(không nhãn)</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>Comma separated file (*.csv)</source> <translation>Các tệp tác nhau bằng đấu phẩy (* .csv)</translation> </message> <message> <source>Label</source> <translation>Nhãn</translation> </message> <message> <source>Address</source> <translation>Địa chỉ</translation> </message> <message> <source>Exporting Failed</source> <translation>Xuất không thành công</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> <message> <source>Send Coins</source> <translation>Gửi Coins</translation> </message> </context> <context> <name>WalletView</name> <message> <source>&amp;Export</source> <translation>&amp;Xuất</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Lựa chọn:</translation> </message> <message> <source>Peercoin Core</source> <translation>Peercoin Core</translation> </message> <message> <source>(default: %u)</source> <translation>(mặc định: %u)</translation> </message> <message> <source>Information</source> <translation>Thông tin</translation> </message> <message> <source>Transaction too large</source> <translation>Giao dịch quá lớn</translation> </message> <message> <source>Warning</source> <translation>Chú ý</translation> </message> <message> <source>(default: %s)</source> <translation>(mặc định: %s)</translation> </message> <message> <source>Insufficient funds</source> <translation>Không đủ tiền</translation> </message> <message> <source>Loading block index...</source> <translation>Đang đọc block index...</translation> </message> <message> <source>Loading wallet...</source> <translation>Đang đọc ví...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Không downgrade được ví</translation> </message> <message> <source>Rescanning...</source> <translation>Đang quét lại...</translation> </message> <message> <source>Done loading</source> <translation>Đã nạp xong</translation> </message> <message> <source>Error</source> <translation>Lỗi</translation> </message> </context> </TS>
ppcoin/ppcoin
src/qt/locale/bitcoin_vi_VN.ts
TypeScript
mit
42,099
<?php /** * 3 latest posts under slider. */ $thumb = has_post_thumbnail ()? wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large' ): [null]; if (!$thumb[0]){ if ( get_post_meta( $post->ID, '_scheduled_thumbnail_id' ) ){ $array = get_post_meta( $post->ID, '_scheduled_thumbnail_id' ); $thumb = wp_get_attachment_image_src( $array [0], 'large' ); } else if ( get_post_meta( $post->ID, '_scheduled_thumbnail_list') ){ $list = get_post_meta( $post->ID, '_scheduled_thumbnail_list'); $array =json_decode($list[0]); $thumb = wp_get_attachment_image_src( $array[0], 'large' ); } else { $thumb = [null]; } } ?> <article class="item col-xs-12 col-sm-4 col-md-4"> <a href="<?=the_permalink()?>" rel="bookmark" title="<?=the_title_attribute()?>"> <div class="post-image"<?=isset ($thumb['0'])? ' style="background-image:url(' . $thumb['0'] . ');"': null?>></div> </a> <h2 class="grey-font"><?=the_title()?></h2> <h3><?=get_field('sub-title')?></h3> <div class='company-post-excerpt'><?=strlen(get_the_excerpt())>300? substr(get_the_excerpt(), 0,298) . '...': get_the_excerpt()?></div> <div class="post-share"> <a href="http://twitter.com/share?url=<?=the_permalink()?>" target="_blank"><i class='ion-social-twitter'></i></a> <a href="http://www.facebook.com/sharer.php?u=<?=the_permalink()?>" target="_blank"><i class='ion-social-facebook'></i></a> <a href="javascript:void((function()%7Bvar%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','//assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)%7D)());" target="_blank"><i class='ion-social-pinterest'></i></a> <a href="http://www.tumblr.com/share/link?<?=the_permalink()?>" target="_blank"><i class='ion-social-tumblr'></i></a> </div> </article>
damnmagazine/damn-sage
templates/home-company-posts.php
PHP
mit
1,880
<?php namespace Dazzle\Redis\Command\Compose; use Dazzle\Redis\Command\Builder; use Dazzle\Redis\Command\Enum; use Dazzle\Redis\Driver\Request; trait ApiSetTrait { /** * @param Request $request * @return mixed */ abstract function dispatch(Request $request); /** * @override * @inheritDoc */ public function sScan($key, $cursor, array $options = []) { $command = Enum::SSCAN; $args = [$key, $cursor]; $args = array_merge($args, $options); return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sInter(...$keys) { $command = Enum::SINTER; $args = $keys; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sInterStore($dst, ...$keys) { $command = Enum::SINTERSTORE; $args = [$dst]; $args = array_merge($args, $keys); return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sIsMember($key, $member) { $command = Enum::SISMEMBER; $args = [$key ,$member]; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sMembers($key) { $command = Enum::SMEMBERS; $args = [$key]; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sMove($src, $dst, $member) { $command = Enum::SMOVE; $args = [$src, $dst, $member]; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sPop($key, $count) { $command = Enum::SPOP; $args = [$key, $count]; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sRandMember($key, $count) { $command = Enum::SRANDMEMBER; $args = [$key, $count]; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sRem($key, ...$members) { $command = Enum::SREM; $args = [$key]; $args = array_merge($args, $members); return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sUnion(...$keys) { $command = Enum::SUNION; $args = $keys; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sUnionStore($dst, ...$keys) { $command = Enum::SUNIONSTORE; $args = [$dst]; $args = array_merge($args, $keys); return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sAdd($key, ...$members) { $command = Enum::SADD; $args = [$key]; $args = array_merge($args, $members); return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sCard($key) { $command = Enum::SCARD; $args = [$key]; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sDiff(...$keys) { $command = Enum::SDIFF; $args = $keys; return $this->dispatch(Builder::build($command, $args)); } /** * @override * @inheritDoc */ public function sDiffStore($dst, ...$keys) { $command = Enum::SDIFFSTORE; $args = [$dst]; $args = array_merge($args, $keys); return $this->dispatch(Builder::build($command, $args)); } }
dazzle-php/redis
src/Redis/Command/Compose/ApiSetTrait.php
PHP
mit
4,082
namespace AAWebSmartHouse.Data.Migrations { using System.Data.Entity.Migrations; using System.Linq; using AAWebSmartHouse.Common; using AAWebSmartHouse.Data.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; public sealed class Configuration : DbMigrationsConfiguration<AAWebSmartHouseDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; this.CodeGenerator = new MySql.Data.Entity.MySqlMigrationCodeGenerator(); // register mysql code generator this.SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator()); } protected override void Seed(AAWebSmartHouseDbContext context) { //// This method will be called after migrating to the latest version. //// You can use the DbSet<T>.AddOrUpdate() helper extension method //// to avoid creating duplicate seed data. E.g. //// //// context.People.AddOrUpdate( //// p => p.FullName, //// new Person { FullName = "Andrew Peters" }, //// new Person { FullName = "Brice Lambson" }, //// new Person { FullName = "Rowan Miller" } //// ); if (!context.Roles.Any(r => r.Name == AdminUser.Name)) { context.Roles.AddOrUpdate( new IdentityRole[] { new IdentityRole(AdminUser.Name), //// new IdentityRole("User") }); context.SaveChanges(); } var databaseRole = context.Roles.Where(ro => ro.Name == AdminUser.Name).FirstOrDefault(); // Adding admin user.. if (!context.Users.Any(u => u.UserName == AdminUser.UserName)) { User user = new User(); string passwordHash = new PasswordHasher().HashPassword(AdminUser.Password); user.PasswordHash = passwordHash; user.FirstName = AdminUser.UserName; user.LastName = AdminUser.UserName; user.Email = AdminUser.UserName; user.UserName = AdminUser.UserName; user.EmailConfirmed = true; user.PhoneNumberConfirmed = true; context.Users.AddOrUpdate(user); context.SaveChanges(); var databaseUser = context.Users.Where(u => u.UserName == AdminUser.UserName).FirstOrDefault(); var userRoleRelation = new IdentityUserRole() { UserId = databaseUser.Id, RoleId = databaseRole.Id }; databaseUser.Roles.Add(userRoleRelation); context.SaveChanges(); } UserStore<User> userStore = new UserStore<User>(context); UserManager<User> userManager = new UserManager<User>(userStore); string userId = context.Users.Where(x => x.Email == AdminUser.UserName && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault(); if (!string.IsNullOrEmpty(userId)) { userManager.UpdateSecurityStamp(userId); } // Adding simple user.. if (!context.Users.Any(u => u.UserName == SimpleUser.UserName)) { User user = new User(); string passwordHash = new PasswordHasher().HashPassword(SimpleUser.Password); user.PasswordHash = passwordHash; user.FirstName = SimpleUser.UserName; user.LastName = SimpleUser.UserName; user.Email = SimpleUser.UserName; user.UserName = SimpleUser.UserName; user.EmailConfirmed = true; user.PhoneNumberConfirmed = true; context.Users.AddOrUpdate(user); context.SaveChanges(); } } } }
Obelixx/AASmartHouse
AAWebSmartHouse/Data/AAWebSmartHouse.Data/Migrations/Configuration.cs
C#
mit
4,177
// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <Volumeprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <Volumeaddress>\n" "Reveals the private key corresponding to <Volumeaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Volume address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); }
volumecoin/volume
src/rpcdump.cpp
C++
mit
2,846
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Problem_15_Calculator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem_15_Calculator")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f2f9368-4c59-438b-8d52-f20aa6497b49")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
ReapeR-MaxPayne/SU-TM-PF-Ext-0517-Excersises-CSharp
03-DataTypesAndVariables-Exercises/Problem_15_Calculator/Properties/AssemblyInfo.cs
C#
mit
1,418
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; define(["require", "exports", "aurelia-framework", "./../../config"], function (require, exports, aurelia_framework_1, config_1) { "use strict"; var CardActionElement = (function () { function CardActionElement() { } CardActionElement.prototype.attached = function () { this.element.classList.add("card-action"); }; CardActionElement.prototype.detached = function () { this.element.classList.remove("card-action"); }; CardActionElement = __decorate([ aurelia_framework_1.customElement(config_1.config.cardAction), aurelia_framework_1.containerless(), aurelia_framework_1.inlineView("<template><div ref='element'><slot></slot></div></template>"), __metadata('design:paramtypes', []) ], CardActionElement); return CardActionElement; }()); exports.CardActionElement = CardActionElement; }); //# sourceMappingURL=cardActionElement.js.map
eriklieben/aurelia-materialize-css
dist/amd/components/card/cardActionElement.js
JavaScript
mit
1,745
module ValidatorIE class StateAP include ActiveModel::Validations attr_accessor :number validates :number, length: { minimum: 9, maximum: 9 }, numericality: true, presence: true validate :number_should_code_state validate :number_should_range_code validate :number_should_mod11 def initialize(opts={}) opts.each do |key, value| self.public_send("#{key}=", value) end @p = @d = 0 end def number_should_code_state number[0..1].eql?('03') end def number_should_range_code if number.to_i.between?(3000001, 3017000) @p = 5 @d = 0 elsif number.to_i.between?(3017001, 3019022) @p = 9 @d = 1 end end def number_should_mod11 result = number_should_modX(11, 7) return if result errors.add(:number, 'não é válido para inscrição estadual.') end private def number_should_modX(mod, at, final = number.size) numberX = number.split(//).map(&:to_i) sum = ModFunctions.sumX(numberX, at, final) + @p digit = mod - sum.divmod(mod).last digit = digit.eql?(10) ? 0 : digit digit = digit.eql?(11) ? @d : digit return numberX[at + 1].eql?(digit) end end end
rmomogi/validator_ie
lib/validator_ie/core/state_ap.rb
Ruby
mit
1,328
# -*- coding: utf-8 -*- tokens = [ 'LPAREN', 'RPAREN', 'LBRACE', 'RBRACE', 'EQUAL', 'DOUBLE_EQUAL', 'NUMBER', 'COMMA', 'VAR_DEFINITION', 'IF', 'ELSE', 'END', 'ID', 'PRINT' ] t_LPAREN = r"\(" t_RPAREN = r"\)" t_LBRACE = r"\{" t_RBRACE = r"\}" t_EQUAL = r"\=" t_DOUBLE_EQUAL = r"\=\=" def t_NUMBER(token): r"[0-9]+" token.value = int(token.value) return token t_COMMA = r"," def t_VAR_DEFINITION(token): r",\sFirst\sof\s(his|her)\sName" return token def t_IF(token): r"I\spromise" return token def t_ELSE(token): r"Mayhaps" return token def t_PRINT(token): r"Hodor" return token def t_END(token): r"And\snow\shis\swatch\sis\sended" return token def t_ID(token): r"[a-zA-Z][_a-zA-Z0-9]*" return token t_ignore = " \t" def t_NEWLINE(token): r"\n+" token.lexer.lineno += len(token.value) def t_IGNORE_COMMENTS(token): r"//(.*)\n" token.lexer.lineno += 1 def t_error(token): raise Exception("Sintax error: Unknown token on line {0}. \"{1}\"".format(token.lineno, token.value.partition("\n")[0]))
pablogonzalezalba/a-language-of-ice-and-fire
lexer_rules.py
Python
mit
1,138
using IoTHelpers.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Devices.I2c; namespace IoTHelpers.I2c.Devices { public struct Acceleration { public double X { get; internal set; } public double Y { get; internal set; } public double Z { get; internal set; } }; public class Adxl345Accelerometer : I2cTimedDevice { // Address Constants public const byte DefaultI2cAddress = 0x53; /* 7-bit I2C address of the ADXL345 with SDO pulled low */ private const byte ACCEL_REG_POWER_CONTROL = 0x2D; /* Address of the Power Control register */ private const byte ACCEL_REG_DATA_FORMAT = 0x31; /* Address of the Data Format register */ private const byte ACCEL_REG_X = 0x32; /* Address of the X Axis data register */ private const byte ACCEL_REG_Y = 0x34; /* Address of the Y Axis data register */ private const byte ACCEL_REG_Z = 0x36; /* Address of the Z Axis data register */ private const int ACCEL_RES = 1024; /* The ADXL345 has 10 bit resolution giving 1024 unique values */ private const int ACCEL_DYN_RANGE_G = 8; /* The ADXL345 had a total dynamic range of 8G, since we're configuring it to +-4G */ private const int UNITS_PER_G = ACCEL_RES / ACCEL_DYN_RANGE_G; /* Ratio of raw int values to G units */ private static TimeSpan DEFAULT_READ_INTERVAL = TimeSpan.FromMilliseconds(100); private Acceleration currentAcceleration = new Acceleration(); public Acceleration CurrentAcceleration { get { if (ReadingMode == ReadingMode.Manual) throw new NotSupportedException($"{nameof(CurrentAcceleration)} is available only when {nameof(ReadingMode)} is set to {ReadingMode.Continuous}."); return currentAcceleration; } } public bool RaiseEventsOnUIThread { get; set; } = false; public event EventHandler AccelerationChanged; public Adxl345Accelerometer(int slaveAddress = DefaultI2cAddress, ReadingMode mode = ReadingMode.Continuous, I2cBusSpeed busSpeed = I2cBusSpeed.FastMode, I2cSharingMode sharingMode = I2cSharingMode.Shared, string i2cControllerName = RaspberryPiI2cControllerName) : base(slaveAddress, mode, DEFAULT_READ_INTERVAL, busSpeed, sharingMode, i2cControllerName) { } protected override Task InitializeSensorAsync() { /* * Initialize the accelerometer: * * For this device, we create 2-byte write buffers: * The first byte is the register address we want to write to. * The second byte is the contents that we want to write to the register. */ var writeBuf_DataFormat = new byte[] { ACCEL_REG_DATA_FORMAT, 0x01 }; /* 0x01 sets range to +- 4Gs */ var writeBuf_PowerControl = new byte[] { ACCEL_REG_POWER_CONTROL, 0x08 }; /* 0x08 puts the accelerometer into measurement mode */ /* Write the register settings */ Device.Write(writeBuf_DataFormat); Device.Write(writeBuf_PowerControl); /* Now that everything is initialized, create a timer so we read data every 100mS */ base.InitializeTimer(); return Task.FromResult<object>(null); } protected override void OnTimer() { var acceleration = this.ReadAcceleration(); if (currentAcceleration.X != acceleration.X || currentAcceleration.Y != acceleration.Y || currentAcceleration.Z != acceleration.Z) { currentAcceleration = acceleration; RaiseEventHelper.CheckRaiseEventOnUIThread(this, AccelerationChanged, RaiseEventsOnUIThread); } } public Acceleration ReadAcceleration() { var regAddrBuf = new byte[] { ACCEL_REG_X }; /* Register address we want to read from */ var readBuf = new byte[6]; /* We read 6 bytes sequentially to get all 3 two-byte axes registers in one read */ /* * Read from the accelerometer * We call WriteRead() so we first write the address of the X-Axis I2C register, then read all 3 axes */ Device.WriteRead(regAddrBuf, readBuf); /* * In order to get the raw 16-bit data values, we need to concatenate two 8-bit bytes from the I2C read for each axis. * We accomplish this by using the BitConverter class. */ var accelerationRawX = BitConverter.ToInt16(readBuf, 0); var accelerationRawY = BitConverter.ToInt16(readBuf, 2); var accelerationRawZ = BitConverter.ToInt16(readBuf, 4); /* Convert raw values to G's */ var accel = new Acceleration { X = (double)accelerationRawX / UNITS_PER_G, Y = (double)accelerationRawY / UNITS_PER_G, Z = (double)accelerationRawZ / UNITS_PER_G }; return accel; } public override void Dispose() { base.Dispose(); } } }
Dot-and-Net/IoTHelpers
Src/IoTHelpers/I2c/Devices/Adxl345Accelerometer.cs
C#
mit
5,521
module.exports = function (grunt) { // Define the configuration for all the tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Configure a mochaTest task mochaTest: { test: { options: { reporter: 'spec', ui: 'bdd', recursive: true, colors: true, 'check-leaks': true, growl: true, 'inline-diffs': true, 'no-exit': true, 'async-only': true }, src: ['test/**/*.js'] } } }); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('test', ['mochaTest']); };
prateekbhatt/testing-sinon
GruntFile.js
JavaScript
mit
782
<?php //Names the page template for each section /* Template Name: Early College */ get_header(); ?> <?php get_template_part( 'parts/banners' ); ?> <div class="row"> <div class="container"> <?php // Gets the alert custom post type id for each sub page needing special announcement $post_id = 5447; $queried_post = get_post($post_id); $content = $queried_post->post_content; $content = apply_filters('the_content', $content); if ($content) { ?> <div class='alert-box alert'> <?php echo "$content"; ?> <a href='#' class='close' aria-hidden="true" role="button"><span class='icon-remove-circle'></span></a></div> <?php } else { } ?> <?php get_template_part( 'parts/content' ); ?> <?php get_template_part( 'parts/sidebars/early-college-sidebar' ); ?> </div> </div> <?php get_footer(); ?>
mattrhummel/GermannaCC-WPTheme
page-early-college.php
PHP
mit
799
import { createEllipsisItem, createFirstPage, createLastItem, createNextItem, createPageFactory, createPrevItem, } from 'src/lib/createPaginationItems/itemFactories' describe('itemFactories', () => { describe('createEllipsisItem', () => { it('"active" is always false', () => { createEllipsisItem(0).should.have.property('active', false) }) it('"type" matches "ellipsisItem"', () => { createEllipsisItem(0).should.have.property('type', 'ellipsisItem') }) it('"value" matches passed argument', () => { createEllipsisItem(5).should.have.property('value', 5) }) }) describe('createFirstPage', () => { it('"active" is always false', () => { createFirstPage().should.have.property('active', false) }) it('"type" matches "firstItem"', () => { createFirstPage().should.have.property('type', 'firstItem') }) it('"value" always returns 1', () => { createFirstPage().should.have.property('value', 1) }) }) describe('createPrevItem', () => { it('"active" is always false', () => { createPrevItem(1).should.have.property('active', false) }) it('"type" matches "prevItem"', () => { createPrevItem(1).should.have.property('type', 'prevItem') }) it('"value" returns previous page number or 1', () => { createPrevItem(1).should.have.property('value', 1) createPrevItem(2).should.have.property('value', 1) createPrevItem(3).should.have.property('value', 2) }) }) describe('createPageFactory', () => { const pageFactory = createPageFactory(1) it('returns function', () => { pageFactory.should.be.a('function') }) it('"active" is true when pageNumber is equal to activePage', () => { pageFactory(1).should.have.property('active', true) }) it('"active" is false when pageNumber is not equal to activePage', () => { pageFactory(2).should.have.property('active', false) }) it('"type" of created item matches "pageItem"', () => { pageFactory(2).should.have.property('type', 'pageItem') }) it('"value" returns pageNumber', () => { pageFactory(1).should.have.property('value', 1) pageFactory(2).should.have.property('value', 2) }) }) describe('createNextItem', () => { it('"active" is always false', () => { createNextItem(0, 0).should.have.property('active', false) }) it('"type" matches "nextItem"', () => { createNextItem(0, 0).should.have.property('type', 'nextItem') }) it('"value" returns the smallest of the arguments', () => { createNextItem(1, 3).should.have.property('value', 2) createNextItem(2, 3).should.have.property('value', 3) createNextItem(3, 3).should.have.property('value', 3) }) }) describe('createLastItem', () => { it('"active" is always false', () => { createLastItem(0).should.have.property('active', false) }) it('"type" matches "lastItem"', () => { createLastItem(0).should.have.property('type', 'lastItem') }) it('"value" matches passed argument', () => { createLastItem(2).should.have.property('value', 2) }) }) })
Semantic-Org/Semantic-UI-React
test/specs/lib/createPaginationItems/itemFactories-test.js
JavaScript
mit
3,176
#include <algorithm> #include "GI/uvmapper.h" UVMapper::UVMapper( glm::ivec2 size) : m_size(size), m_scale(0.f), m_border(glm::vec2(1.)/glm::vec2(size)) {} UVMapper::~UVMapper() {} void UVMapper::computeLightmapPack(std::vector<Object*> &obj) { m_obj = obj; std::vector<Quadrilateral> m_quad; //UV Planar projection for(unsigned o=0; o<m_obj.size(); o++) { glm::vec3 *vertex = m_obj[o]->getVertex(); glm::vec2 *uv = m_obj[o]->getTexCoordsLightmap(); for(unsigned i=0; i<m_obj[o]->getNbFaces(); i++) { glm::vec3 pn = glm::abs( m_obj[o]->getNormalsFaces()[i]); if( pn.x > pn.y && pn.x > pn.z) //Plane X { for(int j=0; j<4; j++) { uv[i*4+j].x = vertex[i*4+j].y; uv[i*4+j].y = vertex[i*4+j].z; } } else if( pn.y > pn.x && pn.y > pn.z) //Plane Y { for(int j=0; j<4; j++) { uv[i*4+j].x = vertex[i*4+j].x; uv[i*4+j].y = vertex[i*4+j].z; } } else //Plane Z { for(int j=0; j<4; j++) { uv[i*4+j].x = vertex[i*4+j].y; uv[i*4+j].y = vertex[i*4+j].x; } } //Normalize to 0 .. X & store the edges glm::vec2 min=uv[i*4],max=uv[i*4]; for(int j=1; j<4; j++) { min = glm::min( min, uv[i*4+j]); max = glm::max( max, uv[i*4+j]); } Quadrilateral q; q.edge = max-min; q.p1 = &uv[i*4+0]; q.p2 = &uv[i*4+1]; q.p3 = &uv[i*4+2], q.p4 = &uv[i*4+3]; m_quad.push_back( q ); //Because TRIGONOMETRIC ORDER... =) uv[i*4+0] = glm::vec2(0.f); uv[i*4+1] = glm::vec2(q.edge.x,0.f); uv[i*4+2] = q.edge; uv[i*4+3] = glm::vec2(0.f,q.edge.y); } } //Compute areaMax m_scale = 0.f; for(unsigned i=0; i<m_quad.size(); i++) m_scale += m_quad[i].getArea(); m_scale = sqrt(m_scale)*1.35; //Normalize to fit to texture for(unsigned i = 0; i < m_quad.size(); ++i) m_quad[i].edge /= m_scale; for(unsigned i=0; i<m_obj.size(); i++) for(unsigned j=0; j<m_obj[i]->getNbVertex(); j++) m_obj[i]->getTexCoordsLightmap()[j] /= m_scale; //Sort by area std::sort(m_quad.begin(), m_quad.end()); //Recursive packing Node root; for(unsigned i = 0; i < m_quad.size(); ++i) { if( insert(&root,m_quad[i]) == NULL) { std::cout << m_quad[i].edge.x << " | " << m_quad[i].edge.y << std::endl; std::cout << "UV MAP PROBLEM" << std::endl; } } } Node* UVMapper::insert(Node *n, Quadrilateral &q) { //If this node have children, we try to recursively insert into them if(n->child[0] && n->child[1]) { Node *c = insert(n->child[0],q); return c ? c : insert(n->child[1],q); } else { //Can this rectangle be packed into this node ? if( q.edge.x > n->rect.z || q.edge.y > n->rect.w) { return NULL; } //Does this rectangle have exactly the same size as this node ? if( q.edge.x == n->rect.z && q.edge.y == n->rect.w) { glm::vec2 offset(n->rect.x, n->rect.y); *(q.p1) += offset; *(q.p2) += offset; *(q.p3) += offset; *(q.p4) += offset; return n; } n->child[0] = new Node(); n->child[1] = new Node(); //Decide which way to split float dw = n->rect.z - q.edge.x; float dh = n->rect.w - q.edge.y; if( dw < dh) { n->child[0]->rect = glm::vec4(n->rect.x+q.edge.x, n->rect.y, n->rect.z-q.edge.x, q.edge.y); n->child[1]->rect = glm::vec4(n->rect.x, n->rect.y+q.edge.y, n->rect.z, n->rect.w-q.edge.y); n->child[0]->rect += glm::vec4(m_border.x,0.f,-m_border.x,0.f); n->child[1]->rect += glm::vec4(0.f,m_border.y,0.f,-m_border.y); } else { n->child[0]->rect = glm::vec4(n->rect.x, n->rect.y+q.edge.y, q.edge.x, n->rect.w-q.edge.y); n->child[1]->rect = glm::vec4(n->rect.x+q.edge.x, n->rect.y, n->rect.z-q.edge.x, n->rect.w); n->child[0]->rect += glm::vec4(0.f,m_border.y,0.f,-m_border.y); n->child[1]->rect += glm::vec4(m_border.x,0.f,-m_border.x,0.f); } //Update the uv of the rectangle glm::vec2 offset(n->rect.x, n->rect.y); q.offset = offset; *(q.p1) += offset; *(q.p2) += offset; *(q.p3) += offset; *(q.p4) += offset; return n; } }
XT95/PBGI
src/GI/uvmapper.cpp
C++
mit
4,909
import java.lang.IndexOutOfBoundsException; public interface Sequence { public int size(); // Return number of elements in sequence. public void addFirst(int e); // Insert e at the front of the sequence. public void addLast(int e); // Insert e at the back of the sequence. // Inserts an element e to be at index i. public void add(int i, int e) throws IndexOutOfBoundsException; // Returns the element at index i, without removing it. public int get(int i) throws IndexOutOfBoundsException; // Removes and returns the element at index i. public int remove(int i) throws IndexOutOfBoundsException; }
adamjcook/cs27500
exam1/problem15/Sequence.java
Java
mit
646
module Multichain describe Client do let(:client) { described_class.new } it 'knows about its asset' do expect(client.asset).to eq 'odi-coin' end context 'send a coin' do it 'sends to a simple address', :vcr do expect(client.send_asset 'stu', 1).to eq ( { recipient: 'stu', asset: 'odi-coin', amount: 1, id: '13fea6fb1ad2dae1f77b60245e4c7b4315c8e0dcacb76f6fe8d726462e8e20b7' } ) end it 'sends to a compound address', :vcr do expect(client.send_asset 'sam:primary', 2).to eq ( { recipient: 'sam:primary', asset: 'odi-coin', amount: 2, id: '6fba0c50f1ca5acc52975bea79590e84337497b647e79e4be417066ecc1a7dfe' } ) end end context 'send data with a coin' do it 'sends a string of data', :vcr do expect(client.send_asset_with_data 'stu', 1, 'deadbeef').to eq ( { recipient: 'stu', asset: 'odi-coin', amount: 1, data: 'deadbeef', id: 'fede7691a223f4f556fbccba71788f6bd8f718c0c7b7e67c8d8f3549f3f2f37e', } ) end end context 'send a URL' do it 'sends a URL', :vcr do Timecop.freeze Time.local 2016, 01, 06 do expect(client.send_url 'sam', 'http://uncleclive.herokuapp.com/blockchain').to eq ( { recipient: 'sam', url: 'http://uncleclive.herokuapp.com/blockchain', hash: 'd004c795edeb3a90c2a2c115f619274fde4268122f61cf380dbf7f43523d9033', timestamp: '1452038400', hex: '313435323033383430307c687474703a2f2f756e636c65636c6976652e6865726f6b756170702e636f6d2f626c6f636b636861696e7c7b22416363657074223a226170706c69636174696f6e2f6a736f6e227d7c64303034633739356564656233613930633261326331313566363139323734666465343236383132326636316366333830646266376634333532336439303333', id: 'd4f8a2983463747bd8a83f833bccde21b3a34d5d703d41f0680fb10905b718e5' } ) end end end end end
theodi/multichain-client
spec/multichain/send_data_spec.rb
Ruby
mit
2,158
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // 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. namespace SafetySharp.Runtime { using System; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters.Binary; using Analysis; using CompilerServices; using ISSE.SafetyChecking.ExecutableModel; using ISSE.SafetyChecking.Formula; using ISSE.SafetyChecking.Modeling; using ISSE.SafetyChecking.Utilities; using Modeling; using Serialization; using Utilities; /// <summary> /// Represents a runtime model that can be used for model checking or simulation. /// </summary> public sealed unsafe class SafetySharpRuntimeModel : ExecutableModel<SafetySharpRuntimeModel> { /// <summary> /// The objects referenced by the model that participate in state serialization. /// </summary> private readonly ObjectTable _serializedObjects; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="serializedData">The serialized data describing the model.</param> /// <param name="stateHeaderBytes"> /// The number of bytes that should be reserved at the beginning of each state vector for the model checker tool. /// </param> internal SafetySharpRuntimeModel(SerializedRuntimeModel serializedData, int stateHeaderBytes = 0) : base(stateHeaderBytes) { Requires.That(serializedData.Model != null, "Expected a valid model instance."); var buffer = serializedData.Buffer; var rootComponents = serializedData.Model.Roots; var objectTable = serializedData.ObjectTable; var formulas = serializedData.Formulas; Requires.NotNull(buffer, nameof(buffer)); Requires.NotNull(rootComponents, nameof(rootComponents)); Requires.NotNull(objectTable, nameof(objectTable)); Requires.NotNull(formulas, nameof(formulas)); Requires.That(stateHeaderBytes % 4 == 0, nameof(stateHeaderBytes), "Expected a multiple of 4."); Model = serializedData.Model; SerializedModel = buffer; RootComponents = rootComponents.Cast<Component>().ToArray(); ExecutableStateFormulas = objectTable.OfType<ExecutableStateFormula>().ToArray(); Formulas = formulas; StateConstraints = Model.Components.Cast<Component>().SelectMany(component => component.StateConstraints).ToArray(); // Create a local object table just for the objects referenced by the model; only these objects // have to be serialized and deserialized. The local object table does not contain, for instance, // the closure types of the state formulas. Faults = objectTable.OfType<Fault>().Where(fault => fault.IsUsed).ToArray(); _serializedObjects = new ObjectTable(Model.ReferencedObjects); Objects = objectTable; StateVectorLayout = SerializationRegistry.Default.GetStateVectorLayout(Model, _serializedObjects, SerializationMode.Optimized); UpdateFaultSets(); _deserialize = StateVectorLayout.CreateDeserializer(_serializedObjects); _serialize = StateVectorLayout.CreateSerializer(_serializedObjects); _restrictRanges = StateVectorLayout.CreateRangeRestrictor(_serializedObjects); PortBinding.BindAll(objectTable); InitializeConstructionState(); CheckConsistencyAfterInitialization(); } /// <summary> /// Gets a copy of the original model the runtime model was generated from. /// </summary> internal ModelBase Model { get; } /// <summary> /// Gets all of the objects referenced by the model, including those that do not take part in state serialization. /// </summary> internal ObjectTable Objects { get; } /// <summary> /// Gets the model's <see cref="StateVectorLayout" />. /// </summary> internal StateVectorLayout StateVectorLayout { get; } /// <summary> /// Gets the size of the state vector in bytes. The size is always a multiple of 4. /// </summary> public override int StateVectorSize => StateVectorLayout.SizeInBytes + StateHeaderBytes; /// <summary> /// Gets the root components of the model. /// </summary> public Component[] RootComponents { get; } /// <summary> /// Gets the state formulas of the model. /// </summary> internal ExecutableStateFormula[] ExecutableStateFormulas { get; } /// <summary> /// Gets the state formulas of the model. /// </summary> public override AtomarPropositionFormula[] AtomarPropositionFormulas => ExecutableStateFormulas; /// <summary> /// Computes an initial state of the model. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override void ExecuteInitialStep() { foreach (var obj in _serializedObjects.OfType<IInitializable>()) { try { obj.Initialize(); } catch (Exception e) { throw new ModelException(e); } } _restrictRanges(); } /// <summary> /// Updates the state of the model by executing a single step. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override void ExecuteStep() { foreach (var component in RootComponents) { try { component.Update(); } catch (Exception e) { throw new ModelException(e); } } _restrictRanges(); } /// <summary> /// Disposes the object, releasing all managed and unmanaged resources. /// </summary> /// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param> protected override void OnDisposing(bool disposing) { if (disposing) Objects.OfType<IDisposable>().SafeDisposeAll(); } /// <summary> /// Creates a <see cref="SafetySharpRuntimeModel" /> instance from the <paramref name="model" /> and the <paramref name="formulas" />. /// </summary> /// <param name="model">The model the runtime model should be created for.</param> /// <param name="formulas">The formulas the model should be able to check.</param> internal static SafetySharpRuntimeModel Create(ModelBase model, params Formula[] formulas) { Requires.NotNull(model, nameof(model)); Requires.NotNull(formulas, nameof(formulas)); var creator = CreateExecutedModelCreator(model, formulas); return creator.Create(0); } public override void SetChoiceResolver(ChoiceResolver choiceResolver) { foreach (var choice in Objects.OfType<Choice>()) choice.Resolver = choiceResolver; } public override CounterExampleSerialization<SafetySharpRuntimeModel> CounterExampleSerialization { get; } = new SafetySharpCounterExampleSerialization(); public static CoupledExecutableModelCreator<SafetySharpRuntimeModel> CreateExecutedModelCreator(ModelBase model, params Formula[] formulasToCheckInBaseModel) { Requires.NotNull(model, nameof(model)); Requires.NotNull(formulasToCheckInBaseModel, nameof(formulasToCheckInBaseModel)); Func<int,SafetySharpRuntimeModel> creatorFunc; // serializer.Serialize has potentially a side effect: Model binding. The model gets bound when it isn't // bound already. The lock ensures that this binding is only made by one thread because model.EnsureIsBound // is not reentrant. lock (model) { var serializer = new RuntimeModelSerializer(); model.EnsureIsBound(); // Bind the model explicitly. Otherwise serialize.Serializer makes it implicitly. serializer.Serialize(model, formulasToCheckInBaseModel); creatorFunc = serializer.Load; } var faults = model.Faults; return new CoupledExecutableModelCreator<SafetySharpRuntimeModel>(creatorFunc, model, formulasToCheckInBaseModel, faults); } public static ExecutableModelCreator<SafetySharpRuntimeModel> CreateExecutedModelFromFormulasCreator(ModelBase model) { Requires.NotNull(model, nameof(model)); Func<Formula[],CoupledExecutableModelCreator <SafetySharpRuntimeModel>> creator = formulasToCheckInBaseModel => { Requires.NotNull(formulasToCheckInBaseModel, nameof(formulasToCheckInBaseModel)); return CreateExecutedModelCreator(model, formulasToCheckInBaseModel); }; return new ExecutableModelCreator<SafetySharpRuntimeModel>(creator, model); } public override Expression CreateExecutableExpressionFromAtomarPropositionFormula(AtomarPropositionFormula formula) { var executableStateFormula = formula as ExecutableStateFormula; if (executableStateFormula!=null) { return Expression.Invoke(Expression.Constant(executableStateFormula.Expression)); } throw new InvalidOperationException("AtomarPropositionFormula cannot be evaluated. Use ExecutableStateFormula instead."); } } }
maul-esel/ssharp
Source/SafetySharp/Runtime/SafetySharpRuntimeModel.cs
C#
mit
9,662
import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore import numpy# from pyqtgraph.parametertree import Parameter, ParameterTree, ParameterItem, registerParameterType class FeatureSelectionDialog(QtGui.QDialog): def __init__(self,viewer, parent): super(FeatureSelectionDialog, self).__init__(parent) self.resize(800,600) self.viewer = viewer self.layout = QtGui.QVBoxLayout() self.setLayout(self.layout) self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel) self.buttonBox.accepted.connect(self.onPressAccepted) def makeCheckBox(name, val=True): return { 'name': name, 'type': 'bool', 'value': val, #'tip': "This is a checkbox", } sigmaOpt = {'name': 'sigma', 'type': 'str', 'value': '[0.0, 1.0, 2.0, 4.0]' } wardOpts = {'name': 'wardness', 'type': 'str', 'value': '[0.0, 0.1, 0.2]' } filterChild = [ makeCheckBox("computeFilter"), sigmaOpt, { 'name':'UCM', 'children': [ makeCheckBox("ucmFilters"), wardOpts, {'name': 'meanSign', 'type': 'float', 'value': '1.0' } ] } ] params = [ { 'name' : "RawData", 'type' : 'group', 'children' : [ { 'name': 'Compute Features On Raw Data', 'type': 'bool', 'value': True, 'tip': "This is a checkbox", }, { 'name' : "0-Order Filter", 'type' : 'group', 'children' : filterChild }, { 'name' : "1-Order Filter", 'type' : 'group', 'children' : filterChild }, { 'name' : "2-Order Filter", 'type' : 'group', 'children' : filterChild } ] }, #ComplexParameter(name='Custom parameter group (reciprocal values)'), #ScalableGroup(name="Expandable Parameter Group", children=[ # {'name': 'ScalableParam 1', 'type': 'str', 'value': "default param 1"}, # {'name': 'ScalableParam 2', 'type': 'str', 'value': "default param 2"}, #]), ] ## Create tree of Parameter objects self.p = Parameter.create(name='params', type='group', children=params) self.t = ParameterTree() self.t.setParameters(self.p, showTop=False) self.layout.addWidget(self.t) self.layout.addWidget(self.buttonBox) ## If anything changes in the tree, print a message def change(param, changes): print("tree changes:") for param, change, data in changes: path = self.p.childPath(param) if path is not None: childName = '.'.join(path) else: childName = param.name() print(' parameter: %s'% childName) print(' change: %s'% change) print(' data: %s'% str(data)) print(' ----------') self.p.sigTreeStateChanged.connect(change) def onPressAccepted(self): self.hide() self.viewer.onClickedComputeFeaturesImpl(self.p) def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.hide() event.accept() else: super(QtGui.QDialog, self).keyPressEvent(event)
timoMa/vigra
vigranumpy/examples/boundary_gui/bv_feature_selection.py
Python
mit
3,993
/** * App */ 'use strict'; // Base setup var express = require('express'); var app = express(); var path = require('path'); var bodyParser = require('body-parser'); var logger = require('morgan'); var mongoose = require('mongoose'); var config = require('./config'); var routes = require('./routes/index'); var validateRequest = require('./middlewares/validateRequest'); // Configuration mongoose.connect(config.db[app.get('env')], function(err) { if (err) { console.log('connection error', err); } else { console.log('connection successful'); } }); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // app.use(logger('dev')); // app.set('view engine', 'html'); // API Routes // app.all('/*', function(req, res, next) { // // CORS headers // res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); // // Set custom headers for CORS // res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key'); // if (req.method == 'OPTIONS') { // res.status(200).end(); // } else { // next(); // } // }); // Auth Middleware - This will check if the token is valid // Only the requests that start with /api/v1/* will be checked for the token. // Any URL's that do not follow the below pattern should be avoided unless you // are sure that authentication is not needed. app.all('/api/v1/*', [validateRequest]); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // Error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500).send(err.message); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500).send(err.message); }); module.exports = app;
lucianot/dealbook-node-api
app.js
JavaScript
mit
2,082
$(document).ready(function(){ 'use strict'; //Turn off and on the music $("#sound-control").click(function() { var toggle = document.getElementById("sound-control"); var music = document.getElementById("music"); if(music.paused){ music.play(); $("#sound-control").attr('src', 'img/ljud_pa.png'); } else { music.pause(); $("#sound-control").attr('src', 'img/ljud_av.png'); } }); //The slideshow var started = false; //Backwards navigation $("#back").click(function() { stopSlideshow(); navigate("back"); }); //Forward navigation $("#next").click(function() { stopSlideshow(); navigate("next"); }); var interval; $("#control").click(function(){ if(started) { stopSlideshow(); } else { startSlideshow(); } }); var activeContainer = 1; var currentImg = 0; var animating = false; var navigate = function(direction) { //Check if no animation is running if(animating) { return; } //Check wich current image we need to show if(direction == "next") { currentImg++; if(currentImg == photos.length + 1) { currentImg = 1; } } else { currentImg--; if(currentImg == 0) { currentImg = photos.length; } } //Check wich container we need to use var currentContainer = activeContainer; if(activeContainer == 1) { activeContainer = 2; } else { activeContainer = 1; } showImage(photos[currentImg - 1], currentContainer, activeContainer); }; var currentZindex = -1; var showImage = function(photoObject, currentContainer, activeContainer) { animating = true; //Make sure the new container is always on the background currentZindex--; //Set the background image of the new active container $("#slideimg" + activeContainer).css({ "background-image" : "url(" + photoObject.image + ")", "display" : "block", "z-index" : currentZindex }); //Fade out and hide the slide-text when the new image is loading $("#slide-text").fadeOut(); $("#slide-text").css({"display" : "none"}); //Set the new header text $("#firstline").html(photoObject.firstline); $("#secondline") .attr("href", photoObject.url) .html(photoObject.secondline); //Fade out the current container //and display the slider-text when animation is complete $("#slideimg" + currentContainer).fadeOut(function() { setTimeout(function() { $("#slide-text").fadeIn(); animating = false; }, 500); }); }; var stopSlideshow = function() { //Change the background image to "play" $("#control").css({"background-image" : "url(img/play.png)" }); //Clear the interval clearInterval(interval); started = false; }; var startSlideshow = function() { $("#control").css({ "background-image" : "url(img/pause.png)" }); navigate("next"); interval = setInterval(function() { navigate("next"); }, slideshowSpeed); started = true; }; $.preloadImages = function() { $(photos).each(function() { $('<img>')[0].src = this.image; }); startSlideshow(); } $.preloadImages(); });
emmb14/MegaSlider
js/megaslider.js
JavaScript
mit
3,148
/* * Manifest Service * * Copyright (c) 2015 Thinknode Labs, LLC. All rights reserved. */ (function() { 'use strict'; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Service function loggerService() { /* jshint validthis: true */ this.logs = []; /** * @summary Appends a log message of a given type to the collection of logs. */ this.append = function(type, message) { this.logs.push({ "date": new Date(), "type": type, "message": message }); }; /** * @summary Clears the logs. */ this.clear = function() { this.logs.length = 0; }; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Register service angular.module('app').service('$logger', [loggerService]); })();
thinknode/desktop
src/services/logger.js
JavaScript
mit
930
from engine.api import API from engine.utils.printing_utils import progressBar from setup.utils.datastore_utils import repair_corrupt_reference, link_references_to_paper def remove_duplicates_from_cited_by(): print("\nRemove Duplicates") api = API() papers = api.get_all_paper() for i, paper in enumerate(papers): progressBar(i, len(papers)) paper.cited_by = list(dict.fromkeys(paper.cited_by)) api.client.update_paper(paper) def check_references(): print("\nCheck References") api = API() papers = api.get_all_paper() for i, paper in enumerate(papers): progressBar(i, len(papers)) other_papers = [p for p in papers if p.id != paper.id] for reference in paper.references: if not reference.get_paper_id(): continue ref_paper = api.get_paper(reference.get_paper_id()) if ref_paper.cited_by.count(paper.id) == 0: print() reference.paper_id = [] api.client.update_paper(paper) repair_corrupt_reference(reference, paper, other_papers, api) def check_cited_by(): print("\nCheck Cited by") api = API() papers = api.get_all_paper() for i, paper in enumerate(papers): progressBar(i, len(papers)) for cited_paper_id in paper.cited_by: if not api.contains_paper(cited_paper_id): paper.cited_by.remove(cited_paper_id) api.client.update_paper(paper) continue cited_paper = api.get_paper(cited_paper_id) cited_paper_refs = [ref.get_paper_id() for ref in cited_paper.references if ref.get_paper_id()] if cited_paper_refs.count(paper.id) == 0: print() paper.cited_by.remove(cited_paper_id) api.client.update_paper(paper) link_references_to_paper(cited_paper, paper, api) def perform_checks(): check_cited_by() remove_duplicates_from_cited_by() check_references() if __name__ == "__main__": perform_checks() exit(0)
thomasmauerhofer/search-engine
src/setup/check_for_currupt_references.py
Python
mit
2,124
import { NgModule, Provider } from '@angular/core'; import { NgxsModule } from '@ngxs/store'; import { AppSoundcloudService } from './soundcloud.service'; import { AppSoundcloudState } from './soundcloud.store'; import { AppSoundcloudApiService } from './soundcloud-api.service'; export const soundcloudStoreModuleProviders: Provider[] = [ AppSoundcloudService, AppSoundcloudApiService, ]; @NgModule({ imports: [NgxsModule.forFeature([AppSoundcloudState])], }) export class AppSoundcloudStoreModule {}
rfprod/dnbhub
src/app/store/soundcloud/soundcloud.module.ts
TypeScript
mit
511
package com.tkmdpa.taf.definitions.pantheon; import com.tkmdpa.taf.steps.pantheon.UserAccountSteps; import net.thucydides.core.annotations.Steps; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Then; import org.jbehave.core.annotations.When; public class UserAccountDefinition { @Steps UserAccountSteps userAccountPage; @When("navigate to Pantheon Edit Profile page from User Account page") public void navigateToEditProfile(){ userAccountPage.navigateToEditProfilePage(); } @Given("navigate to Pantheon Add New App page from User Account page") @When("navigate to Pantheon Add New App page from User Account page") public void navigateToAddNewApp(){ userAccountPage.navigateToAddNewAppPage(); } @Given("all the applications were deleted") public void allAppsWereDeleted(){ userAccountPage.deleteAllApps(); } @Then("check general page elements for Pantheon User Account page") public void checkGeneralPageElements(){ userAccountPage.checkIfTitleIsCorrect(); userAccountPage.checkGeneralPageElements(); } }
ticketmaster-api/ticketmaster-api.github.io
tests/serenity/src/test/java/com/tkmdpa/taf/definitions/pantheon/UserAccountDefinition.java
Java
mit
1,145
// $Id: CurrentFunction.java 96 2005-02-28 21:07:29Z blindsey $ package com.blnz.xsl.expr; import com.blnz.xsl.om.*; /** * Represents the XSLT Function: node-set current() * * The current function returns a node-set that has the * current node as its only member. For an outermost * expression (an expression not occurring within * another expression), the current node is always the same * as the context node. Thus, */ class CurrentFunction extends Function0 { ConvertibleExpr makeCallExpr() { return new ConvertibleNodeSetExpr() { public NodeIterator eval(Node node, ExprContext context) throws XSLException { return new SingleNodeIterator(context.getCurrent(node)); } }; } }
blnz/palomar
src/main/java/com/blnz/xsl/expr/CurrentFunction.java
Java
mit
874
export { default } from './src/layout-container.vue';
wisedu/bh-mint-ui2
packages/layout-container/index.js
JavaScript
mit
54
@extends('masterPage') @section('content') <div class="box"> <div class="box-header"><h3 class="box-title"> Page3</h3></div> <!-- /.box-header --> <div class="box-body"> <form role="form"> <div class="box-body"> <div class="form-group"> <ul> <li><label><input type="checkbox"> NO.278 FORM </label></li> <li><label><input type="checkbox"> NO.160 FORM </label></li> <li><label><input type="checkbox"> NO.169 FORM </label></li> <li><label><input type="checkbox"> NO.261 FORM </label></li> <li><label><input type="checkbox"> NO.157 FORM </label></li> </ul> </div> </div><!-- /.box-body --> <div class="box-footer"> <button type="submit" class="btn btn-primary">Update</button> </div> </form> </div><!-- /.box-body --> </div> @endsection
benAsiri/divisionalSecSystem
resources/views/HR/yearly_Increment_Calc/YICPage3.blade.php
PHP
mit
1,113
require 'rails_helper' def create_service(student, educator) FactoryGirl.create(:service, { student: student, recorded_by_educator: educator, provided_by_educator_name: 'Muraki, Mari' }) end describe StudentsController, :type => :controller do describe '#show' do let!(:school) { FactoryGirl.create(:school) } let(:educator) { FactoryGirl.create(:educator_with_homeroom) } let(:student) { FactoryGirl.create(:student, :with_risk_level, school: school) } let(:homeroom) { student.homeroom } let!(:student_school_year) { student.student_school_years.first || StudentSchoolYear.create!( student: student, school_year: SchoolYear.first_or_create! ) } def make_request(options = { student_id: nil, format: :html }) request.env['HTTPS'] = 'on' get :show, id: options[:student_id], format: options[:format] end context 'when educator is not logged in' do it 'redirects to sign in page' do make_request({ student_id: student.id, format: :html }) expect(response).to redirect_to(new_educator_session_path) end end context 'when educator is logged in' do before { sign_in(educator) } context 'educator has schoolwide access' do let(:educator) { FactoryGirl.create(:educator, :admin, school: school) } let(:serialized_data) { assigns(:serialized_data) } it 'is successful' do make_request({ student_id: student.id, format: :html }) expect(response).to be_success end it 'assigns the student\'s serialized data correctly' do make_request({ student_id: student.id, format: :html }) expect(serialized_data[:current_educator]).to eq educator expect(serialized_data[:student]["id"]).to eq student.id expect(serialized_data[:dibels]).to eq [] expect(serialized_data[:feed]).to eq ({ event_notes: [], services: {active: [], discontinued: []}, deprecated: {interventions: []} }) expect(serialized_data[:service_types_index]).to eq({ 502 => {:id=>502, :name=>"Attendance Officer"}, 503 => {:id=>503, :name=>"Attendance Contract"}, 504 => {:id=>504, :name=>"Behavior Contract"}, 505 => {:id=>505, :name=>"Counseling, in-house"}, 506 => {:id=>506, :name=>"Counseling, outside"}, 507 => {:id=>507, :name=>"Reading intervention"}, 508 => {:id=>508, :name=>"Math intervention"}, }) expect(serialized_data[:event_note_types_index]).to eq({ 300 => {:id=>300, :name=>"SST Meeting"}, 301 => {:id=>301, :name=>"MTSS Meeting"}, 302 => {:id=>302, :name=>"Parent conversation"}, 304 => {:id=>304, :name=>"Something else"}, }) expect(serialized_data[:educators_index]).to eq({ educator.id => {:id=>educator.id, :email=>educator.email, :full_name=>nil} }) expect(serialized_data[:attendance_data].keys).to eq [ :discipline_incidents, :tardies, :absences ] end context 'student has multiple discipline incidents' do let!(:student) { FactoryGirl.create(:student, school: school) } let(:most_recent_school_year) { student.most_recent_school_year } let(:serialized_data) { assigns(:serialized_data) } let(:attendance_data) { serialized_data[:attendance_data] } let(:discipline_incidents) { attendance_data[:discipline_incidents] } let!(:more_recent_incident) { FactoryGirl.create( :discipline_incident, student_school_year: student.student_school_years.first, occurred_at: Time.now - 1.day ) } let!(:less_recent_incident) { FactoryGirl.create( :discipline_incident, student_school_year: most_recent_school_year, occurred_at: Time.now - 2.days ) } it 'sets the correct order' do make_request({ student_id: student.id, format: :html }) expect(discipline_incidents).to eq [more_recent_incident, less_recent_incident] end end context 'educator has grade level access' do let(:educator) { FactoryGirl.create(:educator, grade_level_access: [student.grade], school: school )} it 'is successful' do make_request({ student_id: student.id, format: :html }) expect(response).to be_success end end context 'educator has homeroom access' do let(:educator) { FactoryGirl.create(:educator, school: school) } before { homeroom.update(educator: educator) } it 'is successful' do make_request({ student_id: student.id, format: :html }) expect(response).to be_success end end context 'educator does not have schoolwide, grade level, or homeroom access' do let(:educator) { FactoryGirl.create(:educator, school: school) } it 'fails' do make_request({ student_id: student.id, format: :html }) expect(response).to redirect_to(not_authorized_path) end end context 'educator has some grade level access but for the wrong grade' do let(:student) { FactoryGirl.create(:student, :with_risk_level, grade: '1', school: school) } let(:educator) { FactoryGirl.create(:educator, grade_level_access: ['KF'], school: school) } it 'fails' do make_request({ student_id: student.id, format: :html }) expect(response).to redirect_to(not_authorized_path) end end context 'educator access restricted to SPED students' do let(:educator) { FactoryGirl.create(:educator, grade_level_access: ['1'], restricted_to_sped_students: true, school: school ) } context 'student in SPED' do let(:student) { FactoryGirl.create(:student, :with_risk_level, grade: '1', program_assigned: 'Sp Ed', school: school) } it 'is successful' do make_request({ student_id: student.id, format: :html }) expect(response).to be_success end end context 'student in Reg Ed' do let(:student) { FactoryGirl.create(:student, :with_risk_level, grade: '1', program_assigned: 'Reg Ed') } it 'fails' do make_request({ student_id: student.id, format: :html }) expect(response).to redirect_to(not_authorized_path) end end end context 'educator access restricted to ELL students' do let(:educator) { FactoryGirl.create(:educator, grade_level_access: ['1'], restricted_to_english_language_learners: true, school: school ) } context 'limited English proficiency' do let(:student) { FactoryGirl.create(:student, :with_risk_level, grade: '1', limited_english_proficiency: 'FLEP', school: school) } it 'is successful' do make_request({ student_id: student.id, format: :html }) expect(response).to be_success end end context 'fluent in English' do let(:student) { FactoryGirl.create(:student, :with_risk_level, grade: '1', limited_english_proficiency: 'Fluent') } it 'fails' do make_request({ student_id: student.id, format: :html }) expect(response).to redirect_to(not_authorized_path) end end end end end end describe '#service' do let!(:school) { FactoryGirl.create(:school) } def make_post_request(student, service_params = {}) request.env['HTTPS'] = 'on' post :service, format: :json, id: student.id, service: service_params end context 'admin educator logged in' do let!(:educator) { FactoryGirl.create(:educator, :admin, school: school) } let!(:provided_by_educator) { FactoryGirl.create(:educator, school: school) } let!(:student) { FactoryGirl.create(:student, school: school) } before do sign_in(educator) end context 'when valid request' do let!(:post_params) do { student_id: student.id, service_type_id: 503, date_started: '2016-02-22', provided_by_educator_id: provided_by_educator.id } end it 'creates a new service' do expect { make_post_request(student, post_params) }.to change(Service, :count).by 1 end it 'responds with JSON' do make_post_request(student, post_params) expect(response.status).to eq 200 make_post_request(student, post_params) expect(response.headers["Content-Type"]).to eq 'application/json; charset=utf-8' expect(JSON.parse(response.body).keys).to contain_exactly( 'id', 'student_id', 'provided_by_educator_name', 'recorded_by_educator_id', 'service_type_id', 'recorded_at', 'date_started', 'discontinued_by_educator_id', 'discontinued_recorded_at' ) end end context 'when recorded_by_educator_id' do it 'ignores the educator_id' do make_post_request(student, { student_id: student.id, service_type_id: 503, date_started: '2016-02-22', provided_by_educator_id: provided_by_educator.id, recorded_by_educator_id: 350 }) response_body = JSON.parse(response.body) expect(response_body['recorded_by_educator_id']).to eq educator.id expect(response_body['recorded_by_educator_id']).not_to eq 350 end end context 'when missing params' do it 'fails with error messages' do make_post_request(student, { text: 'foo' }) expect(response.status).to eq 422 response_body = JSON.parse(response.body) expect(response_body).to eq({ "errors" => [ "Student can't be blank", "Service type can't be blank", "Date started can't be blank" ] }) end end end end describe '#names' do let(:school) { FactoryGirl.create(:healey) } def make_request(query) request.env['HTTPS'] = 'on' get :names, q: query, format: :json end context 'admin educator logged in' do let!(:educator) { FactoryGirl.create(:educator, :admin, school: school) } before { sign_in(educator) } context 'query matches student name' do let!(:juan) { FactoryGirl.create(:student, first_name: 'Juan', school: school, grade: '5') } let!(:jacob) { FactoryGirl.create(:student, first_name: 'Jacob', grade: '5') } it 'is successful' do make_request('j') expect(response).to be_success end it 'returns student name and id' do make_request('j') expect(assigns(:sorted_results)).to eq [{ label: "Juan - HEA - 5", value: juan.id }] end end context 'does not match student name' do it 'is successful' do make_request('j') expect(response).to be_success end it 'returns an empty array' do make_request('j') expect(assigns(:sorted_results)).to eq [] end end end context 'educator without authorization to students' do let!(:educator) { FactoryGirl.create(:educator) } before { sign_in(educator) } context 'query matches student name' do let(:healey) { FactoryGirl.create(:healey) } let!(:juan) { FactoryGirl.create(:student, first_name: 'Juan', school: healey, grade: '5') } it 'returns an empty array' do make_request('j') expect(assigns(:sorted_results)).to eq [] end end end context 'educator not logged in' do it 'is not successful' do make_request('j') expect(response.status).to eq 401 expect(response.body).to include "You need to sign in before continuing." end end end describe '#serialize_student_for_profile' do it 'returns a hash with the additional keys that UI code expects' do student = FactoryGirl.create(:student) serialized_student = controller.send(:serialize_student_for_profile, student) expect(serialized_student.keys).to include(*[ 'student_risk_level', 'absences_count', 'tardies_count', 'school_name', 'homeroom_name', 'discipline_incidents_count' ]) end end describe '#calculate_student_score' do context 'happy path' do let(:search_tokens) { ['don', 'kenob'] } it 'is 0.0 when no matches' do result = controller.send(:calculate_student_score, Student.new(first_name: 'Mickey', last_name: 'Mouse'), search_tokens) expect(result).to eq 0.0 end it 'is 0.5 when first name only matches' do result = controller.send(:calculate_student_score, Student.new(first_name: 'Donald', last_name: 'Mouse'), search_tokens) expect(result).to eq 0.5 end it 'is 0.5 when last name only matches' do result = controller.send(:calculate_student_score, Student.new(first_name: 'zzz', last_name: 'Kenobiliiii'), search_tokens) expect(result).to eq 0.5 end it 'is 1.0 when both names match' do result = controller.send(:calculate_student_score, Student.new(first_name: 'Donald', last_name: 'Kenobi'), search_tokens) expect(result).to eq 1.0 end end it 'works for bug test case' do search_tokens = ['al','p'] aladdin_score = controller.send(:calculate_student_score, Student.new(first_name: 'Aladdin', last_name: 'Poppins'), search_tokens) pluto_score = controller.send(:calculate_student_score, Student.new(first_name: 'Pluto', last_name: 'Poppins'), search_tokens) expect(aladdin_score).to be > pluto_score expect(aladdin_score).to eq 1 expect(pluto_score).to eq 0.5 end end describe '#student_feed' do let(:student) { FactoryGirl.create(:student) } let(:educator) { FactoryGirl.create(:educator, :admin) } let!(:service) { create_service(student, educator) } it 'returns services' do feed = controller.send(:student_feed, student) expect(feed.keys).to eq([:event_notes, :services, :deprecated]) expect(feed[:services].keys).to eq [:active, :discontinued] expect(feed[:services][:active].first[:id]).to eq service.id end context 'after service is discontinued' do before do DiscontinuedService.create!({ service_id: service.id, recorded_by_educator_id: educator.id, recorded_at: Time.now }) end it 'filters it' do feed = controller.send(:student_feed, student) expect(feed[:services][:active].size).to eq 0 expect(feed[:services][:discontinued].first[:id]).to eq service.id end end end describe '#restricted_notes' do let!(:school) { FactoryGirl.create(:school) } let(:educator) { FactoryGirl.create(:educator_with_homeroom) } let(:student) { FactoryGirl.create(:student, school: school) } def make_request(student) request.env['HTTPS'] = 'on' get :restricted_notes, id: student.id end context 'when educator is logged in' do before { sign_in(educator) } context 'educator cannot view restricted notes' do let(:educator) { FactoryGirl.create(:educator, :admin, can_view_restricted_notes: false, school: school) } it 'is not successful' do make_request(student) expect(response).to redirect_to(not_authorized_path) end end context 'educator can view restricted notes but is not authorized for student' do let(:educator) { FactoryGirl.create(:educator, schoolwide_access: false, can_view_restricted_notes: true, school: school) } it 'is not successful' do make_request(student) expect(response).to redirect_to(not_authorized_path) end end context 'educator can view restricted notes' do let(:educator) { FactoryGirl.create(:educator, :admin, can_view_restricted_notes: true, school: school) } it 'is successful' do make_request(student) expect(response).to be_success end end end end describe '#sped_referral' do let(:educator) { FactoryGirl.create(:educator, :admin, school: school) } let(:school) { FactoryGirl.create(:school) } let(:service) { FactoryGirl.create(:service, student: student) } let(:student) { FactoryGirl.create(:student, :with_risk_level, school: school) } let(:student_school_year) { FactoryGirl.create(:student_school_year, student: student) } def make_request(options = { student_id: nil, format: :pdf }) request.env['HTTPS'] = 'on' get :sped_referral, id: options[:student_id], format: options[:format] end context 'when educator is not logged in' do it 'does not render a SPED referral' do make_request({ student_id: student.id, format: :pdf }) expect(response.status).to eq 401 end end context 'when educator is logged in' do before do sign_in(educator) make_request({ student_id: student.id, format: :pdf }) end context 'educator has schoolwide access' do it 'is successful' do expect(response).to be_success end it 'assigns the student correctly' do expect(assigns(:student)).to eq student end it 'assigns the student\'s services correctly' do expect(assigns(:services)).to eq student.services end it 'assigns the student\'s school years correctly' do expect(assigns(:student_school_years)).to eq student.student_school_years end end end end end
erose/studentinsights
spec/controllers/students_controller_spec.rb
Ruby
mit
19,225
/* *@author jaime P. Bravo */ $(document).ready(function () { //forms general function sendDataWithAjax(type, url, data) { return $.ajax({ type: type, url: url, data: data, dataType: 'json', beforeSend: function () { console.log('Enviando...'); }, success: function (response) { }, error: function (jqXHR, textStatus, errorThrown) { console.log('Código:' + jqXHR.status); console.log('Error AJAX: ' + textStatus); console.log('Tipo Error: ' + errorThrown); } }); } // Form create $('.create-form-view').submit(function (e) { e.preventDefault(); var url = $(this).attr('action'); var data = $(this).serialize(); var torre = sendDataWithAjax('POST', url, data); torre.success(function (response) { if (response.type === 'error') { generateNoty('bottomLeft', response.message, 'error'); } else { generateNoty('bottomLeft', response.message, 'success'); $('.form-group.input-type').removeClass('has-error'); $('.error-icon').hide(); resetForms('create-form-view'); if (response.login === 'si') { window.location.href = '/matters/index.php/inicio'; } } }); }); $('.dropdown.logo').click(function () { window.location.href = '/matters/index.php/inicio'; }); //Noty Master function function generateNoty(layout, text, type) { var n = noty({ text: text, type: type, dismissQueue: true, layout: layout, theme: 'relax', timeout: 4000 }); } //Datatables $('.table-datatable').DataTable({ "bStateSave": true }); }); //End jQuery function refreshTable(table) { $('.' + table + '').DataTable().ajax.reload(); } //Helper functions function resetForms(form_class) { $('.' + form_class + '').get(0).reset(); } //Hover submenus $(function () { $(".dropdown").hover( function () { $('.dropdown-menu', this).stop(true, true).fadeIn("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); $('b', this).hover().toggleClass("caret caret-reversed"); }, function () { $('.dropdown-menu', this).stop(true, true).fadeOut("fast"); $(this).toggleClass('open'); $('b', this).toggleClass("caret caret-up"); $('b', this).hover().toggleClass("caret caret-reversed"); }); });
fireflex/matters
assets/js/general.js
JavaScript
mit
2,874
<?php class Ess_M2ePro_Sql_Upgrade_v6_4_14__v6_5_0_16_AllFeatures extends Ess_M2ePro_Model_Upgrade_Feature_AbstractFeature { //######################################## public function execute() { $tablesList = array( 'processing_request', 'product_change', 'locked_object', 'lock_item', 'cache_config', 'primary_config', 'config', 'synchronization_config' ); $backup = new Ess_M2ePro_Model_Upgrade_Backup(array($this->_installer, $tablesList)); if (!$backup->isExists()) { $backup->create(); } //######################################## $schema = new Ess_M2ePro_Model_Upgrade_Migration_ToVersion651_Schema($this->_installer); //######################################## $schema->schemaCreate(); //######################################## $migration = new Ess_M2ePro_Model_Upgrade_Migration_ToVersion651_General($this->_installer); $migration->run(); $migration = new Ess_M2ePro_Model_Upgrade_Migration_ToVersion651_NewProcessing($this->_installer); $migration->run(); $migration = new Ess_M2ePro_Model_Upgrade_Migration_ToVersion651_Configs($this->_installer); $migration->run(); $migration = new Ess_M2ePro_Model_Upgrade_Migration_ToVersion651_EbayTables($this->_installer); $migration->run(); $migration = new Ess_M2ePro_Model_Upgrade_Migration_ToVersion651_AmazonTables($this->_installer); $migration->run(); //######################################## $schema->schemaDelete(); } //######################################## }
portchris/NaturalRemedyCompany
src/app/code/community/Ess/M2ePro/sql/Upgrade/v6_4_14__v6_5_0_16/AllFeatures.php
PHP
mit
1,746
var LedgerRequestHandler = require('../../helpers/ledgerRequestHandler'); /** * @api {post} /gl/:LEDGER_ID/add-filter add filter * @apiGroup Ledger.Utils * @apiVersion v1.0.0 * * @apiDescription * Add a filter for caching balances. This will speed up balance * requests containing a matching filters. * * @apiParam {CounterpartyId[]} excludingCounterparties * IDs of transaction counterparties to exclude with the filter * @apiParam {AccountId[]} excludingContraAccounts * IDs of transaction countra accounts to exclude with the filter * @apiParam {CounterpartyId[]} [withCounterparties] * IDs of transaction counterparties to limit with the filter. All others will be * excluded. * * @apiParamExample {x-www-form-urlencoded} Request-Example: * excludingCounterparties=foobar-llc,foobar-inc * excludingContraAccounts=chase-saving,chase-checking * withCounterparties=staples,ubs */ module.exports = new LedgerRequestHandler({ validateBody: { 'excludingCounterparties': { type: 'string', required: true }, 'excludingContraAccounts': { type: 'string', required: true }, 'withCounterparties': { type: 'string' } }, commitLedger: true }).handle(function (options, cb) { var excludingCounterparties = options.body.excludingCounterparties.split(','); var excludingContraAccounts = options.body.excludingContraAccounts.split(','); var withCounterparties = options.body.withCounterparties && options.body.withCounterparties.split(','); var ledger = options.ledger; ledger.registerFilter({ excludingCounterparties: excludingCounterparties, excludingContraAccounts: excludingContraAccounts, withCounterparties: withCounterparties }); cb(null, ledger.toJson()); });
electronifie/accountifie-svc
lib/routes/gl/addFilter.js
JavaScript
mit
1,756
from polyphony import testbench def g(x): if x == 0: return 0 return 1 def h(x): if x == 0: pass def f(v, i, j, k): if i == 0: return v elif i == 1: return v elif i == 2: h(g(j) + g(k)) return v elif i == 3: for m in range(j): v += 2 return v else: for n in range(i): v += 1 return v def if28(code, r1, r2, r3, r4): if code == 0: return f(r1, r2, r3, r4) return 0 @testbench def test(): assert 1 == if28(0, 1, 1, 0, 0) assert 2 == if28(0, 2, 0, 0, 0) assert 3 == if28(0, 3, 1, 0, 0) assert 4 == if28(0, 4, 2, 0, 0) assert 5 == if28(0, 5, 2, 1, 1) assert 6 == if28(0, 6, 2, 2, 2) assert 7 == if28(0, 7, 3, 0, 0) assert 10 == if28(0, 8, 3, 1, 1) assert 13 == if28(0, 9, 3, 2, 2) assert 14 == if28(0, 10, 4, 0, 0) test()
ktok07b6/polyphony
tests/if/if28.py
Python
mit
922
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link href="css/admin.css" type="text/css" rel="stylesheet"> <script src="js/main/jquery.js"></script>
alexander-shibisty/subscribeonme
administrator/blocks/main/header.php
PHP
mit
180
package postactions import ( "net/http" "github.com/fragmenta/auth/can" "github.com/fragmenta/mux" "github.com/fragmenta/server" "github.com/fragmenta/view" "github.com/fragmenta/fragmenta-cms/src/lib/session" "github.com/fragmenta/fragmenta-cms/src/posts" "github.com/fragmenta/fragmenta-cms/src/users" ) // HandleUpdateShow renders the form to update a post. func HandleUpdateShow(w http.ResponseWriter, r *http.Request) error { // Fetch the params params, err := mux.Params(r) if err != nil { return server.InternalError(err) } // Find the post post, err := posts.Find(params.GetInt(posts.KeyName)) if err != nil { return server.NotFoundError(err) } // Authorise update post user := session.CurrentUser(w, r) err = can.Update(post, user) if err != nil { return server.NotAuthorizedError(err) } // Fetch the users authors, err := users.FindAll(users.Where("role=?", users.Admin)) if err != nil { return server.InternalError(err) } // Render the template view := view.NewRenderer(w, r) view.AddKey("currentUser", user) view.AddKey("post", post) view.AddKey("authors", authors) return view.Render() } // HandleUpdate handles the POST of the form to update a post func HandleUpdate(w http.ResponseWriter, r *http.Request) error { // Fetch the params params, err := mux.Params(r) if err != nil { return server.InternalError(err) } // Find the post post, err := posts.Find(params.GetInt(posts.KeyName)) if err != nil { return server.NotFoundError(err) } // Check the authenticity token err = session.CheckAuthenticity(w, r) if err != nil { return err } // Authorise update post user := session.CurrentUser(w, r) err = can.Update(post, user) if err != nil { return server.NotAuthorizedError(err) } // Validate the params, removing any we don't accept postParams := post.ValidateParams(params.Map(), posts.AllowedParams()) err = post.Update(postParams) if err != nil { return server.InternalError(err) } // Redirect to post return server.Redirect(w, r, post.ShowURL()) }
fragmenta/fragmenta-cms
src/posts/actions/update.go
GO
mit
2,058
/* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var _ = require('underscore'); var common = require('./common'); var groups = function(groups) { var buf = this.buf; buf.appendUInt32BE(groups.length); _.each(groups, function(group) { common.appendString(buf, group); }); return this; }; exports.encode = function(version) { var ret = common.encode(common.DESCRIBEGROUP_API, version); ret.groups = groups; return ret; };
pelger/Kafkaesque
lib/message/request/describeGroups.js
JavaScript
mit
1,146
package main.habitivity.services; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * Created by Shally on 2017-12-01. */ public class ConnectivityService implements IConnectivityService { private Context context; private OnConnectivityChangedListener onConnectivityChangedListener; /** * Instantiates a new Android connectivity service. * * @param context the context */ public ConnectivityService(Context context) { this.context = context; registerConnectivityListener(); } @Override public boolean isInternetAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } @Override public void setOnConnectivityChangedListener(OnConnectivityChangedListener onConnectivityChangedListener) { this.onConnectivityChangedListener = onConnectivityChangedListener; dispatchConnectivityChange(); } private void registerConnectivityListener() { context.registerReceiver(new ConnectivityListener(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } private void dispatchConnectivityChange() { if (onConnectivityChangedListener != null) { onConnectivityChangedListener.onConnectivityChanged(isInternetAvailable()); } } private class ConnectivityListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { dispatchConnectivityChange(); } } }
CMPUT301F17T20/Habitivity
app/src/main/java/main/habitivity/services/ConnectivityService.java
Java
mit
1,916
<?php /* @WebProfiler/Collector/twig.html.twig */ class __TwigTemplate_793d44b82b00b11058566fd43a938457dfbf8bd2ba53b4f3f33086ff7eecb7a9 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("@WebProfiler/Profiler/layout.html.twig", "@WebProfiler/Collector/twig.html.twig", 1); $this->blocks = array( 'toolbar' => array($this, 'block_toolbar'), 'menu' => array($this, 'block_menu'), 'panel' => array($this, 'block_panel'), ); } protected function doGetParent(array $context) { return "@WebProfiler/Profiler/layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $__internal_885a323ef25a1b959093aeade41483e120e0de4e3d9a6e34cb8e58b6f7319fe2 = $this->env->getExtension("native_profiler"); $__internal_885a323ef25a1b959093aeade41483e120e0de4e3d9a6e34cb8e58b6f7319fe2->enter($__internal_885a323ef25a1b959093aeade41483e120e0de4e3d9a6e34cb8e58b6f7319fe2_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@WebProfiler/Collector/twig.html.twig")); $this->parent->display($context, array_merge($this->blocks, $blocks)); $__internal_885a323ef25a1b959093aeade41483e120e0de4e3d9a6e34cb8e58b6f7319fe2->leave($__internal_885a323ef25a1b959093aeade41483e120e0de4e3d9a6e34cb8e58b6f7319fe2_prof); } // line 3 public function block_toolbar($context, array $blocks = array()) { $__internal_0ed5225f2697c099b90f1fc0cf34b6562fea659c5d3d505a723d8ba8a596f87e = $this->env->getExtension("native_profiler"); $__internal_0ed5225f2697c099b90f1fc0cf34b6562fea659c5d3d505a723d8ba8a596f87e->enter($__internal_0ed5225f2697c099b90f1fc0cf34b6562fea659c5d3d505a723d8ba8a596f87e_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "toolbar")); // line 4 echo " "; $context["time"] = (($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "templatecount", array())) ? (sprintf("%0.0f", $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "time", array()))) : ("n/a")); // line 5 echo " "; ob_start(); // line 6 echo " "; echo twig_include($this->env, $context, "@WebProfiler/Icon/twig.svg"); echo " <span class=\"sf-toolbar-value\">"; // line 7 echo twig_escape_filter($this->env, (isset($context["time"]) ? $context["time"] : $this->getContext($context, "time")), "html", null, true); echo "</span> <span class=\"sf-toolbar-label\">ms</span> "; $context["icon"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset()); // line 10 echo " "; // line 11 ob_start(); // line 12 echo " <div class=\"sf-toolbar-info-piece\"> <b>Render Time</b> <span>"; // line 14 echo twig_escape_filter($this->env, (isset($context["time"]) ? $context["time"] : $this->getContext($context, "time")), "html", null, true); echo " ms</span> </div> <div class=\"sf-toolbar-info-piece\"> <b>Template Calls</b> <span class=\"sf-toolbar-status\">"; // line 18 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "templatecount", array()), "html", null, true); echo "</span> </div> <div class=\"sf-toolbar-info-piece\"> <b>Block Calls</b> <span class=\"sf-toolbar-status\">"; // line 22 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "blockcount", array()), "html", null, true); echo "</span> </div> <div class=\"sf-toolbar-info-piece\"> <b>Macro Calls</b> <span class=\"sf-toolbar-status\">"; // line 26 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "macrocount", array()), "html", null, true); echo "</span> </div> "; $context["text"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset()); // line 29 echo " "; // line 30 echo twig_include($this->env, $context, "@WebProfiler/Profiler/toolbar_item.html.twig", array("link" => (isset($context["profiler_url"]) ? $context["profiler_url"] : $this->getContext($context, "profiler_url")))); echo " "; $__internal_0ed5225f2697c099b90f1fc0cf34b6562fea659c5d3d505a723d8ba8a596f87e->leave($__internal_0ed5225f2697c099b90f1fc0cf34b6562fea659c5d3d505a723d8ba8a596f87e_prof); } // line 33 public function block_menu($context, array $blocks = array()) { $__internal_e185df5c746139903cb6337f950162fcd4fbfa9902d8e610f7f9b358932fe565 = $this->env->getExtension("native_profiler"); $__internal_e185df5c746139903cb6337f950162fcd4fbfa9902d8e610f7f9b358932fe565->enter($__internal_e185df5c746139903cb6337f950162fcd4fbfa9902d8e610f7f9b358932fe565_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "menu")); // line 34 echo " <span class=\"label\"> <span class=\"icon\">"; // line 35 echo twig_include($this->env, $context, "@WebProfiler/Icon/twig.svg"); echo "</span> <strong>Twig</strong> </span> "; $__internal_e185df5c746139903cb6337f950162fcd4fbfa9902d8e610f7f9b358932fe565->leave($__internal_e185df5c746139903cb6337f950162fcd4fbfa9902d8e610f7f9b358932fe565_prof); } // line 40 public function block_panel($context, array $blocks = array()) { $__internal_78c96d8d3b2ff40962666937ec89c012feae4a79819fc33dc91784001f046169 = $this->env->getExtension("native_profiler"); $__internal_78c96d8d3b2ff40962666937ec89c012feae4a79819fc33dc91784001f046169->enter($__internal_78c96d8d3b2ff40962666937ec89c012feae4a79819fc33dc91784001f046169_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "panel")); // line 41 echo " "; if (($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "templatecount", array()) == 0)) { // line 42 echo " <h2>Twig</h2> <div class=\"empty\"> <p>No Twig templates were rendered for this request.</p> </div> "; } else { // line 48 echo " <h2>Twig Metrics</h2> <div class=\"metrics\"> <div class=\"metric\"> <span class=\"value\">"; // line 52 echo twig_escape_filter($this->env, sprintf("%0.0f", $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "time", array())), "html", null, true); echo " <span class=\"unit\">ms</span></span> <span class=\"label\">Render time</span> </div> <div class=\"metric\"> <span class=\"value\">"; // line 57 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "templatecount", array()), "html", null, true); echo "</span> <span class=\"label\">Template calls</span> </div> <div class=\"metric\"> <span class=\"value\">"; // line 62 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "blockcount", array()), "html", null, true); echo "</span> <span class=\"label\">Block calls</span> </div> <div class=\"metric\"> <span class=\"value\">"; // line 67 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "macrocount", array()), "html", null, true); echo "</span> <span class=\"label\">Macro calls</span> </div> </div> <p class=\"help\"> Render time includes sub-requests rendering time (if any). </p> <h2>Rendered Templates</h2> <table> <thead> <tr> <th scope=\"col\">Template Name</th> <th scope=\"col\">Render Count</th> </tr> </thead> <tbody> "; // line 86 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "templates", array())); foreach ($context['_seq'] as $context["template"] => $context["count"]) { // line 87 echo " <tr> <td>"; // line 88 echo twig_escape_filter($this->env, $context["template"], "html", null, true); echo "</td> <td class=\"font-normal\">"; // line 89 echo twig_escape_filter($this->env, $context["count"], "html", null, true); echo "</td> </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['template'], $context['count'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 92 echo " </tbody> </table> <h2>Rendering Call Graph</h2> <div id=\"twig-dump\"> "; // line 98 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "htmlcallgraph", array()), "html", null, true); echo " </div> "; } $__internal_78c96d8d3b2ff40962666937ec89c012feae4a79819fc33dc91784001f046169->leave($__internal_78c96d8d3b2ff40962666937ec89c012feae4a79819fc33dc91784001f046169_prof); } public function getTemplateName() { return "@WebProfiler/Collector/twig.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 224 => 98, 216 => 92, 207 => 89, 203 => 88, 200 => 87, 196 => 86, 174 => 67, 166 => 62, 158 => 57, 150 => 52, 144 => 48, 136 => 42, 133 => 41, 127 => 40, 116 => 35, 113 => 34, 107 => 33, 98 => 30, 95 => 29, 89 => 26, 82 => 22, 75 => 18, 68 => 14, 64 => 12, 62 => 11, 59 => 10, 53 => 7, 48 => 6, 45 => 5, 42 => 4, 36 => 3, 11 => 1,); } } /* {% extends '@WebProfiler/Profiler/layout.html.twig' %}*/ /* */ /* {% block toolbar %}*/ /* {% set time = collector.templatecount ? '%0.0f'|format(collector.time) : 'n/a' %}*/ /* {% set icon %}*/ /* {{ include('@WebProfiler/Icon/twig.svg') }}*/ /* <span class="sf-toolbar-value">{{ time }}</span>*/ /* <span class="sf-toolbar-label">ms</span>*/ /* {% endset %}*/ /* */ /* {% set text %}*/ /* <div class="sf-toolbar-info-piece">*/ /* <b>Render Time</b>*/ /* <span>{{ time }} ms</span>*/ /* </div>*/ /* <div class="sf-toolbar-info-piece">*/ /* <b>Template Calls</b>*/ /* <span class="sf-toolbar-status">{{ collector.templatecount }}</span>*/ /* </div>*/ /* <div class="sf-toolbar-info-piece">*/ /* <b>Block Calls</b>*/ /* <span class="sf-toolbar-status">{{ collector.blockcount }}</span>*/ /* </div>*/ /* <div class="sf-toolbar-info-piece">*/ /* <b>Macro Calls</b>*/ /* <span class="sf-toolbar-status">{{ collector.macrocount }}</span>*/ /* </div>*/ /* {% endset %}*/ /* */ /* {{ include('@WebProfiler/Profiler/toolbar_item.html.twig', { link: profiler_url }) }}*/ /* {% endblock %}*/ /* */ /* {% block menu %}*/ /* <span class="label">*/ /* <span class="icon">{{ include('@WebProfiler/Icon/twig.svg') }}</span>*/ /* <strong>Twig</strong>*/ /* </span>*/ /* {% endblock %}*/ /* */ /* {% block panel %}*/ /* {% if collector.templatecount == 0 %}*/ /* <h2>Twig</h2>*/ /* */ /* <div class="empty">*/ /* <p>No Twig templates were rendered for this request.</p>*/ /* </div>*/ /* {% else %}*/ /* <h2>Twig Metrics</h2>*/ /* */ /* <div class="metrics">*/ /* <div class="metric">*/ /* <span class="value">{{ '%0.0f'|format(collector.time) }} <span class="unit">ms</span></span>*/ /* <span class="label">Render time</span>*/ /* </div>*/ /* */ /* <div class="metric">*/ /* <span class="value">{{ collector.templatecount }}</span>*/ /* <span class="label">Template calls</span>*/ /* </div>*/ /* */ /* <div class="metric">*/ /* <span class="value">{{ collector.blockcount }}</span>*/ /* <span class="label">Block calls</span>*/ /* </div>*/ /* */ /* <div class="metric">*/ /* <span class="value">{{ collector.macrocount }}</span>*/ /* <span class="label">Macro calls</span>*/ /* </div>*/ /* </div>*/ /* */ /* <p class="help">*/ /* Render time includes sub-requests rendering time (if any).*/ /* </p>*/ /* */ /* <h2>Rendered Templates</h2>*/ /* */ /* <table>*/ /* <thead>*/ /* <tr>*/ /* <th scope="col">Template Name</th>*/ /* <th scope="col">Render Count</th>*/ /* </tr>*/ /* </thead>*/ /* <tbody>*/ /* {% for template, count in collector.templates %}*/ /* <tr>*/ /* <td>{{ template }}</td>*/ /* <td class="font-normal">{{ count }}</td>*/ /* </tr>*/ /* {% endfor %}*/ /* </tbody>*/ /* </table>*/ /* */ /* <h2>Rendering Call Graph</h2>*/ /* */ /* <div id="twig-dump">*/ /* {{ collector.htmlcallgraph }}*/ /* </div>*/ /* {% endif %}*/ /* {% endblock %}*/ /* */
peterpangl/sso-project
var/cache/dev/twig/3c/3c143050536fee4bbe81d2075bb2515ac85282e72e70471d06862fa83c81a660.php
PHP
mit
15,225
<?php namespace Qafoo\ChangeTrack\FISCalculator; class TransactionDatabase { /** * Row based data set * * @var array */ private $data; /** * Items that occur in this data base * * @var string[] */ private $items = array(); /** * @param array $data */ public function __construct(array $data = array()) { foreach ($data as $transactionIndex => $transaction) { foreach ($transaction as $item) { $this->addItem($transactionIndex, $item); } } } /** * Adds $item to the transaction with $transactionIndex * * @param string $transactionIndex * @param \Qafoo\ChangeTrack\FISCalculator\Item $item */ public function addItem($transactionIndex, Item $item) { if (!isset($this->data[$transactionIndex])) { $this->data[$transactionIndex] = array(); } $this->data[$transactionIndex][$item->getHash()] = true; $this->items[$item->getHash()] = $item; } /** * Calculates the support for $itemSet * * @param array $itemSet * @return float */ public function support(Set $itemSet) { $occurrences = 0; foreach ($this->data as $transaction) { foreach ($itemSet as $item) { if (!isset($transaction[$item->getHash()])) { continue 2; } } $occurrences++; } return $occurrences / count($this->data); } /** * Returns the items used in this transaction data base. * * @return \Qafoo\ChangeTrack\FISCalculator\Item[] */ public function getItems() { return array_values($this->items); } }
Qafoo/changetrack
src/main/Qafoo/ChangeTrack/FISCalculator/TransactionDatabase.php
PHP
mit
1,795
// @flow /* ********************************************************** * File: Footer.js * * Brief: The react footer component * * Authors: Craig Cheney, George Whitfield * * 2017.04.27 CC - Document created * ********************************************************* */ import React, { Component } from 'react'; import { Grid, Col, Row } from 'react-bootstrap'; let mitImagePath = '../resources/img/mitLogo.png'; /* Set mitImagePath to new path */ if (process.resourcesPath !== undefined) { mitImagePath = (`${String(process.resourcesPath)}resources/img/mitLogo.png`); // mitImagePath = `${process.resourcesPath}resources/img/mitLogo.png`; } // const nativeImage = require('electron').nativeImage; // const mitLogoImage = nativeImage.createFromPath(mitImagePath); const footerStyle = { position: 'absolute', right: 0, bottom: 0, left: 0, color: '#9d9d9d', backgroundColor: '#222', height: '25px', textAlign: 'center' }; const mitLogoStyle = { height: '20px' }; const bilabLogoStyle = { height: '20px' }; export default class Footer extends Component<{}> { render() { return ( <Grid className='Footer' style={footerStyle} fluid> <Row> <Col xs={4}><img src={'../resources/img/mitLogo.png' || mitImagePath} style={mitLogoStyle} alt='MICA' /></Col> <Col xs={4}>The MICA Group &copy; 2017</Col> <Col xs={4}><img src='../resources/img/bilabLogo_white.png' style={bilabLogoStyle} alt='BioInstrumentation Lab' /></Col> </Row> </Grid> ); } } /* [] - END OF FILE */
TheCbac/MICA-Desktop
app/components/Footer.js
JavaScript
mit
1,554
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import {Typography, Popover, Input, Select, Checkbox} from 'antd'; import {DataInspectorSetValue} from './DataInspectorNode'; import {PureComponent} from 'react'; import styled from '@emotion/styled'; import {SketchPicker, CompactPicker} from 'react-color'; import React, {KeyboardEvent} from 'react'; import {HighlightContext} from '../Highlight'; import {parseColor} from '../../utils/parseColor'; import {TimelineDataDescription} from './TimelineDataDescription'; import {theme} from '../theme'; import {EditOutlined} from '@ant-design/icons'; import type {CheckboxChangeEvent} from 'antd/lib/checkbox'; const {Link} = Typography; // Based on FIG UI Core, TODO: does that still makes sense? export const presetColors = Object.values({ blue: '#4267b2', // Blue - Active-state nav glyphs, nav bars, links, buttons green: '#42b72a', // Green - Confirmation, success, commerce and status red: '#FC3A4B', // Red - Badges, error states blueGray: '#5f6673', // Blue Grey slate: '#b9cad2', // Slate aluminum: '#a3cedf', // Aluminum seaFoam: '#54c7ec', // Sea Foam teal: '#6bcebb', // Teal lime: '#a3ce71', // Lime lemon: '#fcd872', // Lemon orange: '#f7923b', // Orange tomato: '#fb724b', // Tomato - Tometo? Tomato. cherry: '#f35369', // Cherry pink: '#ec7ebd', // Pink grape: '#8c72cb', // Grape }); export const NullValue = styled.span({ color: theme.semanticColors.nullValue, }); NullValue.displayName = 'DataDescription:NullValue'; const UndefinedValue = styled.span({ color: theme.semanticColors.nullValue, }); UndefinedValue.displayName = 'DataDescription:UndefinedValue'; export const StringValue = styled.span({ color: theme.semanticColors.stringValue, wordWrap: 'break-word', }); StringValue.displayName = 'DataDescription:StringValue'; const ColorValue = styled.span({ color: theme.semanticColors.colorValue, }); ColorValue.displayName = 'DataDescription:ColorValue'; const SymbolValue = styled.span({ color: theme.semanticColors.stringValue, }); SymbolValue.displayName = 'DataDescription:SymbolValue'; export const NumberValue = styled.span({ color: theme.semanticColors.numberValue, }); NumberValue.displayName = 'DataDescription:NumberValue'; export const BooleanValue = styled.span({ color: theme.semanticColors.booleanValue, }); BooleanValue.displayName = 'DataDescription:BooleanValue'; const ColorBox = styled.span<{color: string}>((props) => ({ backgroundColor: props.color, boxShadow: `inset 0 0 1px ${theme.black}`, display: 'inline-block', height: 12, marginRight: 4, verticalAlign: 'middle', width: 12, borderRadius: 4, })); ColorBox.displayName = 'DataDescription:ColorBox'; const FunctionKeyword = styled.span({ color: theme.semanticColors.nullValue, fontStyle: 'italic', }); FunctionKeyword.displayName = 'DataDescription:FunctionKeyword'; const FunctionName = styled.span({ fontStyle: 'italic', }); FunctionName.displayName = 'DataDescription:FunctionName'; const ColorPickerDescription = styled.div({ display: 'inline', position: 'relative', }); ColorPickerDescription.displayName = 'DataDescription:ColorPickerDescription'; const EmptyObjectValue = styled.span({ fontStyle: 'italic', }); EmptyObjectValue.displayName = 'DataDescription:EmptyObjectValue'; export type DataDescriptionType = | 'number' | 'string' | 'boolean' | 'undefined' | 'null' | 'object' | 'array' | 'date' | 'symbol' | 'function' | 'bigint' | 'text' // deprecated, please use string | 'enum' // unformatted string | 'color' | 'picker' // multiple choise item like an, eehhh, enum | 'timeline' | 'color_lite'; // color with limited palette, specific for fblite; type DataDescriptionProps = { path?: Array<string>; type: DataDescriptionType; value: any; extra?: any; setValue: DataInspectorSetValue | null | undefined; }; type DescriptionCommitOptions = { value: any; keep: boolean; clear: boolean; set: boolean; }; class NumberTextEditor extends PureComponent<{ commit: (opts: DescriptionCommitOptions) => void; type: DataDescriptionType; value: any; origValue: any; }> { onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const val = this.props.type === 'number' ? parseFloat(e.target.value) : e.target.value; this.props.commit({ clear: false, keep: true, value: val, set: false, }); }; onNumberTextInputKeyDown = (e: KeyboardEvent) => { if (e.key === 'Enter') { const val = this.props.type === 'number' ? parseFloat(this.props.value) : this.props.value; this.props.commit({clear: true, keep: true, value: val, set: true}); } else if (e.key === 'Escape') { this.props.commit({ clear: true, keep: false, value: this.props.origValue, set: false, }); } }; onNumberTextRef = (ref: HTMLElement | undefined | null) => { if (ref) { ref.focus(); } }; onNumberTextBlur = () => { this.props.commit({ clear: true, keep: true, value: this.props.value, set: true, }); }; render() { const extraProps: any = {}; if (this.props.type === 'number') { // render as a HTML number input extraProps.type = 'number'; // step="any" allows any sort of float to be input, otherwise we're limited // to decimal extraProps.step = 'any'; } return ( <Input key="input" {...extraProps} size="small" onChange={this.onNumberTextInputChange} onKeyDown={this.onNumberTextInputKeyDown} ref={this.onNumberTextRef} onBlur={this.onNumberTextBlur} value={this.props.value} style={{fontSize: 11}} /> ); } } type DataDescriptionState = { editing: boolean; origValue: any; value: any; }; export class DataDescription extends PureComponent< DataDescriptionProps, DataDescriptionState > { constructor(props: DataDescriptionProps, context: Object) { super(props, context); this.state = { editing: false, origValue: '', value: '', }; } commit = (opts: DescriptionCommitOptions) => { const {path, setValue} = this.props; if (opts.keep && setValue && path) { const val = opts.value; this.setState({value: val}); if (opts.set) { setValue(path, val); } } if (opts.clear) { this.setState({ editing: false, origValue: '', value: '', }); } }; _renderEditing() { const {type, extra} = this.props; const {origValue, value} = this.state; if ( type === 'string' || type === 'text' || type === 'number' || type === 'enum' ) { return ( <NumberTextEditor type={type} value={value} origValue={origValue} commit={this.commit} /> ); } if (type === 'color') { return <ColorEditor value={value} commit={this.commit} />; } if (type === 'color_lite') { return ( <ColorEditor value={value} colorSet={extra.colorSet} commit={this.commit} /> ); } return null; } _hasEditUI() { const {type} = this.props; return ( type === 'string' || type === 'text' || type === 'number' || type === 'enum' || type === 'color' || type === 'color_lite' ); } onEditStart = () => { this.setState({ editing: this._hasEditUI(), origValue: this.props.value, value: this.props.value, }); }; render(): any { if (this.state.editing) { return this._renderEditing(); } else { return ( <DataDescriptionPreview type={this.props.type} value={this.props.value} extra={this.props.extra} editable={!!this.props.setValue} commit={this.commit} onEdit={this.onEditStart} /> ); } } } class ColorEditor extends PureComponent<{ value: any; colorSet?: Array<string | number>; commit: (opts: DescriptionCommitOptions) => void; }> { onBlur = (newVisibility: boolean) => { if (!newVisibility) { this.props.commit({ clear: true, keep: false, value: this.props.value, set: true, }); } }; onChange = ({ hex, rgb: {a, b, g, r}, }: { hex: string; rgb: {a: number; b: number; g: number; r: number}; }) => { const prev = this.props.value; let val; if (typeof prev === 'string') { if (a === 1) { // hex is fine and has an implicit 100% alpha val = hex; } else { // turn into a css rgba value val = `rgba(${r}, ${g}, ${b}, ${a})`; } } else if (typeof prev === 'number') { // compute RRGGBBAA value val = (Math.round(a * 255) & 0xff) << 24; val |= (r & 0xff) << 16; val |= (g & 0xff) << 8; val |= b & 0xff; const prevClear = ((prev >> 24) & 0xff) === 0; const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff); if (!onlyAlphaChanged && prevClear) { val = 0xff000000 | (val & 0x00ffffff); } } else { return; } this.props.commit({clear: false, keep: true, value: val, set: true}); }; onChangeLite = ({ rgb: {a, b, g, r}, }: { rgb: {a: number; b: number; g: number; r: number}; }) => { const prev = this.props.value; if (typeof prev !== 'number') { return; } // compute RRGGBBAA value let val = (Math.round(a * 255) & 0xff) << 24; val |= (r & 0xff) << 16; val |= (g & 0xff) << 8; val |= b & 0xff; this.props.commit({clear: false, keep: true, value: val, set: true}); }; render() { const colorInfo = parseColor(this.props.value); if (!colorInfo) { return null; } return ( <Popover trigger={'click'} onVisibleChange={this.onBlur} content={() => this.props.colorSet ? ( <CompactPicker color={colorInfo} colors={this.props.colorSet .filter((x) => x != 0) .map(parseColor) .map((rgba) => { if (!rgba) { return ''; } return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`; })} onChange={(color: { hex: string; hsl: { a?: number; h: number; l: number; s: number; }; rgb: {a?: number; b: number; g: number; r: number}; }) => { this.onChangeLite({rgb: {...color.rgb, a: color.rgb.a || 0}}); }} /> ) : ( <SketchPicker color={colorInfo} presetColors={presetColors} onChange={(color: { hex: string; hsl: { a?: number; h: number; l: number; s: number; }; rgb: {a?: number; b: number; g: number; r: number}; }) => { this.onChange({ hex: color.hex, rgb: {...color.rgb, a: color.rgb.a || 1}, }); }} /> ) }> <ColorPickerDescription> <DataDescriptionPreview type="color" value={this.props.value} extra={this.props.colorSet} editable={false} commit={this.props.commit} /> </ColorPickerDescription> </Popover> ); } } class DataDescriptionPreview extends PureComponent<{ type: DataDescriptionType; value: any; extra?: any; editable: boolean; commit: (opts: DescriptionCommitOptions) => void; onEdit?: () => void; }> { onClick = () => { const {onEdit} = this.props; if (this.props.editable && onEdit) { onEdit(); } }; render() { const {type, value} = this.props; const description = ( <DataDescriptionContainer type={type} value={value} editable={this.props.editable} commit={this.props.commit} /> ); // booleans are always editable so don't require the onEditStart handler if (type === 'boolean') { return description; } return ( <span onClick={this.onClick} role="button" tabIndex={-1}> {description} </span> ); } } type Picker = { values: Set<string>; selected: string; }; class DataDescriptionContainer extends PureComponent<{ type: DataDescriptionType; value: any; editable: boolean; commit: (opts: DescriptionCommitOptions) => void; }> { static contextType = HighlightContext; // Replace with useHighlighter context!: React.ContextType<typeof HighlightContext>; onChangeCheckbox = (e: CheckboxChangeEvent) => { this.props.commit({ clear: true, keep: true, value: e.target.checked, set: true, }); }; render(): any { const {type, editable, value: val} = this.props; const highlighter = this.context; switch (type) { case 'timeline': { return ( <> <TimelineDataDescription canSetCurrent={editable} timeline={JSON.parse(val)} onClick={(id) => { this.props.commit({ value: id, keep: true, clear: false, set: true, }); }} /> </> ); } case 'number': return <NumberValue>{+val}</NumberValue>; case 'color': { const colorInfo = parseColor(val); if (typeof val === 'number' && val === 0) { return <UndefinedValue>(not set)</UndefinedValue>; } else if (colorInfo) { const {a, b, g, r} = colorInfo; return ( <> <ColorBox key="color-box" color={`rgba(${r}, ${g}, ${b}, ${a})`} /> <ColorValue key="value"> rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)}) </ColorValue> </> ); } else { return <span>Malformed color</span>; } } case 'color_lite': { const colorInfo = parseColor(val); if (typeof val === 'number' && val === 0) { return <UndefinedValue>(not set)</UndefinedValue>; } else if (colorInfo) { const {a, b, g, r} = colorInfo; return ( <> <ColorBox key="color-box" color={`rgba(${r}, ${g}, ${b}, ${a})`} /> <ColorValue key="value"> rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)}) </ColorValue> </> ); } else { return <span>Malformed color</span>; } } case 'picker': { const picker: Picker = JSON.parse(val); return ( <Select disabled={!this.props.editable} options={Array.from(picker.values).map((value) => ({ value, label: value, }))} value={picker.selected} onChange={(value: string) => this.props.commit({ value, keep: true, clear: false, set: true, }) } size="small" style={{fontSize: 11}} dropdownMatchSelectWidth={false} /> ); } case 'text': case 'string': const isUrl = val.startsWith('http://') || val.startsWith('https://'); if (isUrl) { return ( <> <Link href={val}>{highlighter.render(val)}</Link> {editable && ( <EditOutlined style={{ color: theme.disabledColor, cursor: 'pointer', marginLeft: 8, }} /> )} </> ); } else { return ( <StringValue>{highlighter.render(`"${val || ''}"`)}</StringValue> ); } case 'enum': return <StringValue>{highlighter.render(val)}</StringValue>; case 'boolean': return editable ? ( <Checkbox checked={!!val} disabled={!editable} onChange={this.onChangeCheckbox} /> ) : ( <BooleanValue>{'' + val}</BooleanValue> ); case 'undefined': return <UndefinedValue>undefined</UndefinedValue>; case 'date': if (Object.prototype.toString.call(val) === '[object Date]') { return <span>{val.toString()}</span>; } else { return <span>{val}</span>; } case 'null': return <NullValue>null</NullValue>; // no description necessary as we'll typically wrap it in [] or {} which // already denotes the type case 'array': return val.length <= 0 ? <EmptyObjectValue>[]</EmptyObjectValue> : null; case 'object': return Object.keys(val ?? {}).length <= 0 ? ( <EmptyObjectValue>{'{}'}</EmptyObjectValue> ) : null; case 'function': return ( <span> <FunctionKeyword>function</FunctionKeyword> <FunctionName>&nbsp;{val.name}()</FunctionName> </span> ); case 'symbol': return <SymbolValue>Symbol()</SymbolValue>; default: return <span>Unknown type "{type}"</span>; } } }
facebook/flipper
desktop/flipper-plugin/src/ui/data-inspector/DataDescription.tsx
TypeScript
mit
18,166
using System; using Windows.ApplicationModel.Activation; using Windows.UI.Core; using Windows.UI.Input; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace Podcasts { using System.ComponentModel; using Commands; using Utilities; using ViewModels; using Windows.UI.Xaml.Controls.Primitives; public enum SplitViewState { Open, Close, Toggle, }; public class OpenSplitViewCommand : CommandBase<SplitViewState?> { private SplitView _splitView; internal SplitView SplitView { get { return _splitView; } set { _splitView = value; } } public OpenSplitViewCommand() { } private SplitViewState CurrentState => SplitView.IsPaneOpen ? SplitViewState.Open : SplitViewState.Close; public override bool CanExecute(SplitViewState? parameter) { return parameter != null; } public override void Execute(SplitViewState? desiredState) { if (!desiredState.HasValue) { return; } if (desiredState == SplitViewState.Toggle) { desiredState = CurrentState == SplitViewState.Open ? SplitViewState.Close : SplitViewState.Open; } SplitView.IsPaneOpen = (desiredState == SplitViewState.Open); } } public class NavigationCommand<PageT, Args> : CommandBase<Args> where PageT : Page { public override bool CanExecute(Args parameter) => Chrome.Current != null; public override void Execute(Args parameter) { Chrome.Current.NavigateTo(typeof(PageT), parameter); } } /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Chrome : Page { private static Chrome _current; public static Chrome Current => _current; public static Chrome CreateChrome() { if (_current != null) { return _current; } return _current = new Chrome(); } public App App => (App)Application.Current; public AppViewModel ViewModel => App.ViewModel; public readonly SplitViewState HamburgerCommandParameter = SplitViewState.Toggle; public OpenSplitViewCommand HamburgerCommand { get; private set; } = new OpenSplitViewCommand(); public bool NavigateTo(Type destination, object arguments) => RootFrame.Navigate(destination, arguments); public Chrome() { this.InitializeComponent(); this.HamburgerCommand.SplitView = MainSplitView; this.DataContext = this; this.RootFrame.NavigationFailed += this.OnNavigationFailed; this.RootFrame.Navigating += RootFrame_Navigating; this.RootFrame.Navigated += RootFrame_Navigated; this.ViewModel.PropertyChanged += ViewModel_PropertyChanged; } private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ViewModel.CurrentPodcastPosition)) { if (ViewModel.CurrentPodcastPosition.HasValue) { CurrentPodcastSlider.ValueChanged -= CurrentPodcastSlider_ValueChanged; CurrentPodcastSlider.Value = (int)ViewModel.CurrentPodcastPosition.Value.TotalSeconds; CurrentPodcastSlider.ValueChanged += CurrentPodcastSlider_ValueChanged; } } } private void RootFrame_Navigated(object sender, NavigationEventArgs e) { var navManager = SystemNavigationManager.GetForCurrentView(); if (!this.RootFrame.CanGoBack) { navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed; } else { navManager.BackRequested += NavManager_BackRequested; navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; } } private void NavManager_BackRequested(object sender, BackRequestedEventArgs e) { if (this.RootFrame.CanGoBack) { e.Handled = true; this.RootFrame.GoBack(); } } private void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e) { var navManager = SystemNavigationManager.GetForCurrentView(); navManager.BackRequested -= NavManager_BackRequested; } public void AppLaunched(LaunchActivatedEventArgs e) { if (this.RootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter this.RootFrame.Navigate(typeof(Views.PodcastsListPage), e.Arguments); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> private void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } private void CurrentPodcastSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) { ViewModel.ScrubTo(new TimeSpan(hours: 0, minutes: 0, seconds: (int)e.NewValue)); } } }
AndrewGaspar/Podcasts
Podcasts/Chrome.xaml.cs
C#
mit
6,129
/** * Auction collection */ 'use strict'; var Model = require('../models/auction_model.js'); var Collection = require('tungstenjs/adaptors/backbone').Collection; var AuctionCollection = Collection.extend({ model: Model }); module.exports = AuctionCollection;
marielb/roadshow
app/public/js/collections/auction_collection.js
JavaScript
mit
264
# Public: Executes a block of code and retries it up to `tries` times if an # exception was raised. # # tries - An Integer (default: Float::Infinity). # exceptions - A list of Exceptions (default: StandardError). # # Examples # # class Wrapper # include Bonehead # # def login(username, password) # insist(5, HTTPError) do # HTTP.post "..." # end # end # end # # Returns the return value of the block. module Bonehead extend self def insist(tries = Float::Infinity, *exceptions, &block) exceptions << StandardError if exceptions.empty? catch :__BONEHEAD__ do tries.times do |i| begin throw :__BONEHEAD__, yield(i.succ) rescue *exceptions tries.pred == i ? raise : next end end end end end
britishtea/bonehead
lib/bonehead.rb
Ruby
mit
813
// Regular expression that matches all symbols in the Devanagari Extended block as per Unicode v6.0.0: /[\uA8E0-\uA8FF]/;
mathiasbynens/unicode-data
6.0.0/blocks/Devanagari-Extended-regex.js
JavaScript
mit
121