Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am Making a command line tool for sending an email where I am using urfave/cli package from golang
i had made the application where everything is working properly but got stuck with one string replacement part.
Basically, I want to convert a string
info#gmail.com,vik#hotmail.com,myemailid#yahoo.com
to
"info#gmail.com","vik#hotmail.com","myemailid#yahoo.com"
I tried regex substitution but that didn't give me an accurate result. so I manipulate my code where I used String.Split separated by ',' but after that the look around got complex. can anyone help me with this
To convert the value, simply run something like:
package main
import (
"fmt"
"strings"
)
func main() {
input := "info#gmail.com,vik#hotmail.com,myemailid#yahoo.com"
emails := strings.Join(Map(strings.Split(input, ","), func(in string) string {
return fmt.Sprintf(`"%s"`, in)
}), ",")
fmt.Printf("%v", emails)
}
func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}
https://play.golang.org/p/M0xfCkpT6uD
Good luck.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an interceptor in my angular app where a loading spinner is disabled on specific GET requests. Until now i had no trouble until i had to add an URL with a path variable. I don't know how to capture the path variable with Regex. Here are the essential code snippets:
#Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let displayLoadingScreen = true;
for (const skippUrl of this.skippUrls) {
if (new RegExp(skippUrl).test(request.url)) {
displayLoadingScreen = false;
break;
}
}
...
The urls that have to be skipped:
skippUrls = [
'/product/images',
'/product/${productId}/image', // Stuck on this one. Simply copy pasting the url string doesn't seem to work
'/category/',
...
Thank you for your help!
Try this Regex:
'\/product\/.*\/(image)$'
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a json raw string
{"id":"xxx","person":{"id":"yyy","name":"abc"},"box":{"id":"zzz"}}
I want to rename the field "id" in root to "uuid" without affecting the inner "id" fields.
How can I do this?
regex is the wrong tool for this task. You need to do actual (minimal) JSON parsing. The easiest way to do this is probably with a simple map[string]json.RawMessage, so that only the keys are fully parsed. Example:
var payload map[string]json.RawMessage
if err := json.Unmarshal(input, &payload); err != nil {
panic(err)
}
payload["uuid"] = payload["id"] // Copy from 'id' to 'uuid'
delete(payload, "id") // Delete the old 'id' key/value
output, err := json.Marshal(payload)
if err != nil {
panic(err)
}
// output now has your desired content
I think it is better for you to write some programmatical modificator for the json object. For example, you could try to use https://github.com/qntfy/kazaam or any other json transformation library.
You could also write some data structure with custom json marshaller which takes both "id" on unmarshalling step and produces "uuid" on marshalling step.
One thing of which you can take advantage over regex in golang is that when you don't have defined structure for your JSON to be parsed then you can parse that in an map of string and empty interface that is map[string]interface{}
Now let's start with initially unmarshing your raw string into such map.
Now you can delete the root element of the JSON which you want to change and replace it with another value and again marshal it to get the new string
package main
import (
"fmt"
"encoding/json"
)
func main() {
str := `{"id":"xxx","person":{"id":"yyy","name":"abc"},"box":{"id":"zzz"}}`
mp := make(map[string]interface{})
if err := json.Unmarshal([]byte(str), &mp); err != nil {
fmt.Println("some error occured")
} else {
value := mp["id"].(string)
delete(mp, "id")
mp["uuid"] = value
}
finalAns , _ := json.Marshal(mp)
fmt.Println(string(finalAns))
}
Output :
{"box":{"id":"zzz"},"person":{"id":"yyy","name":"abc"},"uuid":"xxx"}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Need to validate and clean user input of a path. When a user enters the following command line:
app.exe -f "C:\dir with space\"
The the flag value has the last quote escaped, so it's string value is:
C:\dir with space"
What do you guys recommend for a clean approach at sanitizing user input for a directory/path? Regex, or does Go have a library for dealing with this similar to filepath.Clean(), but removes trailing quote?
Edit: The cause is documented here: https://github.com/golang/go/issues/16131
For example,
package main
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
func clean(path string) string {
if runtime.GOOS == "windows" {
path = strings.TrimSuffix(path, `"`)
}
return filepath.Clean(path)
}
func main() {
path := `C:\dir with space"`
fmt.Println(path)
path = clean(path)
fmt.Println(path)
}
Output:
C:\dir with space"
C:\dir with space
Reference: MSDN: Windows: Naming Files, Paths, and Namespaces
pkgDir := flag.String( "f", "", "REQUIRED: `pkgdir` the root directory of the package")
flag.Parse()
*pkgDir = strings.TrimRight(*pkgDir, `'"`)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I am learning F# on my own and am trying to sneak some F# into the workplace.
As a result, I would like to write unit tests in F# to test C# logic.
Can anyone provide me a simple example of an F# unit test targeting a C# method and verifying a C# property as a result of exercising that method?
UPDATE:
Here's an example. When a value is provided for first and last name, how do we unit test (in F#) that GetFullName returns first and last name?
namespace MVVMExample
{
public class ViewModel : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
RaisePropertyChanged("LastName");
}
}
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
So a very simple test for this ViewModel using NUnit could look like this:
testing GetFullName
here is a possible test for this function:
[<Test>]
member __.``GetFullName = "Jon Doe" if FirstName = "Jon" and LastName = "Doh"``() =
let vm = ViewModel()
vm.FirstName <- "Jon"
vm.LastName <- "Doe"
Assert.AreEqual("Jon Doe", vm.GetFullName())
testing PropertyChanged
[<TestFixture>]
type ``ViewModel Unit Tests``() =
[<Test>]
member __.``a PropertyChanged event should be raised if the FirstName was changed``() =
let vm = ViewModel()
let mutable lastChangedProperty = ""
vm.PropertyChanged.Add (fun e -> lastChangedProperty <- e.PropertyName)
vm.FirstName <- "Tom"
Assert.AreEqual("FirstName", lastChangedProperty)
Of course this is not really functional but I think it should be reasonable clear for the given problem.
as you can see it's basically the same you would expect from a C# test - the only F# feature I used are the function/class names in ``...`` which makes the output in your test-runner look nicer:
Code Walkthrough
the [TestFixture] class Test {...} just translates into [<TestFixture>] type Test() = ...
a [Test] method is just [<Test>] member this.MyTestFunction() = ... (this only if you need it - as you can see I did not so I used the idiomatic I-don't-care __ placeholder - see in F# you can name your this-reference any way you want - and you have to do it on each class-member.
as I want to change the lastChangedProperty string if the event is fired I declared it mutable (so you can use the assign operator <-)
to add an event-handler you can just use the .Addfunction on the event
(fun e -> ..) is an lambda - in C# this would be e => ...
disclaimer
of course if you want to use this viewmodel in say a WPF application you should make sure to dispatch to the UI-Thread, etc. which would make the test more nasty but for your example a simple red-green cycle should work ;)
I hope this helps you out (but of course it does not really show the advantages of F# as the test here is ugly side-effecty)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to develop one app in which I need one registration page. How should I apply validation in that for phone numbers and e-mail ? Please somebody help me
You can place validation in your TextFields as follows:
TextField {
id: myTextField
hintText: "Flight number"
inputMode: TextFieldInputMode.NumbersAndPunctuation
validator: Validator {
mode: ValidationMode.Immediate
errorMessage: "Please enter only numbers for this field"
onValidate: {
var valNumeric = /^[0-9 -]+$/i; //Numbers, including space and minus/dash
if (valNumberic.test(parent.text)) {
state = ValidationState.Valid;
} else {
state = ValidationState.Invalid;
}
}
}
}
You can set the inputMode to something such as NumbersAndPunctuation or Email and that will affect the keyboard. Then in the onValidate you can compare the parent.text with a regex expression or in any other way you wish. Setting ValidationState to Invalid will show a validation error with the message you specify in errorMessage.