_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q5000
Edgarj.EdgarjController.update
train
def update upsert do # NOTE: # 1. update ++then++ valid to set new values in @record to draw form. # 1. user_scoped may have joins so that record could be # ActiveRecord::ReadOnlyRecord so that's why access again from # model. @record = model.find(user_scoped.find(params[:id]).id) #upsert_files if [email protected]_attributes(permitted_params(:update)) raise ActiveRecord::RecordInvalid.new(@record) end end end
ruby
{ "resource": "" }
q5001
Edgarj.EdgarjController.search_save
train
def search_save SavedVcontext.save(current_user, nil, params[:saved_page_info_name], page_info) render :update do |page| page << "Edgarj.SearchSavePopup.close();" page.replace 'edgarj_load_condition_menu', :partial=>'edgarj/load_condition_menu' end rescue ActiveRecord::ActiveRecordError app_rescue render :update do |page| page.replace_html 'search_save_popup_flash_error', :text=>t('save_fail') end end
ruby
{ "resource": "" }
q5002
Edgarj.EdgarjController.csv_download
train
def csv_download filename = sprintf("%s-%s.csv", model_name, Time.now.strftime("%Y%m%d-%H%M%S")) file = Tempfile.new(filename, Settings.edgarj.csv_dir) csv_visitor = EdgarjHelper::CsvVisitor.new(view_context) file.write CSV.generate_line(model.columns.map{|c| c.name}) for rec in user_scoped.where(page_info.record.conditions). order( page_info.order_by.blank? ? nil : page_info.order_by + ' ' + page_info.dir) do array = [] for col in model.columns do array << csv_visitor.visit_column(rec, col) end file.write CSV.generate_line(array) end file.close File.chmod(Settings.edgarj.csv_permission, file.path) send_file(file.path, { type: 'text/csv', filename: filename}) #file.close(true) end
ruby
{ "resource": "" }
q5003
Edgarj.EdgarjController.drawer_class
train
def drawer_class @_drawer_cache ||= if self.class == Edgarj::EdgarjController Edgarj::Drawer::Normal else (self.class.name.gsub(/Controller$/, '').singularize + 'Drawer').constantize end end
ruby
{ "resource": "" }
q5004
Edgarj.Search.column_type
train
def column_type(col_name) cache = Cache.instance cache.klass_hash[@_klass_str] ||= {} if v = cache.klass_hash[@_klass_str][col_name.to_s] cache.hit += 1 v else cache.miss += 1 col = @_klass_str.constantize.columns.find{|c| c.name == col_name.to_s } if col cache.klass_hash[@_klass_str][col_name.to_s] = col.type end end end
ruby
{ "resource": "" }
q5005
ActiveRepository.Writers.create
train
def create(attributes={}) attributes = attributes.symbolize_keys if attributes.respond_to?(:symbolize_keys) object = self.new(attributes) if object.present? && object.valid? if persistence_class == self object.id = nil unless exists?(object.id) object.save else object = PersistenceAdapter.create(self, object.attributes) end end new_object = serialize!(object.reload.attributes) new_object.valid? new_object end
ruby
{ "resource": "" }
q5006
Tableau.TableBuilder.to_html
train
def to_html time_header, rows = '<th></th>', Array.new end_time = Time.new(2013, 1, 1, 21, 0, 0) # make the time row @time = Time.new(2013, 1, 1, 9, 0, 0) while @time < end_time time_header += "<th>#{@time.strftime("%-k:%M")}</th>" @time += 900 end #make each day row (0..4).each do |day| classes = @timetable.classes_for_day(day) rows << day_row(day, classes) end rows_str, id_str = '', "id=\"#{@timetable.name}\"" rows.each{ |r| rows_str += "<tr class=\"day\">\n#{r}\n</tr>\n" } %Q{ <!DOCTYPE html> <html> <head> <title>#{@timetable.name || 'Timetable' } - Timetablr.co</title> <style>#{build_css}</style> </head> <body> <h3>#{@timetable.name}</h3> <table #{id_str if @timetable.name}> <tr id="time">#{time_header}</tr> #{rows_str} </table> </body> </html> } end
ruby
{ "resource": "" }
q5007
Kuniri.Setting.read_configuration_file
train
def read_configuration_file(pPath = '.kuniri.yml') if !(File.exist?(pPath)) set_default_configuration else safeInfo = SafeYAML.load(File.read(pPath)) # SafeYAML add collon (':') in the begin of each key. We handle it here @configurationInfo = safeInfo.map do |key, value| [key.tr(':', '').to_sym, value] end.to_h verify_syntax end return @configurationInfo end
ruby
{ "resource": "" }
q5008
Pagify.BasicPager.page
train
def page page if page_exists?(page) return BasicPage.new(self, normalize_page(page)) else if null_page return null_page_instance else return nil end end end
ruby
{ "resource": "" }
q5009
NewsScraper.Scraper.scrape
train
def scrape article_urls = Extractors::GoogleNewsRss.new(query: @query).extract transformed_articles = [] article_urls.each do |article_url| payload = Extractors::Article.new(url: article_url).extract article_transformer = Transformers::Article.new(url: article_url, payload: payload) begin transformed_article = article_transformer.transform transformed_articles << transformed_article yield transformed_article if block_given? rescue Transformers::ScrapePatternNotDefined => e raise e unless block_given? yield e end end transformed_articles end
ruby
{ "resource": "" }
q5010
NewsScraper.Trainer.train
train
def train(query: '') article_urls = Extractors::GoogleNewsRss.new(query: query).extract article_urls.each do |url| Trainer::UrlTrainer.new(url).train end end
ruby
{ "resource": "" }
q5011
JsonRecord.Schema.key
train
def key (name, *args) options = args.extract_options! name = name.to_s json_type = args.first || String raise ArgumentError.new("too many arguments (must be 1 or 2 plus an options hash)") if args.length > 1 field = FieldDefinition.new(name, :type => json_type, :default => options[:default]) fields[name] = field add_json_validations(field, options) define_json_accessor(field, json_field_name) end
ruby
{ "resource": "" }
q5012
JsonRecord.Schema.many
train
def many (name, *args) name = name.to_s options = args.extract_options! type = args.first || name.singularize.classify.constantize field = FieldDefinition.new(name, :type => type, :multivalued => true) fields[name] = field add_json_validations(field, options) define_many_json_accessor(field, json_field_name) end
ruby
{ "resource": "" }
q5013
Tableau.ClassArray.classes_for_day
train
def classes_for_day(day) days_classes = ClassArray.new self.each { |c| days_classes << c if c.day == day } days_classes.count > 0 ? days_classes : nil end
ruby
{ "resource": "" }
q5014
Tableau.ClassArray.earliest_class
train
def earliest_class earliest = self.first self.each { |c| earliest = c if c.time < earliest.time } earliest end
ruby
{ "resource": "" }
q5015
Todoist.Task.save
train
def save opts = {} opts['priority'] = priority if priority opts['date_string'] = date if date # if we don't have an id, then we can assume this is a new task. unless (task_details.has_key?('id')) result = self.class.create(self.content, self.project_id, opts) else result = self.class.update(self.content, self.id, opts) end self.content = result.content self.project_id = result.project_id self.task_details = result.task_details self end
ruby
{ "resource": "" }
q5016
Ldaptic.AttributeSet.replace
train
def replace(*attributes) attributes = safe_array(attributes) user_modification_guard seen = {} filtered = [] attributes.each do |value| matchable = matchable(value) unless seen[matchable] filtered << value seen[matchable] = true end end @target.replace(filtered) self end
ruby
{ "resource": "" }
q5017
Edgarj.SearchForm.method_missing
train
def method_missing(method_name, *args) if method_name.to_s =~ /^(.*)=$/ @attrs[$1.to_sym] = args[0] else val = @attrs[method_name.to_sym] case column_type(method_name) when :integer if val =~ /^\d+$/ val.to_i else val end else val end end end
ruby
{ "resource": "" }
q5018
LibWebSocket.URL.parse
train
def parse(string) return nil unless string.is_a?(String) uri = Addressable::URI.parse(string) scheme = uri.scheme return nil unless scheme self.secure = true if scheme.match(/ss\Z/m) host = uri.host host = '/' unless host && host != '' self.host = host self.port = uri.port.to_s if uri.port request_uri = uri.path request_uri = '/' unless request_uri && request_uri != '' request_uri += "?" + uri.query if uri.query self.resource_name = request_uri return self end
ruby
{ "resource": "" }
q5019
LibWebSocket.URL.to_s
train
def to_s string = '' string += 'ws' string += 's' if self.secure string += '://' string += self.host string += ':' + self.port.to_s if self.port string += self.resource_name || '/' return string end
ruby
{ "resource": "" }
q5020
Loggr.Adapter.logger
train
def logger(name, options = {}, &block) use_adapter = options.key?(:adapter) ? get_adapter(options.delete(:adapter)) : self.adapter use_adapter.logger(name, options).tap do |logger| yield(logger) if block_given? end end
ruby
{ "resource": "" }
q5021
Loggr.Adapter.get_adapter
train
def get_adapter(adp) # okay, this is only because we can't camelize it :) adp = Loggr::Adapter::NOP if !adp # Code adapter from ActiveSupport::Inflector#camelize # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30 adp = adp.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } if adp.is_a?(Symbol) clazz = adp if adp.respond_to?(:to_str) const = begin Loggr::Adapter.const_get(adp.to_s) rescue begin Loggr::Adapter.const_get(adp.to_s.upcase) rescue nil end end unless const # code adapter from ActiveSupport::Inflector#constantize # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107 names = adp.to_s.split('::') names.shift if names.empty? || names.first.empty? const = ::Object names.each { |n| const = const.const_get(n) } end clazz = const end raise "#{clazz}: an adapter must implement #logger and #mdc" unless clazz.respond_to?(:logger) && clazz.respond_to?(:mdc) clazz end
ruby
{ "resource": "" }
q5022
XmlFu.Node.name_parse_special_characters
train
def name_parse_special_characters(val) use_this = val.dup # Ensure that we don't have special characters at end of name while ["!","/","*"].include?(use_this.to_s[-1,1]) do # Will this node contain escaped XML? if use_this.to_s[-1,1] == '!' @escape_xml = false use_this.chop! end # Will this be a self closing node? if use_this.to_s[-1,1] == '/' @self_closing = true use_this.chop! end # Will this node contain a collection of sibling nodes? if use_this.to_s[-1,1] == '*' @content_type = "collection" use_this.chop! end end return use_this end
ruby
{ "resource": "" }
q5023
XmlFu.Node.value=
train
def value=(val) case val when ::String then @value = val.to_s when ::Hash then @value = val when ::Array then @value = val when ::OpenStruct then @value = val when ::DateTime then @value = val.strftime XS_DATETIME_FORMAT when ::Time then @value = val.strftime XS_DATETIME_FORMAT when ::Date then @value = val.strftime XS_DATETIME_FORMAT else if val.respond_to?(:to_datetime) @value = val.to_datetime elsif val.respond_to?(:call) @value = val.call elsif val.nil? @value = nil else @value = val.to_s end end rescue => e @value = val.to_s end
ruby
{ "resource": "" }
q5024
Languages.RubySyntax.handle_semicolon
train
def handle_semicolon(pLine) commentLine = [] if pLine =~ /^=begin(.*?)/ @flagMultipleLineComment = true elsif pLine =~ /^=end/ @flagMultipleLineComment = false end unless @flagMultipleLineComment == true || pLine =~ /#(.*)/ return pLine.split(/;/) end commentLine << pLine end
ruby
{ "resource": "" }
q5025
Ldaptic.DN.find
train
def find(source = @source) scope = 0 filter = "(objectClass=*)" if source.respond_to?(:search2_ext) source.search2( to_s, scope, filter ) elsif source.respond_to?(:search) Array(source.search( :base => to_s, :scope => scope, :filter => filter, :limit => 1 )) else raise RuntimeError, "missing or invalid source for LDAP search", caller end.first end
ruby
{ "resource": "" }
q5026
Ldaptic.DN.domain
train
def domain components = rdns.map {|rdn| rdn[:dc]}.compact components.join('.') unless components.empty? end
ruby
{ "resource": "" }
q5027
Jnlp.Jnlp.generate_local_jnlp
train
def generate_local_jnlp(options={}) # # get a copy of the existing jnlp # (it should be easier than this) # @local_jnlp = Nokogiri::XML(@jnlp.to_s) # # we'll be working with the Hpricot root element # jnlp_elem = (@local_jnlp/"jnlp").first # # set the new codebase # jnlp_elem[:codebase] = "file:#{@local_cache_dir}" # # set the new href # jnlp_elem[:href] = @local_jnlp_href # # for each jar and nativelib remove the version # attribute and point the href to the local cache # @jars.each do |jar| j = @local_jnlp.at("//jar[@href=#{jar.href}]") j.remove_attribute(:version) if options[:include_pack_gz] j[:href] = jar.relative_local_path_pack_gz else j[:href] = jar.relative_local_path end end @nativelibs.each do |nativelib| nl = @local_jnlp.at("//nativelib[@href=#{nativelib.href}]") nl.remove_attribute(:version) if options[:include_pack_gz] nl[:href] = nativelib.relative_local_path_pack_gz else nl[:href] = nativelib.relative_local_path end end end
ruby
{ "resource": "" }
q5028
Jnlp.Jnlp.resource_paths
train
def resource_paths(options={}) if options[:include_pack_gs] cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path_pack_gz} cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path_pack_gz} resources = cp_jars + cp_nativelibs else cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path} cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path} resources = cp_jars + cp_nativelibs end # # FIXME: this should probably be more discriminatory # if options[:remove_jruby] resources = resources.reject {|r| r =~ /\/jruby\//} end resources end
ruby
{ "resource": "" }
q5029
Jnlp.Jnlp.write_local_classpath_shell_script
train
def write_local_classpath_shell_script(filename="#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh", options={}) script = "export CLASSPATH=$CLASSPATH#{local_classpath(options)}" File.open(filename, 'w'){|f| f.write script} end
ruby
{ "resource": "" }
q5030
Jnlp.Jnlp.write_jnlp
train
def write_jnlp(options={}) dir = options[:dir] || '.' path = options[:path] || @path.gsub(/^\//, '') Dir.chdir(dir) do FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') {|f| f.write to_jnlp(options[:jnlp]) } if options[:snapshot] snapshot_path = "#{File.dirname(path)}/#{@family}.jnlp" File.open(snapshot_path, 'w') {|f| f.write to_jnlp(options[:jnlp]) } current_version_path = "#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt" File.open(current_version_path, 'w') {|f| f.write @version_str } end end end
ruby
{ "resource": "" }
q5031
Jnlp.Jnlp.write_local_jnlp
train
def write_local_jnlp(filename=@local_jnlp_name) destination = File.expand_path(filename) unless @local_jnlp_href == destination @local_jnlp_href = destination @local_jnlp_name = File.basename(destination) self.generate_local_jnlp end File.open(filename, 'w') {|f| f.write to_local_jnlp } end
ruby
{ "resource": "" }
q5032
Jnlp.Jnlp.require_resources
train
def require_resources if RUBY_PLATFORM =~ /java/ resource_paths(:remove_jruby => true).each {|res| require res} true else false end end
ruby
{ "resource": "" }
q5033
UnobtrusiveDatePicker.UnobtrusiveDatePickerHelper.unobtrusive_date_text_picker_tag
train
def unobtrusive_date_text_picker_tag(name, date = Date.current, options = {}, html_options = {}) date ||= Date.current options = merge_defaults_for_text_picker(options) DateTimePickerSelector.new(date, options, html_options).text_date_picker(name) end
ruby
{ "resource": "" }
q5034
Jnlp.Resource.update_cache
train
def update_cache(source=@url, destination=@local_path, options={}) unless destination raise ArgumentError, "Must specify destination directory when updatng resource", caller end file_exists = File.exists?(destination) if file_exists && @signature_verified == nil verify_signature end unless file_exists && @signature_verified FileUtils.mkdir_p(File.dirname(destination)) puts "reading: #{source}" if options[:verbose] tried_to_read = 0 begin jarfile = open(source) rescue OpenURI::HTTPError => e puts e if tried_to_read < 1 tried_to_read += 1 retry end end if jarfile.class == Tempfile FileUtils.cp(jarfile.path, destination) puts "copying to: #{destination}" if options[:verbose] else File.open(destination, 'w') {|f| f.write jarfile.read } puts "writing to: #{destination}" if options[:verbose] end puts "#{jarfile.size} bytes written" if options[:verbose] verify_signature ? jarfile.size : false else File.size(destination) end end
ruby
{ "resource": "" }
q5035
Jnlp.Resource.verify_signature
train
def verify_signature if @local_path if RUBY_PLATFORM =~ /java/ begin jarfile = java.util.jar.JarInputStream.new(FileInputStream.new(@local_path), true) @signature_verified = true rescue NativeException @signature_verified = false end else # Use IO.popen instead of system() to absorb # jarsigners messages to $stdout response = IO.popen("jarsigner -verify #{@local_path}"){|io| io.gets} @signature_verified = ($?.exitstatus == 0) end else nil end end
ruby
{ "resource": "" }
q5036
Edgarj.AssocHelper.draw_belongs_to_clear_link
train
def draw_belongs_to_clear_link(f, col_name, popup_field, parent_name, default_label) if Settings.edgarj.belongs_to.disable_clear_link f.hidden_field(col_name) else ('&nbsp;&nbsp;' + link_to("[#{I18n.t('edgarj.default.clear')}]", '#', onClick: "Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;", id: popup_field.clear_link, style: 'display:' + (parent_name.blank? ? 'none' : '')) + f.hidden_field(col_name)).html_safe end end
ruby
{ "resource": "" }
q5037
Edgarj.AssocHelper.draw_belongs_to_field
train
def draw_belongs_to_field(f, popup_path, col_name, model = f.object.class) col = model.columns.detect{|c| c.name == col_name.to_s} return "no column found" if !col parent_model = model.belongs_to_AR(col) return "parent_model is nil" if !parent_model parent_obj = f.object.belongs_to_AR(col) popup_field = Edgarj::PopupHelper::PopupField.new_builder( f.object_name, col_name) default_label = '[' + draw_belongs_to_label_sub(model, col.name, parent_model) + ']' label = content_tag(:span, parent_obj ? parent_obj.name : default_label.html_safe, id: popup_field.label_target) link_tag = Settings.edgarj.belongs_to.link_tag.html_safe if parent_obj if Settings.edgarj.belongs_to.popup_on == 'field' link_to( label + link_tag, popup_path, remote: true) else link_to(label, # TODO: Hardcoded 'master' prefix should be fixed controller: url_prefix + parent_obj.class.name.underscore.pluralize, action: 'show', id: parent_obj, topic_path: 'add') end else if Settings.edgarj.belongs_to.popup_on == 'field' link_to( label + link_tag, popup_path, remote: true) else label end end + draw_belongs_to_clear_link(f, col.name, popup_field, parent_obj && parent_obj.name, default_label) end
ruby
{ "resource": "" }
q5038
Edgarj.AssocHelper.flag_on?
train
def flag_on?(column_value, bitset, flag) val = column_value || 0 (val & bitset.const_get(flag)) != 0 end
ruby
{ "resource": "" }
q5039
Edgarj.AssocHelper.get_bitset
train
def get_bitset(model, col) bitset_name = col.name.camelize + 'Bitset' if model.const_defined?(bitset_name, false) _module = model.const_get(bitset_name) _module.is_a?(Module) ? _module : nil else nil end end
ruby
{ "resource": "" }
q5040
Edgarj.AssocHelper.draw_column_bitset
train
def draw_column_bitset(rec, col_or_sym, bitset) turn_on_flags = [] value = rec.send(get_column_name(col_or_sym)) for flag in bitset.constants do turn_on_flags << flag if flag_on?(value, bitset, flag) end turn_on_flags.map{|f| rec.class.human_const_name(bitset, f) }.join(' ') end
ruby
{ "resource": "" }
q5041
Edgarj.AssocHelper.draw_column_enum
train
def draw_column_enum(rec, col_or_sym, enum) Edgarj::EnumCache.instance.label(rec, get_column_name(col_or_sym), enum) end
ruby
{ "resource": "" }
q5042
Edgarj.AssocHelper.adrs_str_sub
train
def adrs_str_sub(model, prefix, element) e = model.send(prefix + element) e.blank? ? '' : e end
ruby
{ "resource": "" }
q5043
Edgarj.AssocHelper.adrs_str
train
def adrs_str(model, adrs_prefix) result = '' for adrs_element in ['prefecture', 'city', 'other', 'bldg'] do result << adrs_str_sub(model, adrs_prefix, adrs_element) end result end
ruby
{ "resource": "" }
q5044
Edgarj.AssocHelper.permitted?
train
def permitted?(requested_flags = 0) current_user_roles.any?{|ug| ug.admin?} || current_model_permissions.any?{|cp| cp.permitted?(requested_flags)} end
ruby
{ "resource": "" }
q5045
Serializer.ClassMethods.has_serialized
train
def has_serialized(name, &block) serialize name, Hash initializer = Serializer::Initializer.new block.call(initializer) initializer.each do |method, options| define_method "#{method}" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = options[:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}?" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = options[:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}=" do |value| original = send(name) || {} if options[:type] and value case options[:type].to_sym when :float then value = value.to_f if value.respond_to? :to_f when :integer then value = value.to_i if value.respond_to? :to_i when :string then value = value.to_str if value.respond_to? :to_str when :symbol then value = value.to_sym if value.respond_to? :to_sym when :boolean then value = true if value.eql? "true" value = false if value.eql? "false" value = !value.to_i.zero? if value.respond_to? :to_i end end modified = original.clone modified[method.to_sym] = value send("#{name}_will_change!") unless modified.eql?(original) send("#{name}=", modified) end end end
ruby
{ "resource": "" }
q5046
Tableau.BaseParser.parse_table
train
def parse_table(table_rows) classes = Tableau::ClassArray.new @day = 0 # delete the time header row table_rows.delete(table_rows.first) table_rows.each do |row| @time = Time.new(2013, 1, 1, 9, 0, 0) # drop the 'Day' cell from the row row_items = row.xpath('td') row_items.delete(row_items.first) row_items.each do |cell| if cell.attribute('colspan') intervals = cell.attribute('colspan').value classes << create_class(cell) else intervals = 1 end inc_time(intervals) end @day += 1 end classes end
ruby
{ "resource": "" }
q5047
Tableau.BaseParser.create_class
train
def create_class(class_element) begin tt_class = Tableau::Class.new(@day, @time) data = class_element.xpath('table/tr/td//text()') raise "Misformed cell for #{module_id}" if data.count < 4 rescue Exception => e p "EXCEPTION: #{e.message}", "Data Parsed:", data return nil end # If the weeks are in the 2nd index, it's a core timetable if @@WEEKS_REGEX.match(data[1].text()) tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '') tt_class.weeks = create_class_weeks(data[1].text()) tt_class.location = data[2].text() tt_class.name = data[3].text() else # this is a module timetable, laid out differently if data[0].to_s != "" tt_class.code = data[0].text().match(/^[A-Za-z0-9\-]+/).to_s tt_class.type = data[0].text().gsub(tt_class.code, '').gsub('/', '') end tt_class.location = data[1].text() tt_class.name = data[2].text() tt_class.weeks = create_class_weeks(data[3].text()) end # Same attribute on both timetables, DRY'd here tt_class.tutor = data[4] ? data[4].text() : nil if intervals = class_element.attribute('colspan').value tt_class.intervals = intervals.to_i end tt_class end
ruby
{ "resource": "" }
q5048
Tableau.BaseParser.create_class_weeks
train
def create_class_weeks(week_data) week_span_regex = /([\d]{2}-[\d]{2})/ week_start_regex = /^[0-9]{2}/ week_end_regex = /[0-9]{2}$/ week_single_regex = /[\d]{2}/ class_weeks = Array.new week_data.scan(@@WEEKS_REGEX).each do |weekspan| # if it's a 28-39 week span if weekspan =~ week_span_regex start = week_start_regex.match(weekspan)[0].to_i finish = week_end_regex.match(weekspan)[0].to_i while start <= finish class_weeks << start start += 1 end # some single week (30, 31, 32 etc) support elsif weekspan =~ week_single_regex class_weeks << week_single_regex.match(weekspan)[0].to_i end end class_weeks end
ruby
{ "resource": "" }
q5049
Parser.OutputFormat.create_all_data
train
def create_all_data(pParser) return nil unless pParser wrapper = self # Go through each file pParser.fileLanguage.each do |listOfFile| # Inspect each element listOfFile.fileElements.each do |singleElement| @outputEngine.kuniri do wrapper.handle_element(singleElement) end currentFilePathAndName = singleElement.name write_file(currentFilePathAndName) @outputEngine.reset_engine end end end
ruby
{ "resource": "" }
q5050
Jinda.Helpers.markdown
train
def markdown(text) erbified = ERB.new(text.html_safe).result(binding) red = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true) red.render(erbified).html_safe end
ruby
{ "resource": "" }
q5051
Jinda.Helpers.gen_views
train
def gen_views t = ["*** generate ui ***"] # create array of files to be tested $afile = Array.new Jinda::Module.all.each do |m| m.services.each do |s| dir ="app/views/#{s.module.code}" unless gen_view_file_exist?(dir) gen_view_mkdir(dir,t) end if s.code=='link' f= "app/views/#{s.module.code}/index.haml" $afile << f unless gen_view_file_exist?(f) sv = "app/jinda/template/linkview.haml" f= "app/views/#{s.module.code}/index.haml" gen_view_createfile(sv,f,t) end next end dir ="app/views/#{s.module.code}/#{s.code}" unless gen_view_file_exist?(dir) gen_view_mkdir(dir,t) end xml= REXML::Document.new(s.xml) xml.elements.each('*/node') do |activity| icon = activity.elements['icon'] next unless icon action= freemind2action(icon.attributes['BUILTIN']) next unless ui_action?(action) code_name = activity.attributes["TEXT"].to_s next if code_name.comment? code= name2code(code_name) if action=="pdf" f= "app/views/#{s.module.code}/#{s.code}/#{code}.pdf.prawn" else f= "app/views/#{s.module.code}/#{s.code}/#{code}.html.erb" end $afile << f unless gen_view_file_exist?(f) sv = "app/jinda/template/view.html.erb" gen_view_createfile(sv,f,t) end end end end puts $afile.join("\n") puts t.join("\n") return $afile end
ruby
{ "resource": "" }
q5052
ROF.Utility.decode_work_type
train
def decode_work_type(obj) if obj['type'] =~ WORK_TYPE_WITH_PREFIX_PATTERN return 'GenericWork' if Regexp.last_match(2).nil? Regexp.last_match(2) else # this will return nil if key t does not exist work_type = obj['type'].downcase WORK_TYPES[work_type] end end
ruby
{ "resource": "" }
q5053
Jnlp.Otrunk.run_local
train
def run_local(argument=@argument, main_class='net.sf.sail.emf.launch.EMFLauncher2') if RUBY_PLATFORM =~ /java/ java.lang.Thread.currentThread.setContextClassLoader(JRuby.runtime.jruby_class_loader) require_resources configUrl = URL.new(JavaIO::File.new("dummy.txt").toURL, argument) # configUrl = URL.new("document-edit.config") unless @bundleManager @bundleManager = SailCoreBundle::BundleManager.new @serviceContext = @bundleManager.getServiceContext @bundleManager.setContextURL(configUrl) # # Add the <code>bundles</code> configured in this bundles xml file. The format of the file # is XMLEncoder # @bundleManager.addBundles(configUrl.openStream) # # Have all the bundles register their services, and then do any linking # to other registered services # @bundleManager.initializeBundles # # Start the session manager # @manager = @serviceContext.getService(SailCoreService::SessionManager.java_class) end @manager.start(@serviceContext) else command = "java -classpath #{local_classpath} #{main_class} '#{argument}'" $pid = fork { exec command } end end
ruby
{ "resource": "" }
q5054
PutQR.QRCode.render_image_iterm2
train
def render_image_iterm2 return nil unless valid? # References: # https://iterm2.com/documentation-images.html # https://iterm2.com/utilities/imgcat # tmux requires some extra work for unrecognised escape code sequences screen = ENV['TERM'].start_with? 'screen' prefix = screen ? "\ePtmux;\e\e]" : "\e]" suffix = screen ? "\a\e\\" : "\a" png = qrcode.as_png(size: 600) png_base64 = Base64.encode64(png.to_s).chomp options = 'inline=1' "#{prefix}1337;File=#{options}:#{png_base64}#{suffix}" end
ruby
{ "resource": "" }
q5055
Tableau.Timetable.remove_class
train
def remove_class(rem_class) @modules.each do |m| if m.name == rem_class.name m.classes.delete(rem_class) break end end end
ruby
{ "resource": "" }
q5056
Tableau.Timetable.classes_for_day
train
def classes_for_day(day) classes = Tableau::ClassArray.new @modules.each do |mod| cfd = mod.classes_for_day(day) cfd.each { |cl| classes << cl } if cfd end classes.count > 0 ? classes : nil end
ruby
{ "resource": "" }
q5057
Tableau.Timetable.class_for_time
train
def class_for_time(day, time) cfd = self.classes_for_day(day) cfd.each { |c| return c if c.time == time } nil end
ruby
{ "resource": "" }
q5058
Tableau.Timetable.earliest_class
train
def earliest_class earliest_classes = Tableau::ClassArray.new @modules.each { |m| earliest_classes << m.earliest_class } earliest = earliest_classes.first earliest_classes.each { |c| earliest = c if c.time < earliest.time } earliest end
ruby
{ "resource": "" }
q5059
Tableau.Timetable.conflicts
train
def conflicts conflicts = Tableau::ClassArray.new (0..4).each do |day| days_classes = self.classes_for_day(day) next if !days_classes || days_classes.count == 0 # get the last element index last = days_classes.count - 1 for i in 0..last i_c = days_classes[i] time_range = i_c.time..(i_c.time + 3600 * i_c.duration) for j in (i+1)..last if time_range.cover?(days_classes[j].time) conflicts << [days_classes[i], days_classes[j]] end end end end conflicts # return the conflicts end
ruby
{ "resource": "" }
q5060
Chatterbox::ExceptionNotification.Presenter.render_hash
train
def render_hash(hsh) str = "" indiff_hsh = hsh.with_indifferent_access indiff_hsh.keys.sort.each do |key| str << "#{key}: " value = indiff_hsh[key] PP::pp(value, str) end str end
ruby
{ "resource": "" }
q5061
GV.Component.html
train
def html(string) ptr = Libcgraph.agstrdup_html(graph.ptr, string) string = ptr.read_string Libcgraph.agstrfree graph.ptr, ptr string end
ruby
{ "resource": "" }
q5062
GV.BaseGraph.edge
train
def edge(name, tail, head, attrs = {}) component Edge, [name, tail, head], attrs end
ruby
{ "resource": "" }
q5063
GV.BaseGraph.sub_graph
train
def sub_graph(name, attrs = {}) graph = component SubGraph, [name], attrs yield graph if block_given? graph end
ruby
{ "resource": "" }
q5064
GV.Graph.save
train
def save(filename, format = 'png', layout = 'dot') Libgvc.gvLayout(@@gvc, ptr, layout.to_s) Libgvc.gvRenderFilename(@@gvc, ptr, format.to_s, filename); Libgvc.gvFreeLayout(@@gvc, ptr) nil end
ruby
{ "resource": "" }
q5065
GV.Graph.render
train
def render(format = 'png', layout = 'dot') Libgvc.gvLayout(@@gvc, ptr, layout.to_s) data_ptr = FFI::MemoryPointer.new(:pointer, 1) len_ptr = FFI::MemoryPointer.new(:int, 1) Libgvc.gvRenderData(@@gvc, ptr, format.to_s, data_ptr, len_ptr) len = len_ptr.read_uint data_ptr = data_ptr.read_pointer data = data_ptr.read_string len Libgvc.gvFreeRenderData(data_ptr) Libgvc.gvFreeLayout(@@gvc, ptr) data end
ruby
{ "resource": "" }
q5066
Languages.VariableBehaviourHelpers.setup_variable_behaviour
train
def setup_variable_behaviour expression = MODULEBASE + type_of_language + VARIABLECLASS + type_of_language begin clazz = Object.const_get(expression) @variableBehaviour = clazz.new(who_am_i) rescue NameError Util::LoggerKuniri.error('Class name error') end end
ruby
{ "resource": "" }
q5067
Languages.{LANG}.analyse_source
train
def analyse_source(pPath) @name = File.basename(pPath, ".*") @path = File.dirname(pPath) analyse_first_step(pPath) analyse_second_step end
ruby
{ "resource": "" }
q5068
Parser.Parser.start_parser
train
def start_parser if (@filesPath.empty?) raise Error::ConfigurationFileError, "Source path not have #{@language} files." end @filesPath.each do |file| language = @factory.get_language(@language) fileElement = Languages::FileElementData.new(file) source = File.open(file, 'rb') language.analyse_source(fileElement, source) @fileLanguage.push(language) end end
ruby
{ "resource": "" }
q5069
PaynetEasy::PaynetEasyApi::Callback.CallbackFactory.callback
train
def callback(callback_type) callback_class = "#{callback_type.camelize}Callback" callback_file = "callback/#{callback_type}_callback" begin instantiate_callback callback_file, callback_class, callback_type rescue LoadError => error if @@allowed_payneteasy_callback_types.include? callback_type instantiate_callback 'callback/paynet_easy_callback', 'PaynetEasyCallback', callback_type else raise error end end end
ruby
{ "resource": "" }
q5070
PaynetEasy::PaynetEasyApi::Callback.CallbackFactory.instantiate_callback
train
def instantiate_callback(callback_file, callback_class, callback_type) require callback_file PaynetEasy::PaynetEasyApi::Callback.const_get(callback_class).new(callback_type) end
ruby
{ "resource": "" }
q5071
SQLTree::Node.Base.equal_children?
train
def equal_children?(other) self.class.children.all? { |child| send(child) == other.send(child) } end
ruby
{ "resource": "" }
q5072
SQLTree::Node.Base.equal_leafs?
train
def equal_leafs?(other) self.class.leafs.all? { |leaf| send(leaf) == other.send(leaf) } end
ruby
{ "resource": "" }
q5073
RSpec.Benchmark.benchmark
train
def benchmark(times = 1, &block) elapsed = (1..times).collect do GC.start ::Benchmark.realtime(&block) * times end Result.new(elapsed) end
ruby
{ "resource": "" }
q5074
Magma.Renderer.format
train
def format(options) options.map do |key, value| [{ format: :f, size: :s, length: :hls_time, }[key] || key, value].map(&:to_s).join('=') end end
ruby
{ "resource": "" }
q5075
Magma.Renderer.melt_args
train
def melt_args(options) [ options[:infile], "-consumer avformat:#{outfile}", ].concat(pipe(options, %i[ symbolize_keys add_defaults select transform table format ])) end
ruby
{ "resource": "" }
q5076
Magma.Renderer.render!
train
def render! cmd = melt melt_args(options.merge(outfile: outfile)).join(' ') puts "Run: #{cmd}" puts run(cmd) do |_stdin, _stdout, stderr| stderr.each("\r") do |line| STDOUT.write "\r#{line}" end end end
ruby
{ "resource": "" }
q5077
Magma.Renderer.select
train
def select(options) # Clone original options = options.clone # Handle related options options.delete(:real_time) unless options.delete(:enable_real_time) # Reject options.select do |key, value| !value.nil? && %i[ format hls_list_size real_time length preset size start_number vcodec ].include?(key) end end
ruby
{ "resource": "" }
q5078
Magma.Renderer.table
train
def table(options) lpadding = options.keys.max_by(&:length).length + 2 rpadding = options.values.max_by { |v| v.to_s.length }.to_s.length puts 'PROPERTY'.ljust(lpadding) + 'VALUE' puts '=' * (lpadding + rpadding) options.keys.sort.each do |key| puts key.to_s.ljust(lpadding) + options[key].to_s end puts options end
ruby
{ "resource": "" }
q5079
Magma.Renderer.transform
train
def transform(options) options.map do |key, value| [key, ({ real_time: ->(x) { "-#{x}" }, }[key] || proc { |x| x }).call(value)] end.to_h end
ruby
{ "resource": "" }
q5080
Skydrive.Collection.items
train
def items @items = [] @data.each do |object_data| if object_data["type"] @items << "Skydrive::#{object_data["type"].capitalize}".constantize.new(client, object_data) elsif object_data["id"].match /^comment\..+/ @items << Skydrive::Comment.new(client, object_data) end end @items end
ruby
{ "resource": "" }
q5081
JsonRecord.AttributeMethods.read_attribute
train
def read_attribute (field, context) if field.multivalued? arr = json_attributes[field.name] unless arr arr = EmbeddedDocumentArray.new(field.type, context) json_attributes[field.name] = arr end return arr else val = json_attributes[field.name] if val.nil? and !field.default.nil? val = field.default.dup rescue field.default json_attributes[field.name] = val end return val end end
ruby
{ "resource": "" }
q5082
JsonRecord.AttributeMethods.write_attribute
train
def write_attribute (field, val, context) if field.multivalued? val = val.values if val.is_a?(Hash) json_attributes[field.name] = EmbeddedDocumentArray.new(field.type, context, val) else old_value = read_attribute(field, context) converted_value = field.convert(val) converted_value.parent = context if converted_value.is_a?(EmbeddedDocument) unless old_value == converted_value unless field.type.include?(EmbeddedDocument) or Thread.current[:do_not_track_json_field_changes] changes = changed_attributes if changes.include?(field.name) changes.delete(field.name) if converted_value == changes[field.name] else old_value = (old_value.clone rescue old_value) unless old_value.nil? || old_value.is_a?(Numeric) || old_value.is_a?(Symbol) || old_value.is_a?(TrueClass) || old_value.is_a?(FalseClass) changes[field.name] = old_value end end unless converted_value.nil? json_attributes[field.name] = converted_value else json_attributes.delete(field.name) end end context.json_attributes_before_type_cast[field.name] = val end return val end
ruby
{ "resource": "" }
q5083
TouRETS.Property.method_missing
train
def method_missing(method_name, *args, &block) mapped_key = key_map[method_name.to_sym] if attributes.has_key?(mapped_key) attributes[mapped_key] else super end end
ruby
{ "resource": "" }
q5084
Languages.FileElementData.add_global_variable
train
def add_global_variable(*pVariable) pVariable.flatten.each do |element| next unless element.is_a?(Languages::VariableGlobalData) @global_variables.push(element) end end
ruby
{ "resource": "" }
q5085
Edgarj.UserGroup.permitted?
train
def permitted?(model_name, requested_flags = 0) return false if self.kind != Kind::ROLE return true if admin? p = self.model_permissions.find_by_model(model_name) if requested_flags == 0 p else p && p.permitted?(requested_flags) end end
ruby
{ "resource": "" }
q5086
SafeNet.Auth.auth
train
def auth # entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth" # payload payload = { app: { name: @client.app_info[:name], version: @client.app_info[:version], vendor: @client.app_info[:vendor], id: @client.app_info[:id] }, permissions: @client.app_info[:permissions] } # api call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'}) req.body = payload.to_json res = http.request(req) # return's parser if res.code == "200" response = JSON.parse(res.body) # save it in conf.json conf = response.dup File.open(@client.app_info[:conf_path], "w") { |f| f << JSON.pretty_generate(conf) } else # puts "ERROR #{res.code}: #{res.message}" response = nil end # return response end
ruby
{ "resource": "" }
q5087
SafeNet.Auth.is_token_valid
train
def is_token_valid # entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth" # api call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Get.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_token()}" }) res = http.request(req) res.code == "200" end
ruby
{ "resource": "" }
q5088
SafeNet.Auth.revoke_token
train
def revoke_token # entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/auth" # api call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Delete.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}" }) res = http.request(req) res.code == "200" end
ruby
{ "resource": "" }
q5089
SafeNet.NFS.create_directory
train
def create_directory(dir_path, options = {}) # Default values options[:root_path] = 'app' if ! options.has_key?(:root_path) options[:is_private] = true if ! options.has_key?(:is_private) # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}" # Payload payload = { isPrivate: options[:is_private], } # Optional payload["metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta) # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", 'Content-Type' => 'application/json' }) req.body = payload.to_json res = http.request(req) res.code == "200" ? true : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5090
SafeNet.NFS.get_directory
train
def get_directory(dir_path, options = {}) # Default values options[:root_path] = 'app' if ! options.has_key?(:root_path) # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/directory/#{options[:root_path]}/#{SafeNet.escape(dir_path)}" # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Get.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", }) res = http.request(req) JSON.parse(res.body) end
ruby
{ "resource": "" }
q5091
SafeNet.NFS.create_file
train
def create_file(file_path, contents, options = {}) # Default values options[:root_path] = 'app' if ! options.has_key?(:root_path) contents ||= "" # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}" # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) headers = { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", } headers["Metadata"] = Base64.strict_encode64(options[:meta]) if options.has_key?(:meta) headers["Content-Type"] = options[:content_type] || 'text/plain' headers["Content-Length"] = contents.size.to_s req = Net::HTTP::Post.new(uri.path, headers) req.body = contents res = http.request(req) res.code == "200" ? true : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5092
SafeNet.NFS.get_file_meta
train
def get_file_meta(file_path, options = {}) # Default values options[:root_path] = 'app' if ! options.has_key?(:root_path) # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}" # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) headers = { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", } req = Net::HTTP::Head.new(uri.path, headers) res = http.request(req) res_headers = {} res.response.each_header {|k,v| res_headers[k] = v} res_headers["metadata"] = Base64.strict_decode64(res_headers["metadata"]) if res_headers.has_key?("metadata") res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5093
SafeNet.NFS.get_file
train
def get_file(file_path, options = {}) # Default values options[:offset] = 0 if ! options.has_key?(:offset) options[:root_path] = 'app' if ! options.has_key?(:root_path) # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}?" # Query params query = [] query << "offset=#{options[:offset]}" query << "length=#{options[:length]}" if options.has_key?(:length) # length is optional url = "#{url}#{query.join('&')}" # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) headers = { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", } headers["Range"] = options[:range] if options.has_key?(:range) req = Net::HTTP::Get.new(uri.path, headers) res = http.request(req) res_headers = {} res.response.each_header {|k,v| res_headers[k] = v} res.code == "200" ? {"headers" => res_headers, "body" => res.body} : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5094
SafeNet.NFS.move_file
train
def move_file(src_root_path, src_path, dst_root_path, dst_path, action = 'move') # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/movefile" # Payload payload = {} payload["srcRootPath"] = src_root_path # 'app' or 'drive' payload["srcPath"] = src_path payload["destRootPath"] = dst_root_path # 'app' or 'drive' payload["destPath"] = dst_path payload["action"] = action # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", 'Content-Type' => 'application/json' }) req.body = payload.to_json res = http.request(req) res.code == "200" ? true : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5095
SafeNet.NFS.delete_file
train
def delete_file(file_path, options = {}) # Default values options[:root_path] = 'app' if ! options.has_key?(:root_path) # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/nfs/file/#{options[:root_path]}/#{SafeNet.escape(file_path)}" # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Delete.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", }) res = http.request(req) res.code == "200" ? true : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5096
SafeNet.DNS.register_service
train
def register_service(long_name, service_name, service_home_dir_path, options = {}) # Entry point url = "#{@client.app_info[:launcher_server]}#{API_VERSION}/dns" # Payload payload = { longName: long_name, serviceName: service_name, rootPath: 'app', serviceHomeDirPath: service_home_dir_path, } # Optional payload["metadata"] = options[:meta] if options.has_key?(:meta) # API call uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) req = Net::HTTP::Post.new(uri.path, { 'Authorization' => "Bearer #{@client.key_helper.get_valid_token()}", 'Content-Type' => 'application/json' }) req.body = payload.to_json res = http.request(req) res.code == "200" ? true : JSON.parse(res.body) end
ruby
{ "resource": "" }
q5097
SafeNet.SD.set
train
def set(name, contents = '', type = 500) sd = @client.sd.update(name, contents) if sd.is_a?(Hash) && (sd["errorCode"] == -22) # doesn't exist sd = @client.sd.create(name, contents) end sd end
ruby
{ "resource": "" }
q5098
ErbLatex.Template.to_file
train
def to_file( file = suggested_filename ) execute do | contents | if file.is_a?(String) FileUtils.mv contents, file else file.write contents.read file.rewind end end file end
ruby
{ "resource": "" }
q5099
ErbLatex.Template.execute
train
def execute latex = compile_latex Dir.mktmpdir do | dir | @pass_count = 0 @log = '' success = false while log_suggests_rerunning? && @pass_count < 5 @pass_count += 1 success = execute_xelatex(latex,dir) end pdf_file = Pathname.new(dir).join( "output.pdf" ) if success && pdf_file.exist? yield pdf_file else errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ") STDERR.puts @log, errors if ErbLatex.config.verbose_logs raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log ) end end end
ruby
{ "resource": "" }