NativeScript-vue Barcode creation - nativescript-vue

Hi i would like to ask if there is anyway to create a barcode in nativescript-vue, there is a lot of vue js example of creating barcode but im not equipped to translate or convert the codes. is there anyone can give me an example of creating barcode on nativescript-vue? thank you.

You can use nativescript-qr-generator & nativescript-base-64-manager.
The base-64 only if you want to convert the QR code as a base-64.
Import it in your template:
import { QrGenerator } from "nativescript-qr-generator";
import { Base64Manager } from "nativescript-base-64-manager";
You would need a data property generatedQR: null and then you would need a method to generate QR. So the QR code is generated and then then your code value is converted to the base64 value. You can also append any data to the result like an url for example: new QrGenerator().generate("url/" + _Base64Manager.btoa(this.code)
generateQR() {
const _Base64Manager = new Base64Manager();
const result = new QrGenerator().generate( _Base64Manager.btoa(this.code),
{
color: "#your_color",
backgroundColor: "#your_color"
}
);
this.generatedQR = new ImageSource(result);
}
and in template you will have the QR code like an image:
<Image :src="generatedQR" row="4" imageFit="aspectFill"/>

Related

vue testing vuetify input for disabled

I am very new to testing and I'm struggling my way through all this new stuff I am learning. Today I want to write a test for a vuetify <v-text-field> component like this:
<v-text-field
v-model="user.caption"
label="Name"
:disabled="!checkPermissionFor('users.write')"
required
/>
my test should handle the following case:
an active, logged in user has a array in vuex store which has his permissions as a array of strings. exactly like this
userRights: ['dashboard', 'imprint', 'dataPrivacy']
the checkPermissionFor() function is doing nothing else then checking the array above with a arr.includes('x')
after it came out the right is not included it gives me a negotiated return which handles the disabled state on that input field.
I want to test this exact scenario.
my test at the moment looks like this:
it('user has no rights to edit other user overview data', () => {
const store = new Vuex.Store({
state: {
ActiveUser: {
userData: {
isLoggedIn: true,
isAdmin: false,
userRights: ['dashboard', 'imprint', 'dataPrivacy']
}
}
}
})
const wrapper = shallowMount(Overview, {
store,
localVue
})
const addUserPermission = wrapper.vm.checkPermissionFor('users.write')
const inputName = wrapper.find(
'HOW TO SELECT A INPUT LIKE THIS? DO I HAVE TO ADD A CLASS FOR IT?'
)
expect(addUserPermission).toBe(false)
expect(inputName.props('disabled')).toBe(false)
})
big questions now:
how can I select a input from vuetify which has no class like in my case
how can I test for "is the input disabled?"
wrapper.find method accepts a query string. You can pass a query string like this :
input[label='Name'] or if you know the exact index you can use this CSS query too : input:nth-of-type(2).
Then find method will return you another wrapper. Wrapper has a property named element which returns the underlying native element.
So you can check if input disabled like this :
const buttonWrapper = wrapper.find("input[label='Name']");
const isDisabled = buttonWrapper.element.disabled === true;
expect(isDisabled ).toBe(true)
For question 1 it's a good idea to put extra datasets into your component template that are used just for testing so you can extract that element - the most common convention is data-testid="test-id".
The reason you should do this instead of relying on the classes and ids and positional selectors or anything like that is because those selectors are likely to change in a way that shouldn't break your test - if in the future you change css frameworks or change an id for some reason, your tests will break even though your component is still working.
If you're (understandably) worried about polluting your markup with all these data-testid attributes, you can use a webpack plugin like https://github.com/emensch/vue-remove-attributes to strip them out of your dev builds. Here's how I use that with laravel mix:
const createAttributeRemover = require('vue-remove-attributes');
if (mix.inProduction()) {
mix.options({
vue: {
compilerOptions: {
modules: [
createAttributeRemover('data-testid')
]
}
}
})
}
as for your second question I don't know I was googling the same thing and I landed here!

unable to create a document with raw content on dialog flow knowledge bases

i am using com.google.cloud.dialogflow.v2beta1.Document to create document through java rpc,we have a setContent() method which is used creating document with raw content, when i try to create document i am getting below exception.
Caused by: com.google.api.gax.rpc.InvalidArgumentException: Operation
with name
"projects/agent-fa5be/operations/ks-add_document-NDQ0NDQ3MjI5MDA3NTIxMzgyNA"
failed with status = GrpcStatusCode{transportCode=INVALID_ARGUMENT}
and message = CSV documents must have exactly two columns. The
provided document has 1 columns.
when i check dialogflow.v2beta1 Documentation there clearly mentioned content is deprecated use raw_content instead of content. but there is no supported method for raw_content in com.google.cloud.dialogflow.v2beta1.Document
I was experimenting a similar issue. I tried different libraries and techniques until I found something that worked. In my case I've to parse each row as follows:
let input = ['Question1', 'Answer1\n'];
let input2 = ['Question2', 'Answer2\n'];
let base64data = input.toString('base64') + input2.toString('base64');
const request = {
parent: 'projects/PROJECT_ID/knowledgeBases/KNOWLEDGEBASE_ID',
document: {
knowledgeTypes: ['FAQ'],
displayName: 'Echele',
content: base64data,
source: 'rawContent',
mimeType: 'text/csv',
},
};
This allowed my to submit the document, hope it works for you too!
Regards
Please find working solution
String documentName="test.csv";
try {
byte[] bytedata = filedata.toString().getBytes();
ByteString bytestring = ByteString.copyFrom(bytedata);
byte[] bytedata1 = "text/csv".getBytes();
ByteString mimestring = ByteString.copyFrom(bytedata1);
DocumentsSettings docuemtnSettings = DocumentsSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
DocumentsClient documentsClient = DocumentsClient.create(docuemtnSettings);
Document document = Document.newBuilder().setDisplayName(documentName).setContentBytes(bytestring)
.setMimeTypeBytes(mimestring).addKnowledgeTypes(KnowledgeType.FAQ).build();
CreateDocumentRequest createDocumentRequest = CreateDocumentRequest.newBuilder().setDocument(document)
.setParent(knowledgeBaseName).build();
OperationFuture<Document, KnowledgeOperationMetadata> response = documentsClient
.createDocumentAsync(createDocumentRequest);
Document createdDocument = response.get();
System.out.format(" - docuemnt created ID: %s\n", createdDocument.getName());

Base64 Encoding for multi Variables

I have a list of 3 environment variables that I want to bind and encode them (Key +value) in base64.
fro examples,
the 3 Variable now are stored as key-value variables and what i need to have is a base64 encode on this:
{
"VAR1": "313",
"VAR2": "33344",
"VAR3": "rovkssj",
}
I guess that should use the script to create the json and encode it.
appreciate your help
Ronen
Postman uses the built-in module CryptoJS. This could be used to get you close to a solution.
If you add this into the Pre-request Script or Tests tab and send a request, you will see the output of the Base64 conversation in the Postman Console. In the example I'm getting the 'VAR1' environment variable and using this as the value to convert.
var CryptoJS = require("crypto-js")
//Encrypt
var rawStr = CryptoJS.enc.Utf8.parse(pm.environment.get('VAR1'))
var base64 = CryptoJS.enc.Base64.stringify(rawStr)
console.log(`Encrypted value: ${base64}`)
//Decrypt
var parsedWord = CryptoJS.enc.Base64.parse(base64)
var parsedStr = parsedWord.toString(CryptoJS.enc.Utf8)
console.log(`Decrypted value: ${parsedStr}`)
Postman Console output:
This is probably not the exact solution that you need but hopefully this brings you closer to achieving what you need to do.
I see that, in the answer given by #danny-dainton he is importing a JS library. That is unnecessary.
You can just use the btoa and atob functions. Reference
In postman this would be (In your Tests / Pre-request Script tab)
var str = "Hello World!";
var encodedValue = btoa(str);
var decodedValue = atob(encodedValue);
So in your case to decode { "VAR1": "313", "VAR2": "33344", "VAR3": "rovkssj", }
you can just do
var str = "{ \"VAR1\": \"313\", \"VAR2\": \"33344\", \"VAR3\": \"rovkssj\", }";
var encodedValue = btoa(str);
PS: I just want to add that your JSON { "VAR1": "313", "VAR2": "33344", "VAR3": "rovkssj", } is not valid as there is an extra , at the end.

XSLT Streaming Chained Transform

I am using Saxon EE to transform a very large document, using streaming transform. I now need to chain multiple XSLTs. How does one go about doing that ?
When not streaming, I have used the XSLTTransformer class as destination, to do chained transforms. If I am not mistaken, I guess I cannot do that, as that would create a result tree as against result stream.
Thanks,
Ani
Pipe the SAX output events of the 1st transform into the SAX input events of the 2nd transform.
I've attached some example Scala code which shows this.
Basically it kicks off the 2nd XSLT first, which behind the scenes invokes the 1st XSLT with the initial input document capturing the intermediate output which is then fed as the input to the 2nd XSLT in real time. Nice.
It uses JAXP interfaces, so no S9 API.
I've successfully tested it with a 1.2GB input XML file.
Hope this helps.
XSLT 3.0 rocks by the way! Good choice.
import javax.xml.transform.sax.{SAXResult, SAXSource}
import javax.xml.transform.stream.{StreamResult, StreamSource}
import javax.xml.transform.{Source, Transformer}
import com.saxonica.config.StreamingTransformerFactory
import org.xml.sax._
import org.xml.sax.helpers.XMLFilterImpl
object Main extends App
{
val transformer1 = transformer("transform-1.xsl")
val transformer2 = transformer("transform-2.xsl")
val inputXML = "big.xml"
transformer2.transform(
new SAXSource(
new Transformer1OutputReader(transformer1, new StreamSource(inputXML)),
null
),
new StreamResult("out.xml")
)
def transformer(xslt : String) =
new StreamingTransformerFactory().newTransformer(new StreamSource(xslt))
}
class Transformer1OutputReader(
transformer1 : Transformer,
source1 : Source) extends XMLFilterImpl
{
def parseImpl() =
{
println("parseImpl()")
val inputToSecondXslt : ContentHandler = getContentHandler
transformer1.transform(
source1,
new SAXResult(inputToSecondXslt)
)
}
override def parse(input : InputSource) = parseImpl
override def parse(systemId : String) = parseImpl
override def setFeature(name: String, value: Boolean) : Unit = {}
}

Ionic 2 / cordova-plugin-file File.writeFile() refuses to create binary file correctly (png image)

In summary
File.writeFile() creates a PNG file of 0 bytes when trying to write a Blob made from base64 data.
In my application, I am trying to create a file that consists of base64 data stored in the db. The rendered equivalent of the data is a small anti-aliased graph curve in black on a transparent background (never more that 300 x 320 pixels) that has previously been created and stored from a canvas element. I have independently verified that the stored base64 data is indeed correct by rendering it at one of various base64 encoders/decoders available online.
Output from "Ionic Info"
--------------------------------
Your system information:
Cordova CLI: 6.3.1
Gulp version: CLI version 3.9.1
Gulp local:
Ionic Framework Version: 2.0.0-rc.2
Ionic CLI Version: 2.1.1
Ionic App Lib Version: 2.1.1
Ionic App Scripts Version: 0.0.39
OS:
Node Version: v6.7.0
--------------------------------
The development platform is Windows 10, and I've been testing directly on a Samsung Galaxy S7 and S4 so far.
I know that the base64 data has to be converted into binary data (as a Blob) first, as File does not yet support writing base64 directly in to an image file. I found various techniques with which to do this, and the code which seems to suit my needs the most (and reflects a similar way I would have done it in java is illustrated below):
Main code from constructor:
this.platform.ready().then(() => {
this.graphDataService.getDataItem(this.job.id).then((data) =>{
console.log("getpic:");
let imgWithMeta = data.split(",")
// base64 data
let imgData = imgWithMeta[1].trim();
// content type
let imgType = imgWithMeta[0].trim().split(";")[0].split(":")[1];
console.log("imgData:",imgData);
console.log("imgMeta:",imgType);
console.log("aftergetpic:");
// this.fs is correctly set to cordova.file.externalDataDirectory
let folderpath = this.fs;
let filename = "dotd_test.png";
File.resolveLocalFilesystemUrl(this.fs).then( (dirEntry) => {
console.log("resolved dir with:", dirEntry);
this.savebase64AsImageFile(dirEntry.nativeURL,filename,imgData,imgType);
});
});
});
Helper to convert base64 to Blob:
// convert base64 to Blob
b64toBlob(b64Data, contentType, sliceSize) {
//console.log("data packet:",b64Data);
//console.log("content type:",contentType);
//console.log("slice size:",sliceSize);
let byteCharacters = atob(b64Data);
let byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
let slice = byteCharacters.slice(offset, offset + sliceSize);
let byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
console.log("size of bytearray before blobbing:", byteArrays.length);
console.log("blob content type:", contentType);
let blob = new Blob(byteArrays, {type: contentType});
// alternative way WITHOUT chunking the base64 data
// let blob = new Blob([atob(b64Data)], {type: contentType});
return blob;
}
save the image with File.writeFile()
// save the image with File.writeFile()
savebase64AsImageFile(folderpath,filename,content,contentType){
// Convert the base64 string in a Blob
let data:Blob = this.b64toBlob(content,contentType,512);
console.log("file location attempt is:",folderpath + filename);
File.writeFile(
folderpath,
filename,
data,
{replace: true}
).then(
_ => console.log("write complete")
).catch(
err => console.log("file create failed:",err);
);
}
I have tried dozens of different decoding techniques, but the effect is the same. However, if I hardcode simple text data into the writeFile() section, like so:
File.writeFile(
folderpath,
"test.txt",
"the quick brown fox jumps over the lazy dog",
{replace: true}
)
A text file IS created correctly in the expected location with the text string above in it.
However, I've noticed that whether the file is the 0 bytes PNG, or the working text file above, in both cases the ".then()" consequence clause of the File Promise never fires.
Additionally, I swapped the above method and used the Ionic 2 native Base64-To-Gallery library to create the images, which worked without a problem. However, having the images in the user's picture gallery or camera roll is not an option for me as I do not wish to risk a user's own pictures while marshalling / packing / transmitting / deleting the data-rendered images. The images should be created and managed as part of the app.
User marcus-robinson seems to have experienced a similar issue outlined here, but it was across all file types, and not just binary types as seems to be the case here. Also, the issue seems to have been closed:
https://github.com/driftyco/ionic/issues/5638
Anybody experiencing something similar, or possibly spot some error I might have caused? I've tried dozens of alternatives but none seem to work.
I had similar behaviour saving media files which worked perfectly on iOS. Nonetheless, I had the issue of 0 bytes file creation on some Android devices in release build (dev build works perfectly). After very long search, I followed the following solution
I moved the polyfills.js script tag to the top of the index.html in the ionic project before the cordova.js tag. This re-ordering somehow the issue is resolved.
So the order should look like:
<script src="build/polyfills.js"></script>
<script type="text/javascript" src="cordova.js"></script>
Works on ionic 3 and ionic 4.
The credits go to 1
I got that working with most of your code:
this.file.writeFile(this.file.cacheDirectory, "currentCached.jpeg", this.b64toBlob(src, "image/jpg", 512) ,{replace: true})
The only difference i had was:
let byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpeg|jpg);base64,/, ''));
instead of your
let byteCharacters = atob(b64Data);
Note: I did not use other trimming etc. like those techniques you used in your constructor class.