jueves, 22 de abril de 2021

How to Get Current Time using react

 


        var date = moment()          .utcOffset('+05:30')          .format('YYYY-MM-DD hh:mm:ss a');


https://aboutreact.com/react-native-get-current-date-time/

React -> jsPDF -> autoTable

     const  generatePDF = () => {

    /*******/

    //detail info

        console.log(state.displayData_detail);

    /******/        

        var doc = new jsPDF('p', 'px', 'letter'); 

        doc.text(20, 20, '****')

        doc.text('Reporte Inventario Fisico', 20, 35); //string, x-position, y-position

        doc.text(state.displayData_head.NowDate, 300, 35); //string, x-position, y-position

        doc.text(state.displayData_head.WarehouseDestName, 300, 45); 

        doc.text(state.displayData_head.WarehouseName, 300, 55); 

        //doc.text(state.displayData_head.WarehouseId, 100, 50); //string, x-position, y-position

        doc.setFont('helvetica')

        doc.text(20, 60, 'This is the second title OwO.')

        

        var columns = ["PartnerId", "Descripcion", "Unidades", "CDU", "Importe"];

        var rows = [];

        var rows1 = [];

        var itemNew

    /*

            { PartnerId:'1',ProductNum: 'Case Number', name : '101111111' },

            { PartnerId:'2',ProductNum: 'Patient Name', name : 'UAT DR' },

            { PartnerId:'3',ProductNum: 'Hospital Name', name: 'Dr Abcd' }

    */

            state.displayData_detail

          ;


          itemNew.forEach(element => {      

            var temp = [element.PartnerId,element.ProductNum];

            var temp1 = [element.PartnerId,element.ProductNum];

            rows.push(temp);

            rows1.push(temp1);

    

        });  

          


        doc.autoTable(columns,rows,

        { margin:{ top: 75 }}

        );

        


        doc.save('demo.pdf')  

    /******/

    /******/

    }  


https://www.codegrepper.com/code-examples/javascript/jspdf+create+table

sábado, 3 de abril de 2021

Download youtube from Linux

 
sudo apt install youtube-dl

sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl

sudo chmod a+rx /usr/local/bin/youtube-dl

youtube-dl -U

-- install python
--     sudo apt-get install python-is-python3

youtube-dl <video_url>

youtube-dl -F <video_url>

youtube-dl -f 37<video_url>

youtube-dl -x <video_url>

youtube-dl -x --audio-format mp3 <video_url>

youtube-dl -x --audio-format mp3 <video_url>

youtube-dl -i -f mp4 --yes-playlist 'VÍNCULO-DE-LA-LISTA-DE-REPRODUCCIÓN'

## youtube-dl -o "~/Desktop/%(title)s.%(ext)s" 'youtube file url'
## touch ~/.config/youtube-dl.conf 

#--output "~/Desktop/%(title)s.%(ext)s"

 

https://itsfoss.com/download-youtube-linux/

https://nuvogue-electronics.com.mx/blog/como-descargar-una-lista-de-reproduccion-de-youtube-con-youtube-dl/

lunes, 8 de marzo de 2021

Converting a string to an array REACT

If you had a comma-separated list, you could split it into an array like this.

var shoppingList = 'apples,pears,cookies,bread';

// Returns ["apples", "pears", "cookies", "bread"]

var shoppingListArray = shoppingList.split(',');

console.log( 

                        objectStringArray 

                 )

If you had a comma-separated array, you could split it into an array like this.


var objectstring  ='{Header: "ProductNum2", accessor:"A1", filter:false, orderBy:false },{ Header: "Name", accessor:"A2", filter:false, orderBy:false },{ Header: "Description", accessor:"A3", filter:false, orderBy:false },{ Header: "TxnQty", accessor:"TxnQty", filter:false, orderBy:false },{ Header: "UOM", accessor:"UOM", filter:false, orderBy:false },{ Header: "TxnQtyUOMConvFactor", accessor:"TxnQtyUOMConvFactor", filter:false, orderBy:false },{ Header: "TxnQtyUom", accessor:"TxnQtyUom", filter:false, orderBy:false },{ Header: "Value", accessor:"Value", filter:false, orderBy:false }' 

var objectStringArray = (new Function("return [" + objectstring+ "];")());


             console.log( 

                objectStringArray 

             )   

  

source:

 https://stackoverflow.com/questions/13272406/convert-string-with-commas-to-array

 https://gomakethings.com/converting-a-string-to-an-array-with-vanilla-javascript/ 

sábado, 28 de noviembre de 2020

¿Cómo acceder a la cámara con WebView Android?

main.java

 private WebView wv;

//Definir campos

private static final int FILECHOOSER_RESULCODE =1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageUri = null;
//Fin
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();// Oculta la cabecera.
    wv = (WebView) findViewById(R.id.wv);
    wv.loadUrl("https://Mobile.xhtml");
    wv.setWebViewClient(new MyClient());
    wv.setWebChromeClient(new GoogleClient());
    WebSettings webSettings = wv.getSettings();
    webSettings.setJavaScriptEnabled(true);
    wv.getSettings().setDomStorageEnabled(true);
    wv.getSettings().setAllowFileAccess(true);
    wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wv.clearCache(false);

    wv.setWebChromeClient(new WebChromeClient(){
        //Implementacion de Canvas de archivos
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String accepType){
            mUploadMessage = uploadMsg;
            openImageChooser();
        }
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams filechooserParams){
            mUploadMessages = filePathCallback;
            openImageChooser();
            return true;
        }
        public void openFileChooser(ValueCallback<Uri> uploadMsg){
            openFileChooser(uploadMsg, "");
        }
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            openFileChooser(uploadMsg, acceptType);
        }
        //Fin
    });
    //Metodo para descargar pdf
    wv.setDownloadListener(new DownloadListener()
    {
        @Override
        public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimeType,long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("cookie", cookies);
            request.addRequestHeader("User-Agent", userAgent);
            request.setDescription("Descargando pdf..."); //request.setDescription("Downloading file...");
            request.setTitle(URLUtil.guessFileName(url, contentDisposition,mimeType));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalFilesDir(MainActivity.this,Environment.DIRECTORY_DOWNLOADS,".pdf");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Descargando pdf...",Toast.LENGTH_LONG).show();
        }});
    wv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            wv.loadUrl("TU WEB ");
        }
    });
}
//metodo para abrir google drive
private void openImageChooser(){
    try{
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
        if (!imageStorageDir.exists()){
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        mCapturedImageUri = Uri.fromFile(file);
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageUri);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, FILECHOOSER_RESULCODE);
    } catch (Exception e){
        e.printStackTrace();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
    if (requestCode==FILECHOOSER_RESULCODE){
        if (null == mUploadMessage && null == mUploadMessages){
            return;
        }
        if (null != mUploadMessage){
            handleUploadMessage(requestCode, resultCode, intent);
        } else if (mUploadMessages != null){
            handleUploadMessages(requestCode, resultCode, intent);
        }
    }
}

private void handleUploadMessage(int requestCode, int resultCode, Intent intent) {
    Uri result = null;
    try {
        if (resultCode != RESULT_OK){
            result = null;
        } else {
            result = intent == null ? mCapturedImageUri : intent.getData();
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    mUploadMessage.onReceiveValue(result);
    mUploadMessage = null;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void handleUploadMessages(int requestCode, int resultCode, Intent intent) {
    Uri[] results = null;
    try {
        if (resultCode != RESULT_OK){
            results = null;
        } else {
            if (intent != null){
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null){
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++){
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null){
                    results = new Uri[]{Uri.parse(dataString)};
                }
            } else {
                results = new Uri[]{mCapturedImageUri};
            }
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    mUploadMessages.onReceiveValue(results);
    mUploadMessages = null;
}
class MyClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view,String url,Bitmap favicon){
        super.onPageStarted(view,url,favicon);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view,String Url)
    {
        view.loadUrl(Url);
        return true;
    }
    @Override
    public void onPageFinished(WebView view,String url)
    {
        super.onPageFinished(view,url);
    }
}
class GoogleClient extends WebChromeClient
{
    @Override
    public void onProgressChanged(WebView view,int newProgress)
    {
        super.onProgressChanged(view,newProgress);
    }
}

@Override
public void onBackPressed() {
    if (wv.canGoBack())
        wv.goBack();
    else
        super.onBackPressed();

}





Esto fue robado de: https://es.stackoverflow.com/questions/106689/c%C3%B3mo-acceder-a-la-c%C3%A1mara-con-webview-android

miércoles, 28 de octubre de 2020

Don't navigate to other pages in WebView (shouldOverrideUrlLoading )

 ref: https://stackoverflow.com/questions/19426742/dont-navigate-to-other-pages-in-webview-disable-links-and-references


WebView gives developers an easy way to embed a web-based application to an Android app with almost no code. Just give it some URL and it works.

Implementation of the application which displays the predefined web page in a WebView is relatively straightforward.

        myWebView.loadUrl("your_pages");

There are two scenarios how a web app might react to a user click event. The first one is redirection. WebView client has quite an easy way to listen for redirects. You just need to override its method shouldOverrideUrlLoading() .

package com.demilion.myapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.io.IOException;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.webkit.WebViewClient;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends Activity {
private AdView mAdView;
private boolean loaded = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

MobileAds.initialize(this,
"ca-app-pub-000000000000000~0000000000");

mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

WebView myWebView = (WebView) this.findViewById(R.id.webView);
myWebView.setWebChromeClient(new WebChromeClient());

myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

myWebView.addJavascriptInterface(new AudioInterface(this), "AndAud");

// Enable JavaScript
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);


//myWebView.loadUrl("https://codepen.io/loktar00/pen/CHpGo/");
//myWebView.loadUrl("file:///android_asset/myhtml.html");
myWebView.loadUrl("https://codepen.io/loktar00/pen/CHpGo/");



myWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

if(loaded == false){
view.loadUrl(url);
loaded = true;
return true;
}else{
return false;
}

}
})
;







}

public class WebAppInterface {

Context
context;

/**
* Instantiate the interface and set the context
*
* @param context
*/
public WebAppInterface(Context context) {
this.context = context;
}

/**
* Show a dialog from the web page.
*
* @param message
* message of the dialog
*/
@JavascriptInterface
public void showDialog(String message) {

// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
builder.setMessage(message).setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss()
;
}
})
;
// Create the AlertDialog object and return it
builder.create().show();
}
}

public class AudioInterface {
Context
mContext;

AudioInterface(Context c) {
mContext = c;
}

//Play an audio file from the webpage
@JavascriptInterface
public void playAudio(String aud) { //String aud - file name passed
//from the JavaScript function
final MediaPlayer mp;

try {
AssetFileDescriptor fileDescriptor =
mContext.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}