I get the following struct return from disqus.com API and I just don't know how to retrieve only the following "id" value in red using Coldfusion.
This is the full array returned.
{
"cursor":{
"prev":null,
"hasNext":false,
"next":"1213061503000000:1:0",
"hasPrev":false,
"total":null,
"id":"1213061503000000:1:0",
"more":false
},
"code":0,
"response":[
{
"category":"1",
"reactions":0,
"identifiers":[],
"forum":"bobross",
"title":"Donkeys live a long time",
"dislikes":0,
"isDeleted":false,
"author":"1",
"userScore":0,
"id":"2",
"isClosed":false,
"posts":0,
"link":null,
"likes":0,
"message":"\"Donkeys live a long time. None of you have ever seen a dead donkey.\"",
"ipAddress":"127.0.0.1",
"slug":"donkeys_live_a_long_time",
"createdAt":"2008-06-10T02:31:43"
},
{
"category":"1",
"reactions":0,
"identifiers":[
"my-identifier"
],
"forum":"bobross",
"title":"Happy Accidents",
"dislikes":0,
"isDeleted":false,
"author":"1",
"userScore":0,
"id":"1",
"isClosed":false,
"posts":76,
"link":null,
"likes":0,
"message":"\"If you've painted before you know that we don't make mistakes -- we have happy accidents.\"",
"ipAddress":"127.0.0.1",
"slug":"happy_accidents",
"createdAt":"2008-06-10T01:31:43"
}
]
}
Well: firstly, that's a JSON packet not an array, so you need to turn it into a CFML data structure by deserialising it, eg:
data = deserializeJson(jsonPacket);
Then you'll have a native CFML struct (not an array... the array is one of the values within the struct).
From there, you would access any given element the way one normally would with a CFML struct, using struct / array notation, or struct functions / etc.
To directly address the item you point out, it would be (given the code above has been run first):
data.response[1].id
However I suspect you don't really want to address just that one value? But without more detail as to what you're trying to do, it's difficult to answer other than exactly what you want.
If you wanted to get all the IDs, one could do this:
ids = [];
for (singleResponse in data.response){
arrayAppend(ids, singleResponse.id);
}
Or on ColdFusion 10 there's more options with how to iterate over arrays.
Again: clarify what you're trying to do, and we can help you do it.
Related
I have to display some sentences on a screen.
However, the language can change if the user want to, so I do not want but I can do that :
if(language==1)
{
printf("Hello sir");
}
else if(language==2)
{
printf("Hola senor");
}
OR
printf("%s",language == 1 ? "Hello sir" : "Hola senor");
I do not want that because I have a lot of iterations.
Can I use map or enum and change it during code is running, I was thinking about a things like that :
#define MESSAGE_HELLO "Hello sir" OR "Hola senor"
printf("%s",MESSAGE_HELLO);
Do you have an idea ? Can you help me please ?
You can use some internationalization library that might help you. But here I will focus on how one can solve such a problem. Naturally, you need to have a set of languages, a set of message keys and a relationship between message keys and the languages, which would hold the actual message. Let's see some solutions:
Language file
You can store english.txt, etc. which would look like this:
hello_world="Hello World"
goodbye="Good bye"
and some other language, hungarian.txt for example:
hello_world="Heló Világ"
goodbye="Viszontlátásra"
etc.
Now, you can create an array of Map<String, Map<String, String>>, loop the languages, for each language process the corresponding file and fill the map accordingly.
Database
You can store a languages table, a message_keys table and a messages table. The messages table would have a foreign key pointing to languages and another one to message_keys and the actual message would be stored there as well. You could have an API that you could use in order to request items or groups of messages in a certain language.
There are many possible solutions.
In the professional world, I have often used tables (arrays) of phrases. Each slot in the array represents the phrase in another language.
static const char str_hello[] =
{
/* English */ "hello",
/* Spanish */ "hola",
/* German */ "guten tag",
//...
};
This has worked well in embedded systems.
You probably can create two maps for the sentences you want to translate - one map for one language - and then create a pointer to one of the maps. Then use pointer and [] to take sentences you need. Also, the pointer can be changed so that it points to another map at any moment.
Finally, I found a solution that fits with my requirements.
I use a .json file with all sentences and the languages I use.
{
"my-encoding": "UTF-8",
"messages": [
{
"MESS_HELLO": {
"english": "Hello",
"spanish": "Hola"
}
},
{
"MESS_GOODBYE": {
"english": "Bye",
"spanish": "Adios"
}
},
.......
]
}
To use .json file in C++, I included json-c lib in my project.
After loading the json file, I put it in a
std::unordered_map<std::string, std::unordered_map<std::string, std::string>> m_myTable;
With an ID declared in cpp (same as MESS_HELLO or MESS_GOODBYE).
It looks like that :
//"MESS_HELLO" -> { "english" -> "Hello" ; "spanish" -> "Hola" }
//"MESS_GOODBYE" -> { "english" -> "Bye" ; "other_language" -> "mess_in_other_language" ; +++ }
With that type I can do :
Easily add a new message by changing .json file + declaring in code a new ID
Modify the text by only change .json file
Add a new language by adding to .json file + adding several lines in code, but not a big deal.
To display it, I do something like
const auto &text_it = m_myTable.find("MESS_HELLO")
const auto &language_it = text_it->second.find("english");
printf("%s",language_it->second); //print Hello
Of course, it's in functions and well implemented, but I can't tell more about that.
This question already has answers here:
How to set and get fields in struct's method
(3 answers)
Assign a new value to a struct field
(2 answers)
Closed 5 years ago.
I'm playing with Go a bit but found this weird situation while doing some tests.
I'm using method in a struct to send a variable to another method that should change a field, but when I check it at the end, the field goes back to the first value, which has me confused.
func (this TVManager) sendMessage(message string) {
fmt.Println("5", this.connector)
payload := map[string]string {
"id": "0",
"type": "request",
"uri": "ssap://system.notifications/createToast",
"payload": "{'message': 'This is a message'}"}
this.connector.sendCommand(payload)
fmt.Println("4", this.connector)
}
This is the method I'm testing, it calls sendCommand of connector.
func (this MockConnector) sendCommand(payload map[string]string) {
fmt.Println("0", this)
this.last_command = payload
this.value = true
fmt.Println("0", this)
}
Which in the mock object I'm using is simply changing the value of this struct fields.
manager.sendMessage("This is a message")
fmt.Println("1", connector)
assert.Equal(t, expected, connector.last_command, "Command should be equal")
But when I check it, it goes back to internal. I set some prints to try an d track the values and they change the values as expected, but then it reverts.
1 {false map[]}
5 {false map[]}
0 {false map[]}
0 {true map[uri:ssap://system.notifications/createToast payload:{'message': 'This is a message'} id:0 type:request]}
4 {false map[]}
1 {false map[]}
--- FAIL: TestTVManagerSendsNotificationDownToConnector (0.00s)
This is just a small program I'm going over to learn some Go, so I appreciate any help anybody could give me.
You are passing the structures by value. This works fine so long as you are not modifying the structure, but if you do modify it you are actually only modifying a copy. To make this work you need to use pointers to the structures you need to modify.
Instead of:
func (this MockConnector) sendCommand(payload map[string]string)
Use:
func (this *MockConnector) sendCommand(payload map[string]string)
Also, it is considered a bad idea to use this (or self) as a receiver name in Go, as a receiver is not the same thing as a this pointer/reference in other languages.
Another best practice, is if one method for a given type needs a pointer receiver, all methods for that type should have pointer receivers. This is so that the method set remains consistent no matter if the value is a pointer or not.
See method sets, and these FAQ answers for more information.
I am using REST-API for testing
I am stuck where I am checking the response with some specific string.
please refer below info
I got the response from a request is
{
"clusters":[
{
"id":10,
"name":"HP2",
"status":2,
"statusDisplay":"HParihar#4info.com",
"lastModifiedBy":"HParihar#4info.com",
"lastModifiedTime":"06/08/2017 23:42",
"sitesAppsCount":0
},
{
"id":799,
"name":"Regression_cluster_111_09",
"status":2,
"statusDisplay":"admin#4info.net",
"lastModifiedBy":"admin#4info.net",
"lastModifiedTime":"07/11/2017 08:19",
"sitesAppsCount":0
}
]}
and I wanted to match just
"name":"Regression_cluster_111_09",
"status":2,
"statusDisplay":"admin#4info.net",
"sitesAppsCount":0
right side values I'll be keeping as hard coded.
any guesses?
Since you are only checking those 4 parameters are in response or not.
Do no use regex for this.
Use jsonObject's find key/value feature.
Check whether the values to the keys are there.
If key/value is null, the parameter is not in response.
I got my answer
I used the following regex
"name":"Regression_cluster_111_09","status":2,"statusDisplay":"admin#4info.net","lastModifiedBy":"[a-z]+#[0-9a-z]+\.[a-z]+","lastModifiedTime":"[0-9]{2}\/[0-9]{2}\/[0-9]{4}\ [0-9]{2}:[0-9]{2}","sitesAppsCount":0
or I can simply use
"name":"Regression_cluster_111_09","status":2,"statusDisplay":"admin#4info.net",.+"sitesAppsCount":0
thank you all
I'm playing around with peekAll(), trying to understand how it works for the ultimate purpose of iterating through the results.
In a route's model hook, I have:
var peekAllResults = this.store.peekAll('position');
console.log("peekAllResults = ", peekAllResults);
var peekAllResultsContent = peekAllResults.get('content');
console.log("peekAlLresultsContent = ", peekAllResultsContent);
This is returning data, as expected based on what I've got in my app.
In particular, here's what shows in the console:
So far so good. There are 8 records as expected based on what I've got going on.
But when when I add:
console.log("peekAllResultsContent.length=", peekAllResultsContent.length)
I get: peekAllResultsContent.length = 0
Same thing if I do peekAllResultsContent.get("length")
What is going on there?
I thought peekAll was a synchronous call that returned an array. Is there some trick to cracking it open and seeing what's actually in the array? I can't even get the length, so I figure I'm not on the right track.
Everything is wrapped into Ember.Model objects so you won't see clear results from console.log.
But there is no magic behind it. If the entities are already loaded into store you can get them via peekAll.
const positions = this.get('store').peekAll('position');
console.log('positions length', positions.get('length');
//we can iterate over them:
positions.forEach(position => {
console.log(position.get('name'));
};
//we can filter them:
const southOnlyPositions = positions.filter(position => position.get('direction') === 'south');
and so on...
Btw: even for promises you are not supposed to access content. You get the result like this:
const promises = this.get('store').findAll('position');
promises.then(positions => {
// positions here behave same as before
});
In JavaScript, one can remove selected elements from an array by traversing it in reverse order and using splice(index, 1) to remove undesired elements. I'm trying to figure out how to do the same thing in Ember.js (without Ember Data).
I have an ArrayController and the associated Route's model function simply returns a JavaScript array. There an action in the controller, along the following lines:
removeElements: function () {
var i, arr = this.get('content'),
i = arr.length;
while (i) {
i -= 1;
if (arr[i].get('flag')) {
array.replace(i, 1);
}
}
This first appears to work in the browser. For example, if I have three elements and mark the first and third to be removed, the browser will leave the second item displayed. However, if I later try to mark the latter, Ember complains with Uncaught Error: Can't remove an item that has never been added.
I used replace() because Ember arrays don't have a splice method, but the docs also say that replace must be implemented in order to be used, but I don't quite understand where I'm supposed to implement it and I haven't found any sample implementations to guide me.
I've also tried various other methods, such as removeObject, removeObjects and more, but none did what I need.
You'd need to create your own array collection and implement replace on that collection (probably extending Ember.Array to get you started).
removeObject should work just fine (granted a little inefficient, though if the size of this list is small it's negligible):
removeElements: function () {
var controller = this,
list = this.toArray();
list.forEach(function(item){
if(item.get('flag')){
controller.removeObject(item);
}
});
}
using removeAt should give you the results you're looking for
removeElements: function () {
var i = this.get('length');
while (i--) {
if (this.objectAt(i).get('flag')) {
this.removeAt(i);
}
}
}