Search Results

Search found 99 results on 4 pages for 'gsub'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • paperclip callbacks or simple processor?

    - by holden
    I wanted to run the callback after_post_process but it doesn't seem to work in Rails 3.0.1 using Paperclip 2.3.8. It gives an error: undefined method `_post_process_callbacks' for #<Class:0x102d55ea0> I want to call the Panda API after the file has been uploaded. I would have created my own processor for this, but as Panda handles the processing, and it can upload the files as well, and queue itself for an undetermined duration I thought a callback would do fine. But the callbacks don't seem to work in Rails3. after_post_process :panda_create def panda_create video = Panda::Video.create(:source_url => mp3.url.gsub(/[?]\d*/,''), :profiles => "f4475446032025d7216226ad8987f8e9", :path_format => "blah/1234") end I tried require and include for paperclip in my model but it didn't seem to matter. Anyideas?

    Read the article

  • REXML Formatting issues

    - by dagda1
    Hi, I am using REXML to edit an xml file but have ran into difficulties with formatting. My original code looked like this: file = File.new( destination) doc = REXML::Document.new file doc.elements.each("configuration/continuity2") do |element| element.attributes["islive"] = "true" element.attributes["pagetitle"] = "#{@client.page_title}" element.attributes["clientname"] = "#{@client.name}" end doc.elements.each("configuration/continuity2/plans") do |element| element.attributes["storebasedir"] = "#{@client.store_dir}" end I first of all had to add the following code as REXML was adding single quotes instead of double quotes. I found the following via google: REXML::Attribute.class_eval( %q^ def to_string %Q[#@expanded_name="#{to_s().gsub(/"/, '&quot;')}"] end ^ ) I also have a problem in that REXML is reformatting the document. are there ways to stop this? Cheers Paul

    Read the article

  • ActiveRecord field normalization

    - by Bill
    I feel bad asking this question, as I thought I knew enough about Activerecord to answer this myslef. But such is the way of having SO available ... I'm trying to remove the commas from a field in a model of mine, I want the user to be able to type a number , ie 10,000 and that number be stored in the database as 10000. I was hoping that I could do some model-side normalization to remove the comma. I don't want to depend on the view or controller to properly format my data. I tried ; before_validation :normalize def normalize self['thenumber'] = self['thenumber'].to_s.gsub(',','') end no worky :(

    Read the article

  • 400 error when submitting tumblr post (ruby on rails)

    - by Matenia Rossides
    I am having a bit of an issue with getting tumblr working within a rails app. This is the snippet of code which results in a 400 error (meaning that there was an incorrect parameter) @postcontent = @post.content.gsub(/<\/?[^>]*>/, "") post = Tumblr::Post.create(:email => 'valid@email', :password => 'mypassword', :type => 'video', :embed = @post.video_html, :caption = @postcontent) I have checked the API docs and checked my code and code content being rendered, and it still does not want to work. The funny thing is that it worked previously. It was working about a week ago. Has something changed with tumblr?

    Read the article

  • Converting old Mailer to Rails 3 (multipart/mixed)

    - by Oscar Del Ben
    I'm having some difficulties converting this old mailer api to rails 3: content_type "multipart/mixed" part :content_type => "multipart/alternative" do |alt| alt.part "text/plain" do |p| p.body = render_message("summary_report.text.plain.erb", :message = message.gsub(/<.br./,"\n"), :campaign=campaign, :aggregate=aggregate, :promo_messages=campaign.participating_promo_msgs) end alt.part "text/html" do |p| p.body = render_message("summary_report.text.html.erb", :message = message, :campaign=campaign, :aggregate=aggregate,:promo_messages=campaign.participating_promo_msgs) end end if bounce_path attachment :content_type => "text/csv", :body=> File.read(bounce_path), :filename => "rmo_bounced_emails.csv" end attachment :content_type => "application/pdf", :body => File.read(report_path), :filename=>"rmo_report.pdf" In particular I don't understand how to differentiate the different multipart options. Any idea?

    Read the article

  • Merge a hash with the key/values of a string in ruby

    - by LazyJason
    Hi there, I'm trying to merge a hash with the key/values of string in ruby. i.e. h = {:day => 4, :month => 8, :year => 2010} s = "/my/crazy/url/:day/:month/:year" puts s.interpolate(h) All I've found is to iterate the keys and replace the values. But I'm not sure if there's a better way doing this? :) class String  def interpolate(e)    self if e.each{|k, v| self.gsub!(":#{k}", "#{v}")}  end end Thanks

    Read the article

  • How do I get the output of an Xcode user script to auto indent?

    - by John Gallagher
    The Problem I want to press a key when I have a line highlighted and convert from a single line: JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1 to:date2 intoMOC:mockRawMOC]; to a multiline statement: JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1 to:date2 intoMOC:mockRawMOC]; What I've Tried I've got a simple ruby script that almost gets me there. #!/usr/bin/env ruby s = STDIN.read s.gsub!(/(:.+?\w) (\w.+?)/,'\1' + "\n\t" +'\2') print s When I set the output to "Replace Selection", I get this: JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1 to:date2 intoMOC:mockRawMOC]; When I set the output to "Place on Clipboard", then paste it in, I get the desired result: JGLogEntry *logEntry = [JGLogEntry applicationNoWindowsFrom:date1 to:date2 intoMOC:mockRawMOC]; However, this is two keypresses which is clumsy. Any ideas how I can get the replaced text to obey Xcode's auto indent rules?

    Read the article

  • Ruby: map tags into a boolean condition to get a true/false result

    - by cgyDeveloper
    I have an array of tags per item like so: item1 = ['new', 'expensive'] item2 = ['expensive', 'lame'] I also have a boolean expression as a string based on possible tags: buy_it = "(new || expensive) && !lame" How can I determine if an item matches the buying criteria based on the tags associated with it? My original thought was to do a gsub on all words in buy_it to become 'true' or 'false' based on them existing in the itemx tags array and then exec the resulting string to get a boolean result. But since the Ruby community is usually more creative than me, is there a better solution?

    Read the article

  • Substitute all matches with values in Ruby regular expression

    - by Lewisham
    Hi all, I'm having a problem with getting a Ruby string substitution going. I'm writing a preprocessor for a limited language that I'm using, that doesn't natively support arrays, so I'm hacking in my own. I have a line: x[0] = x[1] & x[1] = x[2] I want to replace each instance with a reformatted version: x__0 = x__1 & x__1 = x__2 The line may include square brackets elsewhere. I've got a regex that will match the array use: array_usage = /(\w+)\[(\d+)\]/ but I can't figure out the Ruby construct to replace each instance one by one. I can't use .gsub() because that will match every instance on the line, and replace every array declaration with whatever the first one was. .scan() complains that the string is being modified if you try and use scan with a .sub()! inside a block. Any ideas would be appreciated!

    Read the article

  • Replacing quotes in a file

    - by Matthijs
    I have a large number of large semicolon-separated data files. All string fields are surrounded by double quotes. In some of the files, there are extra quotes in the string fields, which messes up the subsequent importing of the data for analysis (I'm importing to Stata). This code allows me to see the problematic quotes using gnu-awk: echo '"This";"is";1;"line" of" data";""with";"extra quotes""' | awk 'BEGIN { FPAT = "([^;]+)|(\"[^\"]+\")"}; {for ( i=1 ; i<=NF ; i++ ) if ($i ~ /^"(.*".*)+"$/) {print NR, $i}}' 1 "line" of" data" 1 ""with" 1 "extra quotes"" but I do not know how to replace them. I was thinking of doing the replace manually, but it turns out that there are several hundred matches in some of the files. I know about awk's -sub-, -gsub-, and -match- functions, but I am not sure how to design a search and replace for this specific problem. In the example above, the respective fields should be "This", "is", 1, "line of data", "with", "extra quotes", that is: all semicolons are separators, and all quotes except for the outermost quotes should be removed. Should I may be use -sed-, or is -awk- the right tool? Hope you can help me out! Thanks, Matthijs

    Read the article

  • ps forrest for session id

    - by azatoth
    Often I want to get a nice readout what process are running and their relationship; I usually by habit runs ps auxfww and eventual grep for the process in question. Having been thinking about the problem I tried to create an oneliner to get the process tree in ps ufww format for all processes which has the session id specified by arbitrary process name(s); ending up in following code: ps ufww --sid=$(ps -C apache2 -o sess --no-headers | sort | uniq | grep -v -E '^ +0$' | awk 'NR==1{x=$0;next}NF{x=x","$0};END{gsub(/[[:space:]]*/,"",x);print x}') giving for example following output: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 4157 0.0 0.1 41264 3120 ? Ss Jun11 0:00 /usr/sbin/apache2 -k start www-data 4329 0.0 0.0 41264 1976 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 4330 0.0 0.0 41264 2028 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 4331 0.0 0.0 41264 2028 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 4332 0.0 0.0 41264 2028 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 4333 0.0 0.0 41264 2032 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 6648 0.0 0.0 41264 1884 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 6654 0.0 0.0 41264 1884 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start www-data 6655 0.0 0.0 41264 1884 ? S Jun11 0:00 \_ /usr/sbin/apache2 -k start I do wonder now if anyone has an better idea to solve this issue? Are there anything out there that is easier to "oneline" and gives above or better information? For example I would actually want to have included all childs relative any parent. (uncertain if this should be on SF instead, but felt it was more like an programming question)

    Read the article

  • ruby nl2br outside <code> ... </code>

    - by Julien P.
    Hi everyone, I've been struggling on this thing for a week without being able to find what I'm looking for. Here is what I'd like to do: I'm setting up a wiki where I can post all my knowledge to (yes, I know a couple things :p) but I can't render it the way I'd like to. The bodies of my posts are text fields. In order to render them the right way I run the following command: @post.body.gsub("\n", "<br />") I also have some tags with some code inside that looks like this < code my code < /code. Here come's the issue. Every line between the < code and < /code tags are changed to but it doesn'r render properly since I'm using a code render template. Therefore, I'd like to know if there is a way to change all \n to < br / except for those between < code and < /code Thank you everyone for reading this and helping me out. PS: Please do not consider the spaces after the < in each tag. I had to do this to "espace" them. Julien

    Read the article

  • Strange \n in base64 encoded string in Ruby

    - by intellidiot
    The inbuilt Base64 library in Ruby is adding some '\n's. I'm unable to find out the reason. For this special example: irb(main):001:0> require 'rubygems' => true irb(main):002:0> require 'base64' => true irb(main):003:0> str = "1110--ad6ca0b06e1fbeb7e6518a0418a73a6e04a67054" => "1110--ad6ca0b06e1fbeb7e6518a0418a73a6e04a67054" irb(main):004:0> Base64.encode64(str) => "MTExMC0tYWQ2Y2EwYjA2ZTFmYmViN2U2NTE4YTA0MThhNzNhNmUwNGE2NzA1\nNA==\n" The \n's are at the last and 6th position from end. The decoder (Base64.decode64) returns back the old string perfectly. Strange thing is, these \n's don't add any value to the encoded string. When I remove the newlines from the output string, the decoder decodes it again perfectly. irb(main):005:0> Base64.decode64(Base64.encode64(str).gsub("\n", '')) == str => true More of this, I used an another JS library to produce the base64 encoded output of the same input string, the output comes without the \n's. Is this a bug or anything else? Has anybody faced this issue before? FYI, $ ruby -v ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]

    Read the article

  • PDF to PNG Processor - Paperclip

    - by Josh Crowder
    I am trying to develop a system in which a user can upload a slideshow (pdf) and it'll export each slide as a png. After some digging around I came across a post on here that suggested using a processor. I've had a go, but I cant get the command to run, if it is running then I don't know what is happening because no errors are being shown. Any help would be appreciated! module Paperclip class Slides < Processor def initialize(file, options = {}, attachment = nill) super @file = file @instance = options[:instance] @current_format = File.extname(@file.path) @basename = File.basename(@file.path, @current_format) end def make dst = Tempfile.new( [ @basename, @format].compact.join(".")) dst.binmode command = <<-end_command -size 640x300 #{ File.expand_path(dst.path) } tester.png end_command begin success = Paperclip.run("convert", command.gsub(/\s+/, " "))) rescue PaperclipCommandLineError raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" end end end end I think my problem is with the convert command... When I run that command by hand, it works but it doesn't give the details of each slide it just executes it. What I need to happen is once its made all the slides, pass back the data to a new model... or I know where all the slides are, but once I get to that point I'm not sure what todo.

    Read the article

  • Ruby Design Problem for SQL Bulk Inserter

    - by crunchyt
    This is a Ruby design problem. How can I make a reusable flat file parser that can perform different data scrubbing operations per call, return the emitted results from each scrubbing operation to the caller and perform bulk SQL insertions? Now, before anyone gets narky/concerned, I have written this code already in a very unDRY fashion. Which is why I am asking any Ruby rockstars our there for some assitance. Basically, everytime I want to perform this logic, I create two nested loops, with custom processing in between, buffer each processed line to an array, and output to the DB as a bulk insert when the buffer size limit is reached. Although I have written lots of helpers, the main pattern is being copy pasted everytime. Not very DRY! Here is a Ruby/Pseudo code example of what I am repeating. lines_from_file.each do |line| line.match(/some regex/).each do |sub_str| # Process substring into useful format # EG1: Simple gsub() call # EG2: Custom function call to do complex scrubbing # and matching, emitting results to array # EG3: Loop to match opening/closing/nested brackets # or other delimiters and emit results to array end # Add processed lines to a buffer as SQL insert statement @buffer << PREPARED INSERT STATEMENT # Flush buffer when "buffer size limit reached" or "end of file" if sql_buffer_full || last_line_reached @dbc.insert(SQL INSERTS FROM BUFFER) @buffer = nil end end I am familiar with Proc/Lambda functions. However, because I want to pass two separate procs to the one function, I am not sure how to proceed. I have some idea about how to solve this, but I would really like to see what the real Rubyists suggest? Over to you. Thanks in advance :D

    Read the article

  • Ruby : UTF-8 IO

    - by subtenante
    I use ruby 1.8.7. I try to parse some text files containing greek sentences, encoded in UTF-8. (I can't much paste here sample files, because they are subject to copyright. Really just some greek text encoded in UTF-8.) I want, for each file, to parse the file, extract all the words, and make a list of each new word found in this file. All that saved to one big index file. Here is my code : #!/usr/bin/ruby -KU def prepare_line(l) l.gsub(/^\s*[ST]\d+\s*:\s*|\s+$|\(\d+\)\s*/u, "") end def tokenize(l) l.split /['·.;!:\s]+/u end $dict = {} $cpt = 0 $out = File.new 'out.txt', 'w' def lesson(file) $cpt = $cpt + 1 file.readlines.each do |l| $out.puts l l = prepare_line l tokenize(l).each do |t| unless $dict[t] $dict[t] = $cpt $out.puts " #{t}\n" end end end end Dir.new('etc/').each do |filename| f = File.new("etc/#{filename}") unless File.directory? f lesson f end end Here is part of my output : ?@???†?†?????????? ?...[snip very long hangul/hanzi mishmash]... ????????†? ???N2 : ?e?te?? (2) µ???µa (Note that the puts l part seems to work fine, at the end of the given output line.) Any idea what is wrong with my code ? (General comments about ruby idioms I could use are very welcome, I'm really a beginner.)

    Read the article

  • convert variable with mixed date formats to one format in r

    - by jalapic
    A sample of my dataframe: date 1 25 February 1987 2 20 August 1974 3 9 October 1984 4 18 August 1992 5 19 September 1995 6 16-Oct-63 7 30-Sep-65 8 22 Jan 2008 9 13-11-1961 10 18 August 1987 11 15-Sep-70 12 5 October 1994 13 5 December 1984 14 03/23/87 15 30 August 1988 16 26-10-1993 17 22 August 1989 18 13-Sep-97 I have a large dataframe with a date variable that has multiple formats for dates. Most of the formats in the variable are shown above- there are a couple of very rare others too. The reason why there are multiple formats is that the data were pulled together from various websites that each used different formats. I have tried using straightforward conversions e.g. strftime(mydf$date,"%d/%m/%Y") but these sorts of conversion will not work if there are multiple formats. I don't want to resort to multiple gsub type editing. I was wondering if I am missing a more simple solution? Code for example: structure(list(date = structure(c(12L, 8L, 18L, 6L, 7L, 4L, 14L, 10L, 1L, 5L, 3L, 17L, 16L, 11L, 15L, 13L, 9L, 2L), .Label = c("13-11-1961", "13-Sep-97", "15-Sep-70", "16-Oct-63", "18 August 1987", "18 August 1992", "19 September 1995", "20 August 1974", "22 August 1989", "22 Jan 2008", "03/23/87", "25 February 1987", "26-10-1993", "30-Sep-65", "30 August 1988", "5 December 1984", "5 October 1994", "9 October 1984"), class = "factor")), .Names = "date", row.names = c(NA, -18L), class = "data.frame")

    Read the article

  • Escape characters in MySQL, in Ruby

    - by Swards
    I have a couple escaped characters in user-entered fields that I can't figure out. I know they are the "smart" single and double quotes, but I don't know how to search for them in mysql. The characters in ruby, when output from Ruby look like \222, \223, \224 etc irb> "\222".length => 1 So - do you know how to search for these in mysql? When I look in mysql, they look like '?'. I'd like to find all records that have this character in the text field. I tried mysql> select id from table where field LIKE '%\222%' but that did not work. Some more information - after doing a mysqldump, this is how one of the characters is represented - '\\xE2\\x80\\x99'. It's the smart single quote. Ultimately, I'm building an RTF file and the characters are coming out completely wrong, so I'm trying to replace them with 'dumb' quotes for now. I was able to do a gsub(/\222\, "'"). Thanks.

    Read the article

  • Wiki-fying a text using LPeg

    - by Stigma
    Long story coming up, but I'll try to keep it brief. I have many pure-text paragraphs which I extract from a system and re-output in wiki format so that the copying of said data is not such an arduous task. This all goes really well, except that there are no automatic references being generated for the 'topics' we have pages for, which end up needing to be added by reading through all the text and adding it in manually by changing Topic to [[Topic]]. First requirement: each topic is only to be made clickable once, which is the first occurrence. Otherwise, it would become a really spammy linkfest, which would detract from readability. To avoid issues with topics that start with the same words Second requirement: overlapping topic names should be handled in such a way that the most 'precise' topic gets the link, and in later occurrences, the less precise topics do not get linked, since they're likely not correct. Example: topics = { "Project", "Mary", "Mr. Moore", "Project Omega"} input = "Mary and Mr. Moore work together on Project Omega. Mr. Moore hates both Mary and Project Omega, but Mary simply loves the Project." output = function_to_be_written(input) -- "[[Mary]] and [[Mr. Moore]] work together on [[Project Omega]]. Mr. Moore hates both Mary and Project Omega, but Mary simply loves the [[Project]]." Now, I quickly figured out a simple or complicated string.gsub() could not get me what I need to satisfy the second requirement, as it provides no way to say 'Consider this match as if it did not happen - I want you to backtrack further'. I need the engine to do something akin to: input = "abc def ghi" -- Looping over the input would, in this order, match the following strings: -- 1) abc def ghi -- 2) abc def -- 3) abc -- 4) def ghi -- 5) def -- 6) ghi Once a string matches an actual topic and has not been replaced before by its wikified version, it is replaced. If this topic has been replaced by a wikified version before, don't replace, but simply continue the matching at the end of the topic. (So for a topic "abc def", it would test "ghi" next in both cases.) Thus I arrive at LPeg. I have read up on it, played with it, but it is considerably complex, and while I think I need to use lpeg.Cmt and lpeg.Cs somehow, I am unable to mix the two properly to make what I want to do work. I am refraining from posting my practice attempts as they are of miserable quality and probably more likely to confuse anyone than assist in clarifying my problem. (Why do I want to use a PEG instead of writing a triple-nested loop myself? Because I don't want to, and it is a great excuse to learn PEGs.. except that I am in over my head a bit. Unless it is not possible with LPeg, the first is not an option.)

    Read the article

  • Ruby: Parse, replace, and evaluate a string formula

    - by Swartz
    I'm creating a simple Ruby on Rails survey application for a friend's psychological survey project. So we have surveys, each survey has a bunch of questions, and each question has one of the options participants can choose from. Nothing exciting. One of the interesting aspects is that each answer option has a score value associated with it. And so for each survey a total score needs to be calculated based on these values. Now my idea is instead of hard-coding calculations is to allow user add a formula by which the total survey score will be calculated. Example formulas: "Q1 + Q2 + Q3" "(Q1 + Q2 + Q3) / 3" "(10 - Q1) + Q2 + (Q3 * 2)" So just basic math (with some extra parenthesis for clarity). The idea is to keep the formulas very simple such that anyone with basic math can enter them without resolving to some fancy syntax. My idea is to take any given formula and replace placeholders such as Q1, Q2, etc with the score values based on what the participant chooses. And then eval() the newly formed string. Something like this: f = "(Q1 + Q2 + Q3) / 2" # some crazy formula for this survey values = {:Q1 => 1, :Q2 => 2, :Q3 => 2} # values for substitution result = f.gsub(/(Q\d+)/) {|m| values[$1.to_sym] } # string to be eval()-ed eval(result) So my questions are: Is there a better way to do this? I'm open to any suggestions. How to handle formulas where not all placeholders were successfully replaced (e.g. one question wasn't answered)? Ex: {:Q3 = 2} wasn't in values hash? My idea is to rescue eval()... any thoughts? How to get proper result? Should be 2.5, but due to integer arithmetic, it will truncate to 2. I can't expect people who provide the correct formula (e.g. / 2.0 ) to understand this nuance. I do not expect this, but how to best protect eval() from abuse (e.g. bad formula, manipulated values coming in)? Thank you!

    Read the article

  • Using amCharts in Ruby on Rails

    - by Dexter
    I have followed this tutorial in order to use amChart and it worked with no problems , now I am trying to generate a chart with amCharts to show each user and the sign in count but i cant make it work because it not getting the data correctly, what i am missing here ? how can i show user email and sign_in_count ? Users_controller.rb class UsersController < ApplicationController load_and_authorize_resource def index @users = User.all respond_to do |format| format.html # index.html.erb format.json { render :json => @users } end end def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save flash[:notice] = 'A new user created successfully.' redirect_to users_path else flash[:error] = 'An error occurred please try again!' redirect_to users_path end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) flash[:notice] = 'Profile updated' redirect_to users_path else render 'edit' end end def destroy @user = User.find(params[:id]) if current_user == (@user) flash[:error] = "Admin suicide warning: Can't delete yourself." else @user.destroy flash[:notice] = 'User deleted' redirect_to users_path end end def checkname if User.where('user_name = ?', params[:user]).count == 0 render :nothing => true, :status => 200 else render :nothing => true, :status => 409 end return end end Users_helper.rb module UsersHelper def convert_to_amcharts_json(data_array) data_array.to_json.gsub(/\"text\"/, "text").html_safe end end index.html.erb <div id="chartdiv" style="width: 100%; height: 400px;"></div> <script type="text/javascript"> var chart; var chartData = <%= convert_to_amcharts_json(@users) %>; AmCharts.ready(function () { // SERIAL CHART chart = new AmCharts.AmSerialChart(); chart.dataProvider = chartData; chart.categoryField = "email"; // the following two lines makes chart 3D chart.depth3D = 20; chart.angle = 30; // AXES // category var categoryAxis = chart.categoryAxis; categoryAxis.labelRotation = 90; categoryAxis.dashLength = 5; categoryAxis.gridPosition = "start"; // value var valueAxis = new AmCharts.ValueAxis(); valueAxis.title = "Most Active users"; valueAxis.dashLength = 5; chart.addValueAxis(valueAxis); // GRAPH var graph = new AmCharts.AmGraph(); graph.valueField = "sign_in_count"; graph.colorField = "color"; graph.balloonText = "<span style='font-size:14px'>[[category]]: <b>[[value]]</b></span>"; graph.type = "column"; graph.lineAlpha = 0; graph.fillAlphas = 1; chart.addGraph(graph); // CURSOR var chartCursor = new AmCharts.ChartCursor(); chartCursor.cursorAlpha = 0; chartCursor.zoomable = false; chartCursor.categoryBalloonEnabled = false; chart.addChartCursor(chartCursor); // WRITE chart.write("chartdiv"); }); </script>

    Read the article

  • A couple of pattern matching issues with pattern matching in Lua

    - by Josh
    I'm fairly new to lua programming, but I'm also a quick study. I've been working on a weather forecaster for a program that I use, and it's working well, for the most part. Here is what I have so far. (Pay no attention to the zs.stuff. That is program specific and has no bearing on the lua coding.) if not http then http = require("socket.http") end local locale = string.gsub(zs.params(1),"%s+","%%20") local page = http.request("http://www.wunderground.com/cgi-bin/findweather/getForecast?query=" .. locale .. "&wuSelect=WEATHER") local location = string.match(page,'title="([%w%s,]+) RSS"') --print("Gathering weather information for " .. location .. ".") --local windspeed = string.match(page,'<span class="nobr"><span class="b">([%d.]+)</span>&nbsp;mph</span>') --print(windspeed) local condition = string.match(page, '<td class="vaM taC"><img src="http://icons-ecast.wxug.com/i/c/a/[%w_]+.gif" width="42" height="42" alt="[%w%s]+" class="condIcon" />') --local image = string.match(page, '<img src="http://icons-ecast.wxug.com/i/c/a/(.+).gif" width="42" height="42" alt="[%w%s]+" class="condIcon" />') local temperature = string.match(page,'pwsvariable="tempf" english="&deg;F" metric="&deg;C" value="([%d.]+)">') local humidity = string.match(page,'pwsvariable="humidity" english="" metric="" value="(%d+)"') zs.say(location) --zs.say("image ./Images/" .. image .. ".gif") zs.say("<color limegreen>Condition:</color> <color white>" .. condition .. "</color>") zs.say("<color limegreen>Temperature: </color><color white>" .. temperature .. "F</color>") zs.say("<color limegreen>Humidity: </color><color white>" .. humidity .. "%</color>") My main issue is this: I changed the 'condition' and added the 'image' variables to what they are now. Even though the line it's supposed to be matching comes directly from the webpage, it fails to match at all. So I'm wondering what it is I'm missing that's preventing this code from working. If I take out the <td class="vaM taC">< img src="http://icons-ecast.wxug.com/i/c/a/[%w_]+.gif" it'll match condition flawlessly. (For whatever reason, I can't get the above line to display correctly, but there is no space between the `< and img) Can anyone point out what is wrong with it? Aside from the pattern matching, I assure you the line is verbatim from the webpage. Another question I had is the ability to match across line breaks. Is there any possible way to do this? The reason why I ask is because on that same page, a few of the things I need to match are broken up on separate lines, and since the actual pattern I'm wanting to match shows up in other places on the page, I need to be able to match across line breaks to get the exact pattern. I appreciate any help in this matter!

    Read the article

  • LUA: A couple of pattern matching issues

    - by Josh
    I'm fairly new to lua programming, but I'm also a quick study. I've been working on a weather forecaster for a program that I use, and it's working well, for the most part. Here is what I have so far. (Pay no attention to the zs.stuff. That is program specific and has no bearing on the lua coding.) if not http then http = require("socket.http") end local locale = string.gsub(zs.params(1),"%s+","%%20") local page = http.request("http://www.wunderground.com/cgi-bin/findweather/getForecast?query=" .. locale .. "&wuSelect=WEATHER") local location = string.match(page,'title="([%w%s,]+) RSS"') --print("Gathering weather information for " .. location .. ".") --local windspeed = string.match(page,'<span class="nobr"><span class="b">([%d.]+)</span>&nbsp;mph</span>') --print(windspeed) local condition = string.match(page, '<td class="vaM taC"><img src="http://icons-ecast.wxug.com/i/c/a/[%w_]+.gif" width="42" height="42" alt="[%w%s]+" class="condIcon" />') --local image = string.match(page, '<img src="http://icons-ecast.wxug.com/i/c/a/(.+).gif" width="42" height="42" alt="[%w%s]+" class="condIcon" />') local temperature = string.match(page,'pwsvariable="tempf" english="&deg;F" metric="&deg;C" value="([%d.]+)">') local humidity = string.match(page,'pwsvariable="humidity" english="" metric="" value="(%d+)"') zs.say(location) --zs.say("image ./Images/" .. image .. ".gif") zs.say("<color limegreen>Condition:</color> <color white>" .. condition .. "</color>") zs.say("<color limegreen>Temperature: </color><color white>" .. temperature .. "F</color>") zs.say("<color limegreen>Humidity: </color><color white>" .. humidity .. "%</color>") My main issue is this: I changed the 'condition' and added the 'image' variables to what they are now. Even though the line it's supposed to be matching comes directly from the webpage, it fails to match at all. So I'm wondering what it is I'm missing that's preventing this code from working. If I take out the <td class="vaM taC">< img src="http://icons-ecast.wxug.com/i/c/a/[%w_]+.gif" it'll match condition flawlessly. (For whatever reason, I can't get the above line to display correctly, but there is no space between the `< and img) Can anyone point out what is wrong with it? Aside from the pattern matching, I assure you the line is verbatim from the webpage. Another question I had is the ability to match across line breaks. Is there any possible way to do this? The reason why I ask is because on that same page, a few of the things I need to match are broken up on separate lines, and since the actual pattern I'm wanting to match shows up in other places on the page, I need to be able to match across line breaks to get the exact pattern. I appreciate any help in this matter!

    Read the article

  • ActionController::RoutingError (No route matches {:action=>"show", :controller=>"users", :id=>nil}):

    - by Matt Bishop
    I have been trying to fix this routing error for a long time. I would appreciate any assistance! This error is preventing me from being able to authenticate. Here is what I am getting in my Heroku logs. app/controllers/authentications_controller.rb:12:in `create' ActionController::RoutingError (No route matches {:action=>"show", :controller=>"users", :id=>nil}) Here is the routes.rb file: Company::Application.routes.draw do resources :profile_individual resources :careers match 'careers' => 'careers#index' match 'about' => 'about#index' constraints(:subdomain => /^$|www/) do devise_for :users resources :authentications, :identities #, :beta_invitations resources :users do resources :invitations, :controller => 'UserInvitation' do post :upload, :on => :collection get :email_template, :on => :collection get :plaintext_template, :on => :collection get :facebook_invitation, :on => :collection end member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns end end resources :password_resets do get 'password_reset' => 'password_resets#show', :as => 'password_reset' end resources :events, :only => [:new, :index, :create] resources :organizations, :only => [:index, :create] resources :orders do post :ipn, :on => :member resource :payment do member do post :relay_response get :receipt end end resource :paypal_integration do member do get :authorize get :cancel post :finalize end end end match '/users/:id/impact/money/:d' => 'users#impact_money_graph', :constraints => {:d => /\d+{4}_\d+{2}-\d+{2}/}, :as => :user_impact_money match '/users/:id/impact/money' => 'users#impact_money_graph', :as => :user_impact_money match '/users/:id/impact/recruits/:d' => 'users#impact_recruits_graph', :constraints => {:d => /\d+{4}_\d+{2}-\d+{2}/}, :as => :user_impact_recruits match '/users/:id/impact/recruits' => 'users#impact_recruits_graph', :as => :user_impact_recruits match '/auth/failure' => 'authentications#failure' match '/auth/:provider/callback' => 'authentications#create' match '/auth/:provider/callback' => 'authentications#show', :controller => 'users', :as => :login match '/logout' => 'authentications#destroy', :as => :logout match '/login' => 'authentications#new', :as => :login match "/join_team/:id" => "team_members#join", :as => :join_team match "/rsvp/:id" => "rsvps#show", :as => :rsvp match "/signup" => 'authentications#signup', :as => :signup match "/beacon/:id.gif" => "email_beacons#show", :as => :email_beacon root :to => "homes#show" match '/corporate_giving' => "homes#corporate_giving" end constraints(Subdomain) do resource :organization, :path => "/", :only => [:edit, :update] do member do get :org_photos_videos get :org_recent_activity end end resources :events, :except => [:index] do post :publish, :on => :member resource :supporter_invite resource :team_management do post :mailer, :on => :member end resource :team_member do post :invite, :on => :member end resource :rsvp do put :make_order, :on => :collection get :make_order, :on => :collection end resources :invites do post :upload, :on => :collection end resources :ticket_tiers, :team_members end match "/events" => redirect("/") root :to => "organizations#show" end namespace :admin do resources :stats resources :organizations resources :campaigns do resources :rewards resources :contents put :header, :action => 'header_update' end resources :users do member do post :grant_access post :revoke_access end end resources :nonprofits do member do put :approve put :revoke end end end resources :campaigns do get :find_charities, :on => :collection get :how_many_charities, :on => :collection member do post :join get :join post :header, :action => 'header_creation' put :header, :action => 'header_update' end resources :rewards resources :contents resource :donations do resource :paypal_integration, :controller => 'donations' do member do get :authorize get :cancel post :finalize end end end end match '/campaigns/:id/graph/:d' => 'campaigns#graph', :constraints => {:d => /\d+{4}_\d+ {2}-\d+{2}/}, :as => :graph_campaign match '/campaigns/:id/graph' => 'campaigns#graph', :as => :graph_campaign resources :business_campaigns, :controller => 'campaigns' resources :businesses do put :logo, :on => :collection, :action => 'upload_logo' member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns end end resources :nonprofit_campaigns, :controller => 'campaigns' resources :nonprofits do put :logo, :on => :collection, :action => 'upload_logo' member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns get :supporting_campaigns end end resources :publicities match '/campaigns/:campaign_id/rewards/:id' => 'campaigns#reward', :via => :get match "/robots.txt" => "application#robots_txt" match "/beta_invitations" => redirect('/') resource :sitemap resources :referrals end Here is my authentications_controller.rb file class AuthenticationsController < ApplicationController skip_before_filter :require_beta_access before_filter :redirect_to_profile_if_logged_in, :only => [:create, :new] layout :resolve_layout def create omniauth = request.env["omniauth.auth"] authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) if authentication && authentication.user.present? sign_in(:user, authentication.user) redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) elsif current_user current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid']) redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) else user = User.new user.apply_omniauth(omniauth) logger.debug "=======================auth=============================" logger.debug session[:referrer_token] logger.debug "========================================================" if session[:referrer_token] publicity = Publicity.find_by_token(session[:referrer_token]) user.invited_by = publicity user.recruited_by = publicity end if user.save sign_in(user) unless session[:redirect_to] session[:referrer_token] = nil end redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) #redirect_to session[:redirect_to] || campaigns_url(:tc => request.env['omniauth.params']['tc']) #tc is for AB testing else session[:omniauth] = omniauth.except('extra') redirect_to signup_path end end end def failure flash[:error] = "Please check your email and password and try again" redirect_to login_path end def destroy reset_session redirect_to root_path end def signup # end private def redirect_to_profile_if_logged_in redirect_to user_path(current_user.permalink) if current_user end def resolve_layout case action_name when "new", "signup" "authentication" else "selfcontained" end end end I am adding my appplication_controller.rb too: class ApplicationController < ActionController::Base #Wrote by George for beta users -before_filter :require_beta_access before_filter :save_referrer_token protect_from_forgery helper_method :organization_admin?, :team_member?, :profile_url, :current_profile def set_headers # Set our headers here end def save_referrer_token #session.delete(:referrer_token) if params[:ref] publicity = Publicity.find_by_token(params[:ref]) logger.debug "========================================================" logger.debug current_profile.nil? logger.debug publicity.creator logger.debug current_profile logger.debug current_profile != publicity.creator session[:referrer_token] = params[:ref] if current_profile.nil? or publicity.creator != current_profile logger.debug session[:referrer_token] logger.debug "========================================================" end end def robots_txt robots = File.read(Rails.root + "public/robots.#{Rails.env}.txt") render :text => robots, :layout => false, :content_type => "text/plain" end def load_organization @organization = Organization.find_by_permalink(request.subdomain) raise ActiveRecord::RecordNotFound if @organization.nil? end def require_user unless current_user session[:redirect_to] = request.url redirect_to login_url(:host => request.domain) end end def require_beta_access if !current_user redirect_to root_url(:host => request.domain) elsif !current_user.beta_access? redirect_to new_beta_invitation_url(:host => request.domain) end end def require_organization_admin unless organization_admin? redirect_to root_url(:subdomain => @organization.permalink) end end def team_member? if current_user && @event.team_memberships.where(:user_id => current_user.id).count != 0 true end end def organization_admin? if current_user && current_user.beta_access? && @organization && @organization.memberships.where(:user_id => current_user.id, :role => 'admin').count != 0 true end end def profile_url(profile, opt = nil) if profile == current_user user_url(profile, :host => opt[:host]) elsif profile.is_a? BusinessProfile business_url(profile) elsif profile.is_a? NonprofitProfile nonprofit_url(profile) end end def set_current_profile(profile) session[:current_profile] = profile end def current_user @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] end def current_profile #if session session[:current_profile] || current_user #else # nil #end end IGIVEMORE_HTML5_OPTIOINS = { :style => 'z-index: 0;',:width => '290', :height => '200', :frameborder => '0', :url_params => {:wmode=>"opaque"} } def campaign_header_body(camp, opt = IGIVEMORE_HTML5_OPTIOINS) if camp.header_type == Campaign::HEADER_YOUTUBE youtube_html5(camp.header_url, opt).html_safe elsif camp.header_type == Campaign::HEADER_IMAGE "<img src=\"#{camp.header_url}\" width=\"#{opt[:width]}\" height=\"#{opt[:height]}\"/>'".html_safe else "Unsupported Type!!" end end def youtube_html5(url, opt) begin video = YouTubeIt::Client.new.video_by(url) video.embed_html5(opt).gsub(/http:\/\//,"https://") rescue => e "<div style='color:red; width:290px; height:100px; padding-top:100px'>Given Video URL has problem.</div>" end end end

    Read the article

< Previous Page | 1 2 3 4