HOW TO: call stored procedures with Tds Library in Elixir - stored-procedures

I get the following error trying to call a stored procedure using the Tds library for Elixir
The stored procedure get_account exists and has exactly one parameter #id
iex(5)>Tds.Connection.query(pid, "get_account",[%Tds.Parameter{name: "#id", value: 1}])
{:error,
%Tds.Error{message: nil,
mssql: %{class: 16, length: 252, line_number: 0, msg_text: "Procedure or function 'get_account' expects parameter '#id', which was not supplied.", number: 201, proc_name: "get_account",
server_name: "localhost\\SQLEXPRESS", state: 4}}}
iex(6)>
Trying this with Tds.proc(pid, "get_account",[1]) does not work either

Workaround:
Tds.query(pid, "get_account 1",[])
Use this the same way you would pass parameters directly to a stored proc using EXEC.
Updated:
This format also works:
params = [
%Tds.Parameter{name: "#1", value: 100, type: :integer},
%Tds.Parameter{name: "#2", value: 100, type: :integer},
%Tds.Parameter{name: "#3", value: <<0 ,0 ,0 ,0>>, type: :binary},
]
Conn.query(s.db, "save_auth_key #1, #2, #3", params)

Related

How can I parse JSON with this structure(multipart file)?

My java spring boot app is sending JSON that includes a multi-part file, which I need to parse(using angular) in order to target 'picture" inside of "fileupload" when GET is called.
Here is the JSON coming to UI when GET is called:
{
"id": 1,
"name": John,
"fileupload": "MemberFile(id=1, fileId=1, fileName="sample.png", picture=[-119, 80, 78, 71, 13,..., -126])"
}
Any help would be greatly appreciated. Let me know if more details are needed. Thanks
Use JSON.parse to parse your string to javascript object.
const json = '{ "id": 1 "name": John "fileupload": "MemberFile(id=1, fileId=1, fileName="sample.png", picture=[-119, 80, 78, 71, 13,..., -126])" }';
const obj = JSON.parse(json);
console.log(obj);
// expected output: true

pdfMake create method Arguments are invalid

I had been successfully generating a pdf using pdfmake I am now getting this error and I'm not sure what has changed. Even the simple examples are throwing errors.
const docDefinition = {
content: [
{
layout: 'lightHorizontalLines', // optional
table: {
// headers are automatically repeated if the table spans over multiple pages
// you can declare how many rows should be treated as headers
headerRows: 1,
widths: ['*', 'auto', 100, '*'],
body: [
['First', 'Second', 'Third', 'The last one'],
['Value 1', 'Value 2', 'Value 3', 'Value 4'],
[{ text: 'Bold value', bold: true }, 'Val 2', 'Val 3', 'Val 4']
]
}
}
]
};
const pdfDocGenerator = pdfMake.createPdf(docDefinition);
Results in:
//Argument type {content: {layout: string, table: {headerRows: number,
widths: (string | number)[], body: (string[] | ({text: string, bold:
boolean} | string)[])[]}}[]} is not assignable to parameter type
TDocumentDefinitions
However, if I use:
const docDefinition = {
content: 'Hello World'
};
const pdfDocGenerator = pdfMake.createPdf(docDefinition);
All seems well. I don't quite understand how any of the examples in the playground are working at this point. Any suggestions are greatly appreciated!
For reasons that I am unable to explain, changing my import to this resolved my issue.
const pdfMake = require('pdfmake/build/pdfmake');
const pdfFonts = require('pdfmake/build/vfs_fonts');
I am including pdfMake.vfs = pdfFonts.pdfMake.vfs; further down in my page when I am actually building out the pdf.

Add element to a complex nested collection in swift

I'm stuck practicing collections in Swift. Actually, I storing data from an online JSON source into dictionaries/arrays. I'm trying to add a new element to the following collection:
testDict1: Dictionary<String,Dictionary<Int,Dictionary<String, AnyObject>>>
I initialized it with the following elements (it could have been an empty array):
testDict1 = ["fireMagic":[
0:["name":"Basic attack","damage":100],
1:["name":"Super attack","damage":200, "lvlReq": 20],
2:["name":"Mega attack","damage":400, "lvlReq": 40]]]
I would like to "update" data within testDict1 (replace and add a new row if needed) from another array such as:
testDict1 = ["fireMagic":[
0:["name":"Basic attack","damage":100],
1:["name":"Super attack","damage":200, "lvlReq": 20],
2:["name":"Mega attack","damage":400, "lvlReq": 40]
3:["name":"Insane attack","damage":1000, "lvlReq": 60]]]
QUESTION 1
How can I append the element below to testDict1:
3:["name":"Insane attack","damage":1000, "lvlReq": 60] //with "FireMagic" as a key.
I'm facing different errors and I can't make it work. I'm sure it must be more complex than the ways I tried and you may have the solution to end my pain :)
QUESTION 2
How do I do if I need to add other powers such as "WaterMagic" with the same structure as "FireMagic" in testDict1.
testDict1 = ["fireMagic":[
0:["name":"Basic attack","damage":100],
1:["...":"...","...":"..."]],
["waterMagic":[
0:["name":"Basic attack","damage":100]]
Thank you in advance for your help in my learning quest!
Q1:
Unsafe:
testDict1["fireMagic"]![3] = ["name":"Insane attack","damage":1000, "lvlReq": 60]
Safe:
if let _ = testDict1["fireMagic"] {
testDict1["fireMagic"]![3] = ["name":"Insane attack","damage":1000, "lvlReq": 60]
}
Safe and simple (thanks #dfri):
testDict1["fireMagic"]?[3] = ["name":"Insane attack","damage":1000, "lvlReq": 60]
Q2:
testDict1["waterMagic"] = [0:["name":"Test attack","damage":100]]
But I would suggest using arrays, enums and structs instead of dictionaries, it's much simpler to handle, and it's also more safe:
enum MagicType {
case Water
case Fire
}
struct Magic {
let magic: MagicType
let name: String
let damage: Int
let lvlReq: Int?
}
Create an array of objects:
var fireMagics = [Magic(magic: .Fire, name: "Basic attack", damage: 100, lvlReq: nil), Magic(magic: .Fire, name: "Super attack", damage: 200, lvlReq: 20), Magic(magic: .Fire, name: "Mega attack", damage: 100, lvlReq: 40)]
Access the objects in the array by index:
fireMagics[0]
fireMagics[1]
fireMagics[2]
etc.
Add an object to the array:
fireMagics.append(Magic(magic: .Fire, name: "Insane attack", damage: 1000, lvlReq: 60))
Create a different type of Magic object:
var waterMagics = [Magic(magic: .Water, name: "Test attack", damage: 100, lvlReq: nil)]

Highcharts not rendering data points

I'm pulling some data from a database that I'm trying to render into a Highcharts stock chart. The data is pulled from the database with PHP and passed to the chart with a $.get(..php/line-data.php) call, and the data retrieved is supposed to be the data that is rendered on the chart.
The data is being returned in the following manner, and I have verified this by logging data in the console. It appears as such, with the first value being the UNIX-to-Javascript converted date/time (x-axis), and the second being the value (y-axis):
[[1362639600000, 8],[1362726000000, 20],[1362985200000, 28],[1363071600000, 51],[1363158000000, 64],[1363244400000, 11],[1363330800000, 4],[1363503600000, 4],[1363590000000, 21],[1363676400000, 10],[1363762800000, 31],[1363849200000, 13],[1363935600000, 17],[1364194800000, 10],[1364454000000, 1],[1365058800000, 30],[1365145200000, 10],[1366009200000, 55],[1366182000000, 18],[1366268400000, 22],[1366354800000, 12]]
As an experiment, I tried just plugging this data straight into a basic demo Fiddle, and it seems to render fine.
FIDDLE HERE.
So what am I doing incorrectly? Everything seems to be set up correctly, but it's not rendering. This is what I see:
Here are the relevant portions of my code. Yes, I know that mysql_* is deprecated...I'll change it.
$.get('../php/line-data.php', function(data) {
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'total_mentions',
margin: [20, 10, 10, 10],
spacingTop: 0,
spacingBottom: 1,
spacingLeft: 0,
spacingRight: 0
},
series : [{
name : 'Total Mentions',
data: data,
type:'line',
lineWidth:1,
shadow:false,
states: {
hover: {
lineWidth:1
}
},
id : 'dataseries',
tooltip : {
valueDecimals: 4,
borderColor:'#DA7925',
borderRadius: 0,
borderWidth: 1,
shadow: false
},
color:'#DA7925',
fillOpacity:0.2
}]
[more options...etc.]
No problems with this code. It's pulling the correct data and echoing how I expect it to.
<?php
$expAddress = "URL";
$expUser = "USERNAME";
$expPwd = "PASSWORD";
$database = "DB";
$db = mysql_connect($expAddress, $expUser, $expPwd);
mysql_select_db($database, $db);
$ok = mysql_query("
SELECT
DATE(created_at) AS create_date,
COUNT(id) AS total
FROM
tweets
WHERE
subject LIKE 'word1'
OR
subject LIKE 'word2'
GROUP BY
DATE(created_at)");
if (!$ok) {
echo "<li>Mysql Error: ".mysql_error()."</li>";
}
else {
while($row = mysql_fetch_assoc($ok)){
extract($row);
$date = strtotime($create_date);
$date *= 1000;
$data[] = "[$date, $total]";
}
$tmp = join($data,',');
echo "[".$tmp."]";
}
?>
Have you tried parsing your data (string) into a javascript object before setting it to the series[i].data?
series : [{
data: JSON.parse(data)
}]
What you are getting from php through $.get is basically string and NOT a javascript array of array of numbers, which is what you want. It may look like that, but it is as simple as "5"!=5, but parseInt("5")==5 same is the case with json objects, you need to parse the string into such an object before javascript or highcharts can interpret it correctly, highcharts could do it on your behalf, but it is not designed that way.
Try his fiddle to get an idea of the data types in picture
var data="[[1362639600000, 8],[1362726000000, 20],[1362985200000, 28],[1363071600000, 51],[1363158000000, 64],[1363244400000, 11],[1363330800000, 4],[1363503600000, 4],[1363590000000, 21],[1363676400000, 10],[1363762800000, 31],[1363849200000, 13],[1363935600000, 17],[1364194800000, 10],[1364454000000, 1],[1365058800000, 30],[1365145200000, 10],[1366009200000, 55],[1366182000000, 18],[1366268400000, 22],[1366354800000, 12]]"
console.log(typeof data); //string
var parsedData=JSON.parse(data);
console.log(typeof parsedData); //object
console.log(typeof parsedData[0]); //object [1362639600000, 8]
console.log(typeof parsedData[0][0]); //number 1362639600000
When you paste the console value directly in the fiddle, you are actually pasting it as a valid javascript array, try using your console value wrapped by " quotes " and see that the exact issue is reproduced!!
Demo # jsFiddle
An alternate approach could be using the $.getJSON() method instead. jQuery does the parsing for you before it calls your callback method
Your problem is in either the output from the PHP script or when you receive the data in your Javascript (quite obvious).
First, don't do JSON by hand use json_encode (http://php.net/manual/en/function.json-encode.php). It's easier and it will guarantee that strings will be escaped properly.
Secondly, inspect your data variable with a debugger. You could also post the exact content of the variable to the question.
But basically, as long as it is working in the fiddle and not in your program you have not yet reproduced the error in your code properly in the fiddle.
For instance, you could replace data in your callback with the data you have in your fiddle to see if the code runs.

Cannot use AFNetworking to upload image

I am creating an iOS app using Rubymotion. I am trying to make a multipart upload
of an image.
I use this code to make upload but I get error:
data = {token: "2xCGdzcuEeNzhst3Yaa8f", task: 1, message: "message", latitude: 1, longitude: 1}
client = AFHTTPClient.alloc.initWithBaseURL(NSURL.URLWithString("http://api.example.com/api/v1/"))
request = client.multipartFormRequestWithMethod('POST', path:"messages", parameters:data, constructingBodyWithBlock:lambda{ |form_data|
image_data = UIImagePNGRepresentation(image.image)
form_data.appendPartWithFileData(image_data, name:'new_avatar', fileName:'new_avatar.png', mimeType:'image/png')
})
operation = AFJSONRequestOperation.alloc.initWithRequest(request)
operation.setCompletionBlockWithSuccess(lambda{ |operation, responseObject| puts 'all done!'})
I get this error:
undefined method `setCompletionBlockWithSuccess' for #<AFJSONRequestOperation:0xb227f00> (NoMethodError)
From what I can see, operation is a valid object and should have this method.
Am I missing something here?
Update 1
This is my updated code but when I run it the POST action does not seem to fire. Am I still missing any code? I do not get any errors either.
data = {token: "2xCGdzcuEeNzhs5tYaa8f", task: 1, message: "message", latitude: 1, longitude: 1}
client = AFHTTPClient.alloc.initWithBaseURL(NSURL.URLWithString("http://api.example.com/api/v1/"))
request = client.multipartFormRequestWithMethod('POST', path:"messages", parameters:data, constructingBodyWithBlock:lambda{ |form_data|
image_data = UIImagePNGRepresentation(image.image)
form_data.appendPartWithFileData(image_data, name:'new_avatar', fileName:'new_avatar.png', mimeType:'image/png')
})
operation = AFJSONRequestOperation.alloc.initWithRequest(request)
operation.setCompletionBlockWithSuccess(lambda { |operation, responseObject| puts 'all done!'},
failure: lambda { |operation, error| puts 'error' })
The request object outputs this:
<NSMutableURLRequest:195641792 - url: http://api.example.com/api/v1/messages,
headers: {"Content-Length"=>"118200", "Content-Type"=>"multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY", "Accept-Language"=>"en, fr, de, ja, nl, it, es, pt, pt-PT, da, fi, nb, sv, ko, zh-Hans, zh-Hant, ru, pl, tr, uk, ar, hr, cs, el, he, ro, sk, th, id, ms, en-GB, ca, hu, vi, en-us;q=0.8", "User-Agent"=>"theapp/1.0 (iPhone Simulator; iOS 6.0; Scale/1.00)"},
cache policy: 0, Pipelining: false, main doc url: , timeout: 60.0, network service type: 0 >
The operation object outputs this:
<AFJSONRequestOperation:0xa78c660>
The method signature is setCompletionBlockWithSuccess(lambda..., failure: lambda...) -- you need to add a failure parameter. Something like this:
operation.setCompletionBlockWithSuccess(lambda { |operation, responseObject| puts 'all done!'},
failure: lambda { |operation, error| puts 'error' })
Also, you'll want to make sure to actually start the request operation:
operation.start
See https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFJSONRequestOperation.m#L102-L103 for the definition of this method.
I wrote a class to do this kind of work. Check out my answer HERE. It uses AFNetworking and includes methods for basic network requests.

Resources