I have some translations now that are paragraphs of text which quickly become tedious to manage as single JSON strings:
{
"a": {
"b": "This is a really long translated value I have here..."
}
}
I think ideally I would like to be able to represent the values differently and then transform them. For example as an array of strings that would be concatenated together:
{
"a": {
"b": [
"This is a really long ",
"translated value ",
"I have here..."
]
}
}
Does angular-translate have the appropriate hooks to achieve this?? And if so, what is the best approach?
Related
Forgive all my comments, I'm learning and that keeps me straight. Looking for a better solution to my conditional statement near the bottom and provided the rest for context. Tried out the loop comment suggested, but still not getting the right result as written here
// define the main package file
package main
//importing formatting features for the user I/O and string manipulation packages
//Parenthesis not needed if only importing 1 package
import (
"fmt"
"strings"
)
// defining the main function of the standalone app
func main() {
//initializing a string array
options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
//creating a slice in the array to designate favorites
favFruits := options[0:3]
fmt.Println(options)
//initializing variable for user input
var fruit string
fmt.Print("Favorite Fruit Not Listed: ")
fmt.Scan(&fruit)
//convert response to lowercase
fruitConv := strings.ToLower(fruit)
//conditional statement example
for _, pick := range options {
if pick == fruitConv {
fmt.Println("You were supposed to pick something else")
break
} else {
fmt.Println("Response Accepted!")
break
}
break
}
//adding user inputed favorite fruit to the sliced array
favFruits = append(favFruits, fruitConv)
fmt.Print(favFruits)
}
I got your point. If you go to official Go packages section you will get slices package over there. Ref: slices
There is one function named contains inside the slices package, you can make use of that function. For your simplicity, I have created one example matching with your scenario.
func main() {
//initializing a string array
options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
// assuming fruit as user input
fruit := "lemon"
//conditional statement example
if fruit == "coconut" || fruit == "coconuts" {
fmt.Println("Coconuts are nasty (except on your hair/skin)")
//**there has to be a way to simplify this code if the array grows server-side or something**
} else if slices.Contains(options, fruit) {
fmt.Println("You were supposed to pick something different...")
}
}
Here is the working link :- https://goplay.tools/snippet/bzSm_biR4Vr
Note: Since in your scenario there is lot of such contain checks, I would recommend to use map instead of slice. Internally if you deep dive in conatins function of slice you will get to know.
I am quite new to coding, so simple tasks seems like the mount Everest. I have created a Switch statement for a player to choose 3 out of 4 characters to play with. I' d like him/her to name their characters uniquely.
I tried by adding a "parameter [String]" to the method and inside it, adding each characters name, using a "for Loop" to check if a character has already be named this way.
The thing is that I keep looping and can' t sort out how to name each character uniquely.
If someone has any clue, thanks to answer.
func makeTheTeam(listOfName: [String]) {
var listOfName = listOfName
// Presents all the fighter available
gameAction.charactersPresentation()
while listOfFighters.count < 3 {
print("\nInput a number associated to select a fighter:")
if let userChoice = readLine() {
print("Name your fighter:")
if let nameChoice = readLine() {
switch userChoice {
case "1":
listOfFighters.append(Warrior(fighterName: "\(nameChoice)"))
case "2":
listOfFighters.append(Wizard(fighterName: "\(nameChoice)"))
case "3":
listOfFighters.append(Colossus(fighterName: "\(nameChoice)"))
case "4":
listOfFighters.append(Dwarf(fighterName: "\(nameChoice)"))
default:
print("You have not chosen three characters to enter the ring!! \n\nEnter a number associated to a fighter...")
}
}
}
}
}
For getting rid of the "unique" names issue, you could:
1- Get the benefit of using Sets, by converting listOfName to a set and check the counts:
if Set(listOfName).count == listOfName.count {
// unique names, we are good to go
} else {
// similar names...
}
OR
2- if your desired behavior is to check the array sequentially after adding each element, you could use contains. As an example of the basic usage for it:
var names = [String]()
var inputName = "Jack"
// will append "Jack"
if names.contains(inputName) {
// name is already exist
} else {
names.append(inputName)
}
inputName = "Smith"
// will append "Smith"
if names.contains(inputName) {
// name is already exist
} else {
names.append(inputName)
}
inputName = "Smith"
// will NOT append "Jack"
if names.contains(inputName) {
// name is already exist
} else {
names.append(inputName)
}
Tip:
If makeTheTeam function should receive an unspecific number of strings, I would suggest to declare it as variadic:
func makeTheTeam(listOfName: String...) { // ...
I can't figure out how to build a structure for this json object in golang:
{
"response": [1702487, {
"uid": 150261846,
"first_name": "Олег",
"last_name": "Брейн"
}, {
"uid": 53260546,
"first_name": "Олег",
"last_name": "Лобацевич"
}
]
}
As you can see there is no keys names for array and for count too.
Would be glad if you can help
In this situation you'll have to punt and use interface{} somewhere, for example:
package main
import (
"fmt"
"encoding/json"
)
type JsObject struct {
Response []interface{}
}
func main() {
bs := []byte(`{"response":[1702487,{"uid":150261846,"first_name":"Олег","last_name":"Брейн"},{"uid":53260546,"first_name":"Олег","last_name":"Лобацевич"}]}`)
var jso JsObject
json.Unmarshal(bs, &jso)
fmt.Printf("%+v\n", jso)
}
Json to go is quite handy for this sort of thing:
https://mholt.github.io/json-to-go/
If you can remove the spurious 1702487 which makes this a heterogenous list, you should be able to parse it easily into a proper structure, otherwise you might be stuck using interface:
https://play.golang.org/p/w7ebLTuOj9
Presumably you want an array of structs like this:
type Person struct {
UID int `json:"uid"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
not sure what 1702487 is but if uid of request, it doesn't really belong in the array.
type AutoGenerated struct {
Response []interface{} `json:"response"`
}
Currently I do something like this:
Observable.just([1, 2, 3, 4])
.flatMapLatest {
numbers in
guard number = numbers.first else {
return Objservable.empty()
}
return Observable.just(number)
}
Is there a more idiomatic way to do this or any prebuilt operators I can use?
The way you implemented it is absolutely correct. I'd simply have used flatMap in place of flatMapLatest as it is a more general operator and we don't need the special logic of flatMapLatest.
You could create your own operator that applies to observables that are of type Collection.
extension Observable where Element : Collection {
func mapFirst() -> Observable<Element.Iterator.Element> {
return self.flatMap { elements in
guard number = numbers.first else {
return Objservable.empty()
}
return Observable.just(number)
}
}
}
Your solution is quite good, you can eg. move it into extension and it'll be more general.
But if you really want to do this other way: you can take a look at RxOptionals and use it like:
Observable.just([1, 2, 3, 4])
.filterEmpty()
.map { $0.first }
.filterNil()
I read: Swap the values in a MongoDB array
And tried to use that but it didn't work for the example I have so will ask if I missed anything or if I need a different approach.
I have a DB with objects that looks something like this:
{
"_id": ObjectId("5448ec9c97086e180c239346"),
"cfg": {
"children": {
"0": ObjectId("5448ecb2d9f98f3c1746f5ba"),
"1": ObjectId("5448ecb2d9f98f3c1746f5bf"),
"2": ObjectId("5448ecb2d9f98f3c1746f5bb"),
"3": ObjectId("5448ecb2d9f98f3c1746f5c0"),
"4": ObjectId("5448ecb2d9f98f3c1746f5bc"),
"5": ObjectId("5448ecb2d9f98f3c1746f5c1"),
"6": ObjectId("5448ecb2d9f98f3c1746f5bd"),
"7": ObjectId("5448ecb2d9f98f3c1746f5c2"),
"8": ObjectId("5448ecb2d9f98f3c1746f5be"),
"9": ObjectId("5448ecb2d9f98f3c1746f5c3")
}
}
}
It also has the objects listen here in the "children" list.
This is supposed to be a ordered list, so if I want to move index 6 up to index 4, i also have to move 5 down to 6 and 4 down to 5.
The way that I handled this is to try and use the swap suggested in the link I had in the start and then run that recursive.
I don't want to paste to much code here but basiclly what I do is:
function swapChilds(index, i, parent, steps, self,callback){
if (i >= steps + 1)
return callback(null);
// Genereate swap
self.collection.update({_id: parent.meta.parentObjectID},{$set: swap}, function(err){
if (err){
console.log('errSwap:' + err);
return callback(err);
}
swapChilds(index,i + 1, parent, steps, self,callback);
});
}
So this uses index and i to get a correct swaping going and then just calls itself until it has been called steps amout of times (i start with i = 1)
When tying this I was also using console.log(swap) just to see that it looks good, and it does, it looks something like:
{ 'cfg.children.6': 5448ecb2d9f98f3c1746f5c1,
'cfg.children.5': 5448ecb2d9f98f3c1746f5bd }
{ 'cfg.children.5': 5448ecb2d9f98f3c1746f5bc,
'cfg.children.4': 5448ecb2d9f98f3c1746f5c1 }
There are 2 problems, the first is that that last row there should be 'cfg.children.4': 5448ecb2d9f98f3c1746f5bd (notice the last two letters) since this "bd" is the one that should get moved up to position 4. I realize why this happens, it's since I don't get a new version of the parent, so it will use the old list (will fix and test if it makes any difference).
Now despite this error the code does nothing, when I check in the db after running this set, nothing has changed.
I don't understand where the problem is. Am I doing something very wrong here?
Does it have something todo with ObjectID? I've tried to just use the string, i've tried to make new ObjectID(correctValue) but it doesn't do anything at all.
How can I make multiple swaps to keep a list ordered?
I had messed up in the arguments was as simple as that.
If anyone is intressed in the fix the new code looks like:
function swapChilds(index, i, parent, steps, self,callback){
if (i >= steps + 1)
return callback(null);
// Genereate swapdata
self.collection.update({_id: parent._id},{$set: swap}, function(err){
if (err){
console.log('errSwap:' + err);
return callback(err);
}
self.getObjectById(parent._id, function(err,parent2) {
if (err){
console.log('errSwap2:' + err);
return callback(err);
}
swapChilds(index,i + 1, parent2, steps, self,callback);
});
});
}
I've added a call to get the updated parent so that it doesn't use old values after the first swap, I also change to parent._id instead of the wrong one I had before parent.meta.parentObjectId (I just wanted the current object not it's parent).