Rails: sending data to asana and getting a syntax error - ruby-on-rails

assign task to Asana
require "rubygems"
require "JSON"
require "net/https"
api_key = "1wPBetR9.6bhINO7xO9ypG6iP2aYU8hx"
workspace_id = "5386494137624"
assignee = "craig#theaerialistpress.com"
# set up HTTPS connection
uri = URI.parse("https://app.asana.com/api/1.0/tasks")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# set up the request
header = {
"Content-Type" => "application/json"
}
req = Net::HTTP::Post.new(uri.path, header)
req.basic_auth(api_key, '')
req.body = {
"data" => {
"workspace" => workspace_id,
"name" => "House Order: " + #order.name,
"assignee" => assignee,
"projects" => "35978729781365",
"notes" => "Name: " + #order.name +
"\nEmail: " + #order.email +
"\nEvent Date: " + #date.to_s +
"\nDesign: " + #order.design +
"\n\nPaper Color: " + #order.paper_color +
"\nFont #1: " + #order.font1 +
"\nFont #2: " + #order.font2 +
if #order.card_type1 != "none"
"\n\nCard #1: " + #order.card_type1 + "\nPaper Weight: " + #order.paper_weight1 + "\nQuantity: " + #order.quantity1 + "\nInk Color #1: " + #order.ink_color11 + "\nInk Color #2: " + #order.ink_color12 + "\nWording: " + #order.wording1 + "\nReturn Address Printing: " + #order.return_address1 + "\nGuest Address Printing: " + #order.guest_address1.to_s + "\nEnvelope Liners: " + #order.envelope_liners1
end
if #order.card_type2 != "none"
"\n\nCard #2: " + #order.card_type2 + "\nPaper Weight: " + #order.paper_weight2 + "\nQuantity: " + #order.quantity2 + "\nInk Color #2: " + #order.ink_color21 + "\nInk Color #2: " + #order.ink_color22 + "\nWording: " + #order.wording2 + "\nReturn Address Printing: " + #order.return_address2 + "\nGuest Address Printing: " + #order.guest_address2.to_s + "\nEnvelope Liners: " + #order.envelope_liners2
end
}
}.to_json()
# issue the request
res = http.start { |http| http.request(req) }
# output
body = JSON.parse(res.body)
if body['errors'] then
puts "Server returned an error: #{body['errors'][0]['message']}"
else
puts "Created task with id: #{body['data']['id']}"
end
I am getting a syntax error when I am using if statements inside the data I am sending to asana. I am very new at rails and not sure what I am doing wrong.
This is the error:
syntax error, unexpected keyword_if, expecting '}' if #order.card_type2 != "none" ^ /Users/craigrinde/Dropbox/top_secret/aerialist/app/controllers/orders_controller.rb:212: syntax error, unexpected '}', expecting keyword_end } ^

Related

print method in lua script/redis is not working

I am trying to execute the following script and getting the below error. Redis is running in docker
Exception in thread "main" org.redisson.client.RedisException: ERR
user_script:1: Script attempted to access nonexistent global variable
'print' script: 6f736423f082e141036b833d1f86b5a36a494611, on
#user_script:1..
I get the same error when I execute using redis CLI
127.0.0.1:6379> eval "print("Comparison is_made b/w minimum_value out of two is: ")" 0 (error) ERR user_script:1: Script attempted to
access nonexistent global variable 'print' script:
8598b7f0db450c711d3a9e73a296e331bd1ef945, on #user_script:1.
127.0.0.1:6379>
Java code. I am using Redison lib to connect to Redis and execute script.
String script = "local rate = redis.call('hget', KEYS[1], 'rate');"
+ "local interval = redis.call('hget', KEYS[1], 'interval');"
+ "local type = redis.call('hget', KEYS[1], 'type');"
+ "assert(rate ~= false and interval ~= false and type ~= false, 'RateLimiter is not initialized')"
+ "local valueName = KEYS[2];"
+ "local permitsName = KEYS[4];"
+ "if type == '1' then "
+ "valueName = KEYS[3];"
+ "permitsName = KEYS[5];"
+ "end;"
+"print(\"rate\"..rate) ;"
+"print(\"interval\"..interval) ;"
+"print(\"type\"..type); "
+ "assert(tonumber(rate) >= tonumber(ARGV[1]), 'Requested permits amount could not exceed defined rate'); "
+ "local currentValue = redis.call('get', valueName); "
+ "local res;"
+ "if currentValue ~= false then "
+ "local expiredValues = redis.call('zrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "local released = 0; "
+ "for i, v in ipairs(expiredValues) do "
+ "local random, permits = struct.unpack('Bc0I', v);"
+ "released = released + permits;"
+ "end; "
+ "if released > 0 then "
+ "redis.call('zremrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "if tonumber(currentValue) + released > tonumber(rate) then "
+ "currentValue = tonumber(rate) - redis.call('zcard', permitsName); "
+ "else "
+ "currentValue = tonumber(currentValue) + released; "
+ "end; "
+ "redis.call('set', valueName, currentValue);"
+ "end;"
+ "if tonumber(currentValue) < tonumber(ARGV[1]) then "
+ "local firstValue = redis.call('zrange', permitsName, 0, 0, 'withscores'); "
+ "res = 3 + interval - (tonumber(ARGV[2]) - tonumber(firstValue[2]));"
+ "else "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end; "
+ "else "
+ "redis.call('set', valueName, rate); "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end;"
+ "local ttl = redis.call('pttl', KEYS[1]); "
+ "if ttl > 0 then "
+ "redis.call('pexpire', valueName, ttl); "
+ "redis.call('pexpire', permitsName, ttl); "
+ "end; "
+ "return res;";
RedissonClient client = null;
try {
client = Redisson.create();
client.getRateLimiter("user1:endpoint1").setRate(
RateType.PER_CLIENT, 5, 1, RateIntervalUnit.SECONDS);
String sha1 = client.getScript().scriptLoad(script);
List<Object> keys =
Arrays.asList("user1:endpoint1", "{user1:endpoint1}:value",
"{user1:endpoint1}:value:febbb04d-6365-4cb8-b32b-8d90800cd4e6",
"{user1:endpoint1}:permits", "{user1:endpoint1}:permits:febbb04d-6365-4cb8-b32b-8d90800cd4e6");
byte[] random = new byte[8];
ThreadLocalRandom.current().nextBytes(random);
Object args[] = {1, System.currentTimeMillis(), random};
boolean res = client.getScript().evalSha(READ_WRITE, sha1, RScript.ReturnType.BOOLEAN, keys, 1,
System.currentTimeMillis(), random);
System.out.println(res);
}finally {
if(client != null && !client.isShutdown()){
client.shutdown();
}
}
checked the Lua print on the same line thread but io.write also is giving same error.
As in the comments wrote return() seems* the only way.
Example for redis-cli (set redis DB and use it in Lua)
(Collect Data and return as one string)
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. " | " end return(txt)'
Now the eval
eval "local f = redis.call('GET', KEYS[1]) return(loadstring(f))()" 1 LuaV
...shows whats in table: redis
(One long String no \n possible)
Exception: eval 'redis.log(2, _VERSION)' 0 gives out without ending the script but only on the server.
Than \n will work when you do...
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. "\n" end return(txt)'
...and the eval
eval 'local f = redis.call("GET", KEYS[1]) f = loadstring(f)() redis.log(2, f)' 1 LuaV

Extract REST API request json value to variable in RestAssured

We have to validate the value sent in our REST API request payload with Response value, Tried the below and was able to get the JSON array printed. How to get the specific object inside the array of the request JSON body.
Request Payload :
{
"Testinfo":{
"abc":2,
"xyz":"2020-01-01"
},
"Details":{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws"
}
}
}
Code :
jsonObject = (JSONObject) JSONValue.parse(request);
JSONObject Testinfo = (JSONObject) jsonObject.get("Testinfo");
JSONObject Details = (JSONObject) jsonObject.get("Details");
System.err.println("Testinfo value in the request is: " + Testinfo);
System.err.println("Details value in the request is: " + Details);
Output :
{
"abc":2,
"xyz":"2020-01-01"
},
{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws",
}
How to get specific value such as "Details.eductation.test3"
Tried below
JSONArray jsonArray = (JSONArray) JSONValue.parse(request)
but getting an error as :
java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to net.minidev.json.JSONArray
Please guide.
Use JSONPath
String json = "{\r\n" + " \"Testinfo\": {\r\n" + " \"abc\": 2,\r\n"
+ " \"xyz\": \"2020-01-01\"\r\n" + "\r\n" + "\r\n" + " },\r\n" + "\r\n" + " \"Details\": {\r\n"
+ " \"eductation\": {\r\n" + " \"test1\": 9,\r\n" + " \"test2\": 100,\r\n"
+ " \"test3\": 50\r\n" + " },\r\n" + " \"neweductiona\": {\r\n"
+ " \"test1\": \"value\",\r\n" + " \"test2\": \"Draws\",\r\n"
+ " \"test3\": 50\r\n" + "\r\n" + " }\r\n" + " }\r\n" + "}";
JsonPath js = new JsonPath(json);
System.out.println("Value is : "+js.getString("Details.eductation.test3"));
Output :
Value is : 50

ERR value is not an integer or out of range

I have this code in a lua script which I run from .net.
const string script = " if redis.call('EXISTS', '{0}') == 1 then" +
" local user = redis.call('get','{0}')" +
" local value = cjson.decode(user)" +
" value['UserPreferences'] = cjson.decode('{1}')" +
" value['Timestamp'] = cjson.decode('{2}')" +
" local val=cjson.encode(value)" +
" redis.call('set', '{0}', val)" +
" redis.call('EXPIRE', '{0}','{3}')" +
" end";
var redisScript = string.Format(script, "User_" + userId, JsonConvert.SerializeObject(userPreferences), JsonConvert.SerializeObject(DateTime.UtcNow), ConfigurationManager.AppSettings["RedisKeyExpiryTime"]);
await Cache.ScriptEvaluateAsync(redisScript);
This returns the error :
Error: ERR value is not an integer or out of range
please give some feedback to solve the issue.

Google Adwords Reporting HTTP POST request returns 400 response code

I am trying to use Google Adwords Reporting HTTP POST request to retrieve stats for a list of keywords that could exist under multiple Campaigns/Adgroups. This is the API documentation that I was referring to https://developers.google.com/adwords/api/docs/guides/reporting#prepare-the-http-post-request.
Below is scala code that returns 400 error code. What am I doing wrong ? Or is there another way of retrieving data from KEYWORDS_PERFORMANCE_REPORT report type ?
val httpClient = new DefaultHttpClient()
val postRequest=new HttpPost("https://adwords.google.com/api/adwords/reportdownload/v201605")
postRequest.addHeader("Host","adwords.google.com")
postRequest.addHeader("User-Agent", "curl, gzip")
postRequest.addHeader("Accept","*/*")
postRequest.addHeader("Expect","100-continue")
postRequest.addHeader("Accept-Encoding","gzip")
postRequest.addHeader("Content-Type","multipart/form-data; boundary=------------------------12d01fae60c7b559; charset=utf-8")
postRequest.addHeader("Authorization","Bearer 1/*************************************")
postRequest.addHeader("developerToken","/*************************************")")
postRequest.addHeader("clientCustomerId","/*************************************")")
postRequest.addHeader("Parameters","__rdxml: <?xml version=\"1.0\" " +
"encoding=\"UTF-8\"?>" +
"<reportDefinition>" +
" <selector>" +
" <fields>CampaignId</fields>" +
" <fields>AdGroupId</fields>" +
" <fields>Id</fields>" +
" <fields>Criteria</fields>" +
" <fields>CriteriaType</fields>" +
" <fields>Impressions</fields>" +
" <fields>Clicks</fields>" +
" <fields>Cost</fields>" +
" <predicates>" +
" <field>Status</field>" +
" <operator>NOT_IN</operator>" +
" <values>PAUSED</values>" +
" </predicates>" +
" </selector>" +
" <reportName>Criteria performance report #56bd904878715</reportName>" +
" <reportType>CRITERIA_PERFORMANCE_REPORT</reportType>" +
" <dateRangeType>LAST_7_DAYS</dateRangeType>" +
" <downloadFormat>CSV</downloadFormat>" +
"</reportDefinition>")
val httpResponse=httpClient.execute(postRequest)
println(httpResponse.getStatusLine.toString)
Your report definition should go into the POST request's body encoded either as application/x-www-form-urlencoded or multipart/form-data—in your code you are adding it as a header called Parameters.

Twitter API link parser

I am having an issue and tried to do everything regarding this!! even HttpUtility.ParseQueryString won't help!
I am trying to parse twitter links coming from the API in the form of http://t.co/oEVQbihMWu. I need the fully resolved URL.
My code:
richTextBox1.Clear();
richTextBox1.Visible = true;
SearchOptions SO = new SearchOptions();
SO.GeoCode = richTextBox3.Text + "," + richTextBox2.Text + "mi";
TwitterResponse<TwitterSearchResultCollection> TweetSearchResult = TwitterSearch.Search(tokens, "#blogger", SO);
if (TweetSearchResult.Result != RequestResult.Success) richTextBox1.Text = "connection Error";
else
{
string a = null;
foreach (var tweet in TweetSearchResult.ResponseObject)
{
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, tweet.User.Website, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + tweet.User.Website + "\n" + tweet.Text + "\n\n\n");
}
links being represented by tweet.user.website.
any help? :)
In the API response, there is entities.urls which contains an array of url and expanded_url mappings. Check your library's documentation for equivalent.
Alternatively, if you inspect the response for t.co links, you will find this:
<noscript><META http-equiv="refresh" content="0;URL=http://www.fitnessbydanielle.com"></noscript><title>http://www.fitnessbydanielle.com</title><script>window.opener = null; location.replace("http:\/\/www.fitnessbydanielle.com")</script>
Parse it to get the url.
I managed to crack it.
What I did:
foreach (var tweet in TweetSearchResult.ResponseObject)
{
if(tweet.User.Website != null)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tweet.User.Website);
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, realUrl, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + realUrl + "\n" + tweet.Text + "\n\n\n");
}
}
File.AppendAllText(#".\BloggerTable.csv", a, Encoding.UTF8);
}
Wrapped it inside a condition so no users without website will show and used a webrequest to get the link. stored the location inside the httprequest header for each and every tweet.

Resources