how can i get csv in google appsscript? - csv

function myFunction() {
var gen_otp_url = 'http://data.krx.co.kr/comm/fileDn/GenerateOTP/generate.cmd'
// #otp payload
var gen_otp_data = {'locale' : 'ko_KR',
'mktId' : 'STK',
'trdDd' : '20221205',
'money' : '1',
'csvxls_isNo' : 'false',
'name' : 'fileDown',
'url' : 'dbms/MDC/STAT/standard/MDCSTAT03901'};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : gen_otp_data};
var otp = UrlFetchApp.fetch(gen_otp_url, options);
Logger.log(otp.getContentText())
var csv_url = 'http://data.krx.co.kr/comm/fileDn/download_csv/download.cmd'
var gen_csv_data = {'code' : otp };
var csv_options = {
'method' : 'post',
'contentType': 'application/json',
'muteHttpExceptions': true,
'payload' : gen_csv_data};
var csv = UrlFetchApp.fetch(csv_url, csv_options);
Logger.log(csv.getContentText());
}
I want to load the csv log with this..
Logger.log(csv.getContentText());
When I did the same code on Python, it was a byte code, so I decoded it, but it didn't work on appsscript...
i tried this. it doesn't work...
function to64(arr) {
var bytes = [];
for (var i = 0; i < arr.length; i++)
bytes.push(arr[i]<128?arr[i]:arr[i]-256);
return Utilities.base64EncodeWebSafe(bytes)
} // to64

function myFunction() {
var gen_otp_url = 'http://data.krx.co.kr/comm/fileDn/GenerateOTP/generate.cmd'
// #otp payload
var gen_otp_data = {'locale' : 'ko_KR',
'mktId' : 'STK',
'trdDd' : '20221205',
'money' : '1',
'csvxls_isNo' : 'false',
'name' : 'fileDown',
'url' : 'dbms/MDC/STAT/standard/MDCSTAT03901'};
var options = {
'method' : 'post',
'payload' : gen_otp_data};
var otp = UrlFetchApp.fetch(gen_otp_url, options);
Logger.log(otp.getContentText())
var csv_url = 'http://data.krx.co.kr/comm/fileDn/download_csv/download.cmd'
var gen_csv_data = {'code' : otp.getContentText() };
var csv_options = {
'method' : 'post',
'muteHttpExceptions': true,
'payload' : gen_csv_data};
var csv = UrlFetchApp.fetch(csv_url, csv_options);
Logger.log(csv.getContentText("cp949"))
}
I removed this, 'contentType': 'application/json',

I want to get this..
AqADUIYgYA1S7YNpohdEFcDGdj9Dk3U4+1LksLL0tDQRtSksuLS7Bnxpl86F7dAOkunw9BBwugQaSjGAcH15eTgGZqZmUYRxtFW2OJYnOsQtBgM+EFJCxYg3zco1gIgRZqIo4cIzoURnTI8+MmkJ4v/rk8yudrOQ53ef0cNipdpCT2QuimcLoNhc1Lfcxcp2zXt/wiFT3lY4zZLV84P+nFYo9mrWvGCVTr7yVbjg2wtc9glyj0xDQ2lZrfrchZWN
but i get this.. from Logger.log(otp.getContentText())
AqADUIYgYA1S7YNpohdEFUP2/gB8rhRtkSnlEoAJIio=
Logger.log(Utilities.base64EncodeWebSafe(otp.getContent()))
QXFBRFVJWWdZQTFTN1lOcG9oZEVGUlk5SHIzUDJBUVJKMDYvMnNmQTEvOD0=

Related

FinBox.com logging in with UrlFetchApp to access another link?

I can't log in successfully from Google Apps Script despite looking for solutions hours long, including many entries in SoF.
The login process sends a POST request to this url: https://finbox.com/_/api/v5/tokens
Input of the credentials happens here: https://finbox.com/login/email
Response code is 400.
Any help will be really appreciated :)
So far I ended up with this:
function testFinBoxWithCredentials(stock = "AAPL") {
var options = {
method: 'post',
contentType: 'application/json',
payload: {
email: 'xxxxxxxxx',
password: 'xxxxxxxxx'
},
muteHttpExceptions: true,
followRedirects: false
};
const response = UrlFetchApp.fetch("https://finbox.com/_/api/v5/tokens", options);
Logger.log(response.getResponseCode());
if ( response.getResponseCode() == 200 ) {
Logger.log("Couldn't login.");
}
else if ( response.getResponseCode() == 302 ) {
Logger.log("Logged in successfully");
var cookie = response.getAllHeaders()['Set-Cookie'];
Logger.log(cookie);
//Access then a link like https://finbox.com/NASDAQGS:AAPL
/* var cookies = response.getAllHeaders()['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
url2 = "https://finbox.com/NASDAQGS:AAPL";
options2 = {
"method": "get",
"headers": {
"Cookie": cookies.join(';')
}
}
var response2 = UrlFetchApp.fetch(url2, options2);
var content = response2.getContentText();
Logger.log(content)*/
} ```

How to save to database by using ajax

I have a code which is works fine, but the data cannot save to the database. I want to insert cost, currency_rate, profit_rate and pprice to database through Ajax. Here are the code of javascript and update.php, I have tried to modify the code to save in my Mysql server, but it didn't success. Can someone help with this?
javascript
$(".profitRate").change(function() {
var myArray = [];
//find closest table->next table
var elem = $(this).closest('table').next('table');
var action = elem.find('tr').data('action');
console.log(action)
var profitRate = Number($("#profitRate").val());
//looping
elem.find('tr').each(function() {
//get cost
var cost = $(this).find('input[name=cost]').val();
//get curency rate
var currecy_rate = $(this).find('select[name=currency_rate]').val();
//calculate profit
var profit_total = Math.round(cost * profitRate * currecy_rate)
$(this).find('input[name=pprice]').val(profit_total)
//add to json object
auto_array = {};
auto_array["cost"] = cost;
auto_array["currecy_rate"] = currecy_rate;
auto_array["pprice"] = profit_total;
myArray.push(auto_array) //push to array
});
console.log(myArray)
form_data = elem.find('tr').data('action');
$.ajax({
data: {
action: action,
form_data: form_data,
},
url: 'update.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
}
}
});
})
update.php
<?php
if ($_POST['action'] == 'update_price') {
parse_str($_POST['form_data'], $my_form_data);
$id = $my_form_data['id'];
$cost = $my_form_data['cost'];
$profit_rate = $my_form_data['profit_rate'];
$currency_rate = $my_form_data['currency_rate'];
$pprice = $my_form_data['pprice'];
$sql = $query = $finalquery = $sqlresult = '';
if ($cost){
$sql.="cost='$cost',";
}
if ($profit_rate){
$sql.="profit_rate='$profit_rate',";
}
if ($currency_rate){
$sql.="currency_rate='$currency_rate',";
}
if ($pprice){
$sql.="pprice='$pprice',";
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
}

Invalid JSON payload received. Unable to parse number (Google Vision API)

I'm getting the error:
Invalid JSON payload received. Unable to parse number. INVALID_ARGUMENT
I got the key and everything and I'm still having the same error return. A few suggestions are resizing the image first to less fit the 4MB image limit.
I also tried emulating the same JSON request coming from their docs. But still have the same issue.
https://cloud.google.com/vision/docs/drag-and-drop
Here's the code I'm using: (I got the sample from Akshay Kadam)
me.detection_types = {
LABEL_DETECTION: 'label',
DOCUMENT_TEXT_DETECTION: 'text',
LOGO_DETECTION: 'logo',
LANDMARK_DETECTION: 'landmark'
};
var api_key = '';
$scope.takePicture = function(){
var options = {
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
targetWidth: 150,
targetHeight: 150,
correctOrientation: true,
cameraDirection: 0,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
quality: 25
};
$cordovaCamera.getPicture(options).then(function(imagedata){
me.current_image = "data:image/jpeg;base64," + imagedata;
me.image_description = '';
me.locale = '';
var vision_api_json = {
"requests":[
{
"image":{
"content": imagedata
},
"imageContext": {
"cropHintsParams": {
"aspectRatios": [
0.8,
1,
1.2
]
}
},
"features":[
{
"type": me.detection_type,
"maxResults": 1
}
]
}
]
}
var file_contents = JSON.stringify(vision_api_json);
$cordovaFile.writeFile(
cordova.file.applicationStorageDirectory,
'file.json',
file_contents,
true
).then(function(result){
var headers = {
'Content-Type': 'application/json'
};
options.headers = headers;
var server = 'https://vision.googleapis.com/v1/images:annotate?key=' + api_key;
var filePath = cordova.file.applicationStorageDirectory + 'file.json';
$cordovaFileTransfer.upload(server, filePath, options, true)
.then(function(result){
alert(JSON.stringify(result))
var res = JSON.parse(result.response);
var key = me.detection_types[me.detection_type] + 'Annotations';
me.image_description = res.responses[0][key][0].description;
}
Need help. Thank you!
UPDATE:
I tried adding Content-Length and was still having the same problem.

What is the error in this code?My data is not inserting into sql server

I have checked my api through postman and its working but the error is in the jquery or ajax.
I have tried to find error but cant understand.Please Try to solve this problem.Thankyou so much
$(document).ready(function () {
$("#AddPatientReport").click(function () {
alert("PatientReport Added Successfully");
var DoctorId = $("#ReportDoctorId").val();
var DoctorName = $("#ReportDoctorName").val();
var PatientName = $("#ReportPatientName").val();
var PatientId = $("#ReportPatientId").val();
var PharmacyCategory1 = $("#ReportPharmacyCategory1").val();
var Medicine1 = $("#ReportMedicine1").val();
var PharmacyCategory2 = $("#ReportPharmacyCategory2").val();
var Medicine2 = $("#ReportMedicine2").val();
var AppointmentDate = $("#ReportPatientDate").val();
var AppointmentTime = $("#ReportPatientTime").val();
var PatientDescription = $("#ReportPatientDescription").val();
$.ajax({
url: '/home/addpatientreport',
type: 'POST',
data: {
DoctorId: DoctorId,
DoctorName: DoctorName,
PatientName: PatientName,
PatientId: PatientId,
PharmacyCategory1: PharmacyCategory1,
Medicine1: Medicine1,
PharmacyCategory2: PharmacyCategory2,
Medicine2: Medicine2,
AppointmentDate: AppointmentDate,
AppointmentTime: AppointmentTime,
PatientDescription: PatientDescription
},
dataType: 'application/json; charset=utf-8',
contentType: "application/x-www-form-urlencoded"
});
});
});

Wordpress custom JSON feed with multiple categories

Good morning to all.
It is possible to have a custom JSON feed with the last 10 posts from all categories with 10 or more posts published?
I'm doing that with a loop over all categories with 10 or more posts published using the JSON API plugin for wordpress by dphiffer
So if I have 14 categories I will do 140 requests and overload the server.
I'm searching for a way to do that with 1 or 2 requests. Like first request to get the categories indexes with 10 or more posts and the second request with all the data.
Thanks
Here is the code i've developed so far:
<script type="text/javascript">
var slug = 'news'; // Main categorie
var maxLength = 10; // Total of articles per categorie
var wpurl = 'http://wpurl.com'; // WP URL
var loadedValue, loadedTotal;
var categories = new Array();
var newsData = new Array();
//Get main categorie index by slug
$.ajax({
url: wpurl+'/?json=get_category_index',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
if(cat.slug == slug) {
get_all_categories(cat.id);
}
}
},
error: function(data){
console.log(data);
}
});
//Get all sub-categories from an categorie slug
function get_all_categories(cat_index) {
$.ajax({
url: wpurl+'/?json=get_category_index&parent='+cat_index,
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (i = 0; i < data.categories.length; i++) {
var cat = data.categories[i];
//Check if categorie have 10 (maxLength) or more posts. If so push it to array (categories)
if(cat.post_count >= maxLength) {
categories.push({
'index': cat.id,
'title': cat.title
});
}
}
},
error: function(data){
console.log(data);
}
}).done(function() {
//Set loading
var totalItem = categories.length*maxLength;
var actualItem = 0;
var loaded = 0;
for(var i=1; i<=categories.length; i++){
prepareCategory(categories[i-1].index, maxLength, i);
function prepareCategory(categorieIndex, maxLenght, count) {
var content;
$.ajax({
url: wpurl+'/api/get_category_posts?category_id='+categorieIndex+'&count='+maxLenght+'&status=publish',
type: 'GET',
dataType: 'jsonp',
success: function(data){
for (e = 0; e < data.posts.length; e++) {
//Loading percent
actualItem++;
loaded = (actualItem/totalItem)*100;
document.getElementById('loadingBox').innerHTML = 'Loading: '+Math.round(loaded)+'%';
//Post data
var post = data.posts[e];
var title = post.title;
var thumb = post.thumbnail_images.appthumb.url || 'content/images/noimage.png';
var newContent = '<div class="new"><img src="'+thumb+'" width="320" height="164"><div class="new_description">'+title+'</div></div>';
var newId = 'cat'+count+'new'+(e+1);
newsData.push({
'id': newId,
'content':newContent
});
}
},
error: function(data){
console.log(data);
}
});
}
}
});
};
function loaded() {
if (window.localStorage.length != 0)
{
localStorage.clear();
setGlobalStorageAndRedirect();
} else {
setGlobalStorageAndRedirect();
}
function setGlobalStorageAndRedirect() {
localStorage.setItem('postPerCat', maxLength);
localStorage.setItem('catNumbs', categories.length);
localStorage.setItem('wpurl', wpurl);
localStorage.setItem('categoriesArray', JSON.stringify(categories));
localStorage.setItem('newsData', JSON.stringify(newsData));
window.location="main.html";
}
}
</script>