问:
How to position image on canvas same as overlaped div of same dimension
I have two div of same dimension which overlap each other using z-index.
Ist div contain image and 2nd div contain a canvas

I am trying to draw image on canvas same place as Ist div. I am using hammerjs library to zoomin/out , reposition and rotate image. I found these code somewhere else

```<code>function getMeta(url){

     img = new Image();
    var remoteImage = {}
    img.src = url;
    remoteImage.width = img.naturalWidth
    remoteImage.height = img.naturalHeight
    remoteImage.src = url;
    return remoteImage
}

var urlImage = getMeta('https://www.penghu-nsa.gov.tw/FileDownload/Album/Big/20161012162551758864338.jpg')

var text = document.querySelector("#text");
var oImg=document.querySelector("#img_scan");

oImg.style['transition-duration'] = '100ms';
var timeInMs = 0;
var preAngle = 0;
var rotateAngle = 0;
var preRotation = 0;

var originalSize = {
    width : oImg.offsetWidth,
    height : oImg.offsetHeight,
}

var current = {
    x : 0,
    y : 0,
    z : 1,
    angle : 0,
    width: originalSize.width,
    height: originalSize.height,
}

var last = {
    x : 0,
    y : 0,
    z : 1,
}

var oImgRec = oImg.getBoundingClientRect();

var cx = oImgRec.left + oImgRec.width * 0.5;

var cy = oImgRec.top + oImgRec.height * 0.5;

var imageCenter = {
    x:cx,
    y:cy
}

var pinchImageCenter = {}

var deltaIssue = { x: 0, y: 0 };

var pinchStart = { x: undefined, y: undefined, isPanend:false}

var panendDeltaFix = {x:0,y:0,isPanend:false}

var pinchZoomOrigin = undefined;

var lastEvent = ''

var hammer = new Hammer(oImg);

hammer.get('pinch').set({enable: true});

hammer.get('pan').set({direction: Hammer.DIRECTION_ALL}).recognizeWith(hammer.get('pinch'));

hammer.on("pinchstart", function(e) {

    last.x = current.x;
    last.y = current.y;
    pinchStart.x = e.center.x;
    pinchStart.y = e.center.y;
    pinchImageCenter = {
        x: imageCenter.x + last.x,
        y: imageCenter.y + last.y
    }

    lastEvent = 'pinchstart';

});

hammer.on("pinchmove", function(e) {

    if(preAngle == 0){
        preAngle = Math.round(e.rotation);
        preRotation = Math.round(e.rotation);
    }else{
        if(Math.abs(Math.round(e.rotation)-preRotation)>=300){

            if(e.rotation > 0){
                preAngle+=360;
            }else if(e.rotation < 0){
                preAngle-=360;

            }

        }

        current.angle = rotateAngle + (Math.round(e.rotation)-preAngle);
        preRotation = Math.round(e.rotation);

    }

    var newScale = (last.z * e.scale) >= 0.1 ? (last.z * e.scale) : 0.1;

    var d = scaleCal(e.center, pinchImageCenter, last.z, newScale)

    current.x = d.x + last.x;

    current.y = d.y + last.y;

    current.z = d.z + last.z;

    update();

    lastEvent = 'pinchmove';
});

hammer.on("pinchend", function(e) {
    last.x = current.x;
    last.y = current.y;
    last.z = current.z;
    rotateAngle = current.angle;
    preAngle = 0;
    lastEvent = 'pinchend';

});

hammer.on("panmove", function(e) {
    var panDelta = {
        x:e.deltaX,
        y:e.deltaY
    }

    if (lastEvent !== 'panmove') {

        deltaIssue = {
            x: panDelta.x,
            y: panDelta.y
        }
    }

    current.x = (last.x+panDelta.x-deltaIssue.x);

    current.y = (last.y+panDelta.y-deltaIssue.y);

    lastEvent = 'panmove'
    update();
});

hammer.on("panend", function(e) {
    last.x = current.x;
    last.y = current.y;
    lastEvent = 'panend';
});

hammer.on('tap', function(e) {

    if((Date.now()-timeInMs)<300){

        if(last.z > 1){
            last.z = 1;
            current.z = 1;
            update();
        }else if(last.z <= 1){
            last.z = 2;
            current.z = 2;
            update();
        }
    }

    timeInMs = Date.now();
    lastEvent = 'tap';

});

function scaleCal(eCenter, originCenter, currentScale, newScale) {

    var zoomDistance = newScale - currentScale;

    var x = (originCenter.x - eCenter.x)*(zoomDistance)/currentScale;

    var y = (originCenter.y - eCenter.y)*(zoomDistance)/currentScale;

    var output = {
        x: x,
        y: y,
        z: zoomDistance
    }
    return output
}

function update() {

    current.height = originalSize.height * current.z;

    current.width = originalSize.width * current.z;

    if(current.z < 0.1){
        current.z = 0.1;
    }

    oImg.style.transform = " translate3d(" + current.x + "px, " + current.y + "px, 0)rotate("+current.angle+"deg)scale("+current.z+")"

}

</code>```

So by above code user can zoomin/zoom out , rotate image . After they set image in their desired position i am putting that image on canvas so i can use dataurl method to save image later.

I tried below code to draw image on canvas same place as div ,same dimension and with same angle  but sadly image is not getting exactly same positioned as div

```<code>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

$("#btn").click(copyoncanvas);

function copyoncanvas(){

var bound=objimg.getBoundingClientRect();

var objimg=new Image();

objimg.src="https://www.penghu-nsa.gov.tw/FileDownload/Album/Big/20161012162551758864338.jpg";

ctx.drawImage(objimg,bound.left,bound.top,current.width,current.height);

drawRotated(current.angle,bound.left,bound.top);
}

function drawRotated(degrees,l,t){

const objimg=document.getElementById("img_scan");

ctx.clearRect(0,0,canvas.width,canvas.height);

ctx.save();

var x=canvas.width/2;

var y=canvas.height/2;

ctx.translate(x,y);

ctx.rotate(degrees * Math.PI/180);

ctx.drawImage(objimg,-l,-t,current.width,current.height);

ctx.restore();

}

</code>```

I think my problem is with drawrotated function because it work fine without using it but i want to rotate image on canvas too

HTML

```<code><div id="container">

<div class="box"><canvas id="canvas"></canvas></div>

<div id="imgcont">

<img src="https://www.penghu-nsa.gov.tw/FileDownload/Album/Big/20161012162551758864338.jpg" id="img_scan" class="img-custom-img2"/>

</div>

</div>

<button id="btn">Copy on canvas</button>

</code>```

CSS

```<code>#container{
  position:relative;margin: 0px;
padding:0px;background:#ff0;
top:0px; overflow:hidden;
width:300px;
border:1px solid #000; height:250}

    #img_scan,.box{
      width:100%; height:100%;
        position: absolute;
        top: 0;
        left: 0; margin:0; padding:0px
    }

.box{z-index:98;height:250}

#canvas{width:100%;margin:0;
padding:0;
width:300;height:250}

#img_scan{width:300px;height:250px}

#imgcont{width:100%;height:250px;z-index:99}
</code>```

Body:
I have two div of same dimension which overlap each other using z-index.
Ist div contain image and 2nd div contain a canvas

I am trying to draw image on canvas same place as Ist div. I am using hammerjs library to zoomin/out , reposition and rotate image. I found these code somewhere else

function getMeta(url){

     img = new Image();
    var remoteImage = {}
    img.src = url;
    remoteImage.width = img.naturalWidth
    remoteImage.height = img.naturalHeight
    remoteImage.src = url;
    return remoteImage
}

var urlImage = getMeta('https://www.penghu-nsa.gov.tw/FileDownload/Album/Big/20161012162551758864338.jpg')

var text = document.querySelector("#text");
var oImg=document.querySelector("#img_scan");

oImg.style['transition-duration'] = '100ms';
var timeInMs = 0;
var preAngle = 0;
var rotateAngle = 0;
var preRotation = 0;

var originalSize = {
    width : oImg.offsetWidth,
    height : oImg.offsetHeight,
}

var current = {
    x : 0,
    y : 0,
    z : 1,
    angle : 0,
    width: originalSize.width,
    height: originalSize.height,
}

var last = {
    x : 0,
    y : 0,
    z : 1,
}

var oImgRec = oImg.getBoundingClientRect();

var cx = oImgRec.left + oImgRec.width * 0.5;

var cy = oImgRec.top + oImgRec.height * 0.5;

var imageCenter = {
    x:cx,
    y:cy
}

var pinchImageCenter = {}

var deltaIssue = { x: 0, y: 0 };

var pinchStart = { x: undefined, y: undefined, isPanend:false}

var panendDeltaFix = {x:0,y:0,isPanend:false}

var pinchZoomOrigin = undefined;

var lastEvent = ''

var hammer = new Hammer(oImg);

hammer.get('pinch').set({enable: true});

hammer.get('pan').set({direction: Hammer.DIRECTION_ALL}).recognizeWith(hammer.get('pinch'));

hammer.on("pinchstart", function(e) {

    last.x = current.x;
    last.y = current.y;
    pinchStart.x = e.center.x;
    pinchStart.y = e.center.y;
    pinchImageCenter = {
        x: imageCenter.x + last.x,
        y: imageCenter.y + last.y
    }

    lastEvent = 'pinchstart';

});

hammer.on("pinchmove", function(e) {

    if(preAngle == 0){
        preAngle = Math.round(e.rotation);
        preRotation = Math.round(e.rotation);
    }else{
        if(Math.abs(Math.round(e.rotation)-preRotation)>=300){

            if(e.rotation > 0){
                preAngle+=360;
            }else if(e.rotation < 0){
                preAngle-=360;

            }

        }

        current.angle = rotateAngle + (Math.round(e.rotation)-preAngle);
        preRotation = Math.round(e.rotation);

    }

    var newScale = (last.z * e.scale) >= 0.1 ? (last.z * e.scale) : 0.1;

    var d = scaleCal(e.center, pinchImageCenter, last.z, newScale)

    current.x = d.x + last.x;

    current.y = d.y + last.y;

    current.z = d.z + last.z;

    update();

    lastEvent = 'pinchmove';
});

hammer.on("pinchend", function(e) {
    last.x = current.x;
    last.y = current.y;
    last.z = current.z;
    rotateAngle = current.angle;
    preAngle = 0;
    lastEvent = 'pinchend';

});

hammer.on("panmove", function(e) {
    var panDelta = {
        x:e.deltaX,
        y:e.deltaY
    }

    if (lastEvent !== 'panmove') {

        deltaIssue = {
            x: panDelta.x,
            y: panDelta.y
        }
    }

    current.x = (last.x+panDelta.x-deltaIssue.x);

    current.y = (last.y+panDelta.y-deltaIssue.y);

    lastEvent = 'panmove'
    update();
});

hammer.on("panend", function(e) {
    last.x = current.x;
    last.y = current.y;
    lastEvent = 'panend';
});

hammer.on('tap', function(e) {

    if((Date.now()-timeInMs)<300){

        if(last.z > 1){
            last.z = 1;
            current.z = 1;
            update();
        }else if(last.z <= 1){
            last.z = 2;
            current.z = 2;
            update();
        }
    }

    timeInMs = Date.now();
    lastEvent = 'tap';

});

function scaleCal(eCenter, originCenter, currentScale, newScale) {

    var zoomDistance = newScale - currentScale;

    var x = (originCenter.x - eCenter.x)*(zoomDistance)/currentScale;

    var y = (originCenter.y - eCenter.y)*(zoomDistance)/currentScale;

    var output = {
        x: x,
        y: y,
        z: zoomDistance
    }
    return output
}

function update() {

    current.height = originalSize.height * current.z;

    current.width = originalSize.width * current.z;

    if(current.z < 0.1){
        current.z = 0.1;
    }

    oImg.style.transform = " translate3d(" + current.x + "px, " + current.y + "px, 0)rotate("+current.angle+"deg)scale("+current.z+")"

}

So by above code user can zoomin/zoom out , rotate image . After they set image in their desired position i am putting that image on canvas so i can use dataurl method to save image later.

I tried below code to draw image on canvas same place as div ,same dimension and with same angle  but sadly image is not getting exactly same positioned as div

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

$("#btn").click(copyoncanvas);

function copyoncanvas(){

var bound=objimg.getBoundingClientRect();

var objimg=new Image();

objimg.src="https://www.penghu-nsa.gov.tw/FileDownload/Album/Big/20161012162551758864338.jpg";

ctx.drawImage(objimg,bound.left,bound.top,current.width,current.height);

drawRotated(current.angle,bound.left,bound.top);
}

function drawRotated(degrees,l,t){

const objimg=document.getElementById("img_scan");

ctx.clearRect(0,0,canvas.width,canvas.height);

ctx.save();

var x=canvas.width/2;

var y=canvas.height/2;

ctx.translate(x,y);

ctx.rotate(degrees * Math.PI/180);

ctx.drawImage(objimg,-l,-t,current.width,current.height);

ctx.restore();

}

I think my problem is with drawrotated function because it work fine without using it but i want to rotate image on canvas too

HTML

<canvas id="canvas"></canvas>

<button id="btn">Copy on canvas</button>

CSS

#container{
  position:relative;margin: 0px;
padding:0px;background:#ff0;
top:0px; overflow:hidden;
width:300px;
border:1px solid #000; height:250}

    #img_scan,.box{
      width:100%; height:100%;
        position: absolute;
        top: 0;
        left: 0; margin:0; padding:0px
    }

.box{z-index:98;height:250}

#canvas{width:100%;margin:0;
padding:0;
width:300;height:250}

#img_scan{width:300px;height:250px}

#imgcont{width:100%;height:250px;z-index:99}


来源: stackexchange

问:
Is this Python runtime binding?

def wurk():
    print(i)
for i in range(4):
    wurk()
```

Despite being declared before the for loop, wurk() can still be bound to i. How does this runtime binding work? I think one related question is here

ContentLicense: CC BY-SA 4.0

Title: Is this Python runtime binding?

Body:
def wurk():
    print(i)
for i in range(4):
    wurk()

Despite being declared before the for loop, wurk() can still be bound to i. How does this runtime binding work? I think one related question is here


问:
How to display variation weights and prices of a product on shop page?
Example image

I want the weights and prices of a product to appear on my shop page like in the example image above (weights and prices are to the right of the product title in the example). How do I do this?

I have tried this code, but it doesn't show my variation weights and prices on the shop page.

```<code>/**
 * Show product weight on archive pages
 */
add_action( 'woocommerce_after_shop_loop_item', 'rs_show_weights', 9 );

function rs_show_weights() {

    global $product;
    $weight = $product->get_weight();

    if ( $product->has_weight() ) {
        echo '<div class="product-meta"><span class="product-meta-label">Weight: </span>' . $weight . get_option('woocommerce_weight_unit') . '</div></br>';
    }
}
</code>```

Body:
Example image

I want the weights and prices of a product to appear on my shop page like in the example image above (weights and prices are to the right of the product title in the example). How do I do this?

I have tried this code, but it doesn't show my variation weights and prices on the shop page.

/**
 * Show product weight on archive pages
 */
add_action( 'woocommerce_after_shop_loop_item', 'rs_show_weights', 9 );

function rs_show_weights() {

    global $product;
    $weight = $product->get_weight();

    if ( $product->has_weight() ) {
        echo '
Weight: ' . $weight . get_option('woocommerce_weight_unit') . '

';
    }
}


问:
How to create a setter in a model object that would update indexedDB in vanilla JS?
I'm trying to create an object which when any properties are set would update its corresponding indexedDB data automatically.

The following code works as intended but each time that I'm calling the object from the indexedb. I need to create the object as

new
ResultsModel(indexedDbData._scores,indexedDbData._overallScore,indexedDbData.id)

Which seems an "anti-pattern" as I'm calling what would be "private" variables even if at this point it's just data.

Is that an issue?
I'm also not sure about setting up "setter" and "getter" ? Should I just create "update" function at this point ?

What would be a good pattern to achieve this ?

```<code>export class ResultsModel{
    constructor(scores,overallScore, id){
        this._scores = scores;
        this._overallScore = overallScore;
        this.id = id;
    }

    async init(){
        sessionStorage.setItem("lastResults", JSON.stringify(this));
        await this.save();
    }

    async save(){
        let req = await db.transaction("moodResults","readwrite").objectStore("moodResults").put(this);
        req.onsuccess = function(event) {console.log("saved")}
        req.onerror = function(event) {console.log("error")}
    }

    get scores(){
        return this._scores;
    }

    get overallScore(){
        return this._overallScore;
    }

    set scores(newValue){
        this._scores = newValue;
    }

    set overallScore(newValue){
        this._overallScore = newValue;
        if(this.overallScore === undefined){return}

        return (async () =>{
            let objectStore = await db.transaction("moodResults","readwrite").objectStore("moodResults");
            const req = await objectStore.get(parseInt(this.id));

            req.onsuccess = async () =>{
                if(req.result === undefined){
                    throw new Error("Object with specified key not found");
                }

                const data = req.result;
                data._overallScore = newValue;

                const updateOverallScore = objectStore.put(data)

                updateOverallScore.onsuccess = () =>{
                    console.log("update worked")
                }
                updateOverallScore.onerror = () =>{
                    console.log("update didn't worked")
                }
            }

            req.onerror = () =>{
                console.log("getting object didn't work")
            }
        })()
    }
}
</code>```

Body:
I'm trying to create an object which when any properties are set would update its corresponding indexedDB data automatically.

The following code works as intended but each time that I'm calling the object from the indexedb. I need to create the object as

new
ResultsModel(indexedDbData._scores,indexedDbData._overallScore,indexedDbData.id)

Which seems an "anti-pattern" as I'm calling what would be "private" variables even if at this point it's just data.

Is that an issue?
I'm also not sure about setting up "setter" and "getter" ? Should I just create "update" function at this point ?

What would be a good pattern to achieve this ?

export class ResultsModel{
    constructor(scores,overallScore, id){
        this._scores = scores;
        this._overallScore = overallScore;
        this.id = id;
    }

    async init(){
        sessionStorage.setItem("lastResults", JSON.stringify(this));
        await this.save();
    }

    async save(){
        let req = await db.transaction("moodResults","readwrite").objectStore("moodResults").put(this);
        req.onsuccess = function(event) {console.log("saved")}
        req.onerror = function(event) {console.log("error")}
    }

    get scores(){
        return this._scores;
    }

    get overallScore(){
        return this._overallScore;
    }

    set scores(newValue){
        this._scores = newValue;
    }

    set overallScore(newValue){
        this._overallScore = newValue;
        if(this.overallScore === undefined){return}

        return (async () =>{
            let objectStore = await db.transaction("moodResults","readwrite").objectStore("moodResults");
            const req = await objectStore.get(parseInt(this.id));

            req.onsuccess = async () =>{
                if(req.result === undefined){
                    throw new Error("Object with specified key not found");
                }

                const data = req.result;
                data._overallScore = newValue;

                const updateOverallScore = objectStore.put(data)

                updateOverallScore.onsuccess = () =>{
                    console.log("update worked")
                }
                updateOverallScore.onerror = () =>{
                    console.log("update didn't worked")
                }
            }

            req.onerror = () =>{
                console.log("getting object didn't work")
            }
        })()
    }
}


问:
Install apk update from firbase | Android Kotlin
I have an android app that not on Google play and I want it to get updates using APK on the server.
This code is working and checks for updates by searching for APK on Firebase storage with greater version than the current build and ending it to download

```<code>    private fun checkUpdates(){
    val storage = FirebaseStorage.getInstance()
    val storageRef = storage.reference
    val rootRef = storageRef.root
    rootRef.listAll().addOnSuccessListener { listResult ->
        for (item in listResult.items) {
            // item is a StorageReference for a file
            val fileName = item.name
            val version = fileName.substring(fileName.indexOf("app_v") + 5, fileName.indexOf(".apk"))
            if (version.replace(".", "") > BuildConfig.VERSION_CODE.toString().replace(".", "")) {
                val builder = AlertDialog.Builder(this)
                builder.setMessage(R.string.new_up_av)
                builder.setPositiveButton(R.string.install) { _, _ ->
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_STORAGE
                        )
                        download(version)
                    } else {
                        download(version)
                    }
                }
                val dialog = builder.create()
                dialog.show()
            }
            else{
                Toast.makeText(this, R.string.no_updates, Toast.LENGTH_LONG).show()
            }
        }
    } .addOnFailureListener{
        Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show()
    }
}
</code>```

The download function is this (notice the comment on line 4):

```<code>    private fun download(version: String) {
    Toast.makeText(this, R.string.download_updates, Toast.LENGTH_SHORT).show()
    val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    val downloadUri = Uri.parse(//url for apk here.)
    val request = DownloadManager.Request(downloadUri)
        .setTitle(getString(R.string.download_updates))
        .setDescription(getString(R.string.app_name))
    val downloadId = downloadManager.enqueue(request)

    // Check if the download was successful
    if (downloadId == -1L) {
        // Download failed, show an error message
        Toast.makeText(this, "download failed", Toast.LENGTH_SHORT).show()
        return
    }

    // Listen for the download to complete and install the update
    val downloadReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (downloadId == id) {
                installApk(context, "app_v$version.apk")
            }
        }
    }
    registerReceiver(downloadReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}
</code>```

on line 4 i verified it works manually and the problems is showing also with sure-working APKs like WhatsApp.

the installApk function:

```<code>        fun installApk(context: Context, fileName: String) {
    val file = File(Environment.getExternalStorageDirectory().toString() + "/Download/" + filename)
    val fileUri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file)
    val intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
}
</code>```

provider in Manifest:

```<code>        <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android: resource="@xml/provider_paths" />
    </provider>
</code>```

provider_paths.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="downloads" path="Download/" />
</paths>
</code>```

The problem: seems like its downloading, starting to install, and than shows an error occurred while parsing the package message. no logs.
(It works manually)
I have tried many other ways buts I couldn't figure what cussing the problem.
If someone fammiliar with intalling apk programmatically I looking for help.

Body:
I have an android app that not on Google play and I want it to get updates using APK on the server.
This code is working and checks for updates by searching for APK on Firebase storage with greater version than the current build and ending it to download

    private fun checkUpdates(){
    val storage = FirebaseStorage.getInstance()
    val storageRef = storage.reference
    val rootRef = storageRef.root
    rootRef.listAll().addOnSuccessListener { listResult ->
        for (item in listResult.items) {
            // item is a StorageReference for a file
            val fileName = item.name
            val version = fileName.substring(fileName.indexOf("app_v") + 5, fileName.indexOf(".apk"))
            if (version.replace(".", "") > BuildConfig.VERSION_CODE.toString().replace(".", "")) {
                val builder = AlertDialog.Builder(this)
                builder.setMessage(R.string.new_up_av)
                builder.setPositiveButton(R.string.install) { _, _ ->
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_STORAGE
                        )
                        download(version)
                    } else {
                        download(version)
                    }
                }
                val dialog = builder.create()
                dialog.show()
            }
            else{
                Toast.makeText(this, R.string.no_updates, Toast.LENGTH_LONG).show()
            }
        }
    } .addOnFailureListener{
        Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show()
    }
}

The download function is this (notice the comment on line 4):

    private fun download(version: String) {
    Toast.makeText(this, R.string.download_updates, Toast.LENGTH_SHORT).show()
    val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    val downloadUri = Uri.parse(//url for apk here.)
    val request = DownloadManager.Request(downloadUri)
        .setTitle(getString(R.string.download_updates))
        .setDescription(getString(R.string.app_name))
    val downloadId = downloadManager.enqueue(request)

    // Check if the download was successful
    if (downloadId == -1L) {
        // Download failed, show an error message
        Toast.makeText(this, "download failed", Toast.LENGTH_SHORT).show()
        return
    }

    // Listen for the download to complete and install the update
    val downloadReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            if (downloadId == id) {
                installApk(context, "app_v$version.apk")
            }
        }
    }
    registerReceiver(downloadReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
}

on line 4 i verified it works manually and the problems is showing also with sure-working APKs like WhatsApp.

the installApk function:

        fun installApk(context: Context, fileName: String) {
    val file = File(Environment.getExternalStorageDirectory().toString() + "/Download/" + filename)
    val fileUri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file)
    val intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
}

provider in Manifest:

        <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android: resource="@xml/provider_paths" />
    </provider>

provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="downloads" path="Download/" />
</paths>

The problem: seems like its downloading, starting to install, and than shows an error occurred while parsing the package message. no logs.
(It works manually)
I have tried many other ways buts I couldn't figure what cussing the problem.
If someone fammiliar with intalling apk programmatically I looking for help.


问:
Logback NOT writing in log.txt
Problem Statement: Logback is printing in console properly but not in log.txt file. There are many solutions given in other pages but apparently none worked. Could someone help me in this regard?

Java:-

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log {

    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger("Example App");
        logger.info("'sup? I'm your info logger");
        logger.debug("hey HEY hey! I'm your debug logger");
    }
}
</code>```

Config:- logback-fileAppender.xml

<configuration>

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${project.basedir}/Log.txt</file>
    <append>true</append>

    <immediateFlush>true</immediateFlush>

    <encoder>
        <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
</appender>

<root level="DEBUG">
    <appender-ref ref="FILE" />
</root>
</configuration>
```

Expected:- The logs should be printed in log.txt

Actual:- The logs is not printed in log.txt

Note: I am using my customized directory structure in maven not the default provided by maven "src/main/resources".

Title: Logback NOT writing in log.txt

Body:
Problem Statement: Logback is printing in console properly but not in log.txt file. There are many solutions given in other pages but apparently none worked. Could someone help me in this regard?

Java:-

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log {

    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger("Example App");
        logger.info("'sup? I'm your info logger");
        logger.debug("hey HEY hey! I'm your debug logger");
    }
}

Config:- logback-fileAppender.xml

<configuration>

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${project.basedir}/Log.txt</file>
    <append>true</append>

    <immediateFlush>true</immediateFlush>

    <encoder>
        <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
</appender>

<root level="DEBUG">
    <appender-ref ref="FILE" />
</root>
</configuration>

Expected:- The logs should be printed in log.txt

Actual:- The logs is not printed in log.txt

Note: I am using my customized directory structure in maven not the default provided by maven "src/main/resources".


问:
Runtime ConcurrentModificationException in java

private static void deleteContact() {
    System.out.println("Please enter the name:");
    String name = scanner.next();
    if (name.equals("")) {
        System.out.println("!Please enter the name");
        deleteContact();
    } else {
        boolean doesExist = false;

        // line 182
        for (Contact c: contacts) {
            if (c.getName().equals(name)) {
                doesExist = true;
                contacts.remove(c);
            }
        }

        if (!doesExist) {
            System.out.println("There is no such contact");
        }
    }

    showInitialOptions();
}
```
```Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    at java.util.ArrayList$Itr.next(ArrayList.java:859)
    at org.neutral_networks.javaChallange.Main.deleteContact(Main.java:182)
```
<p>line 182 in my code mean, this for loop:</p>
<pre class="lang-java prettyprint-override"><code>        for (Contact c: contacts) {
            if (c.getName().equals(name)) {
                doesExist = true;
                contacts.remove(c);
            }
        }
</code>```

Please help me out to solve this exception.

i just build this deleteContact() method for remove contact from the contact list.

i am getting the input from the user and this is actually name of the contact which one users would like to remove from the contact list.

so, generally when i call the function and and give input it will causes the exit my program and say,, Exception in thread "main" java.util.ConcurrentModificationException

Body:
private static void deleteContact() {
    System.out.println("Please enter the name:");
    String name = scanner.next();
    if (name.equals("")) {
        System.out.println("!Please enter the name");
        deleteContact();
    } else {
        boolean doesExist = false;

        // line 182
        for (Contact c: contacts) {
            if (c.getName().equals(name)) {
                doesExist = true;
                contacts.remove(c);
            }
        }

        if (!doesExist) {
            System.out.println("There is no such contact");
        }
    }

    showInitialOptions();
}

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    at java.util.ArrayList$Itr.next(ArrayList.java:859)
    at org.neutral_networks.javaChallange.Main.deleteContact(Main.java:182)

line 182 in my code mean, this for loop:

        for (Contact c: contacts) {
            if (c.getName().equals(name)) {
                doesExist = true;
                contacts.remove(c);
            }
        }

Please help me out to solve this exception.

i just build this deleteContact() method for remove contact from the contact list.

i am getting the input from the user and this is actually name of the contact which one users would like to remove from the contact list.

so, generally when i call the function and and give input it will causes the exit my program and say,, Exception in thread "main" java.util.ConcurrentModificationException


问:
Chrome extension built to change textarea in a form keeps reverting
I'm building a Chrome extension to fill out a website form. The form includes a textarea field. I'm able to successfully change the textarea once, but when I click outside of the text area (for example, on to the next input field) the textarea reverts back to the original placeholder value.

Here's a quick overview of how the extension is working. There's a a pop up window for the user to input the description they want to end up in the form textarea and an autofill button. When the user inputs text and pressed autofill the inputted text appears once, but then reverts.

Here's my code:

Manifest.json

```<code>{
"manifest_version": 3,
    "name": "NW Chrome Extension",
    "description": "My first chrome extension",
    "version": "1.0",
    "action": {
        "default_popup": "ext/index.html",
        "default_icon": "assets/hello_extensions.png"
    },
    "background": {
        "service_worker": "welcome/background.js"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ]
}
</code>```

Index.html

```<code><HTML>
    <body>
        <input type="text" id="description" placeholder="Description">
        <button type="button" id="autofill">Fill</button>
        <script src="script.js"></script>
    </body>
</HTML>
</code>```

Script.js

```<code>document.getElementById("autofill").addEventListener("click", () => {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            description: document.getElementById('description').value,
        }, function(response) {
            console.log("error")
        })
    })
})
</code>```

Content.js

```<code>chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse, event) {
        try {
            document.getElementById("description").value = request.description

        } catch (error) {
            console.log(error)
            sendResponse({status: "Exception occurred!"})
        }
    }
)
</code>```

Here's a code snip from the website form:

I've tried a few things to get this working:

Changing content.js to use document.getElementById("description").innerHTML (rather than .value)

Adding return false to content.js to prevent the form from refreshing

Specifying the button type=button in indexhtml to prevent the form from refreshing

Body:
I'm building a Chrome extension to fill out a website form. The form includes a textarea field. I'm able to successfully change the textarea once, but when I click outside of the text area (for example, on to the next input field) the textarea reverts back to the original placeholder value.

Here's a quick overview of how the extension is working. There's a a pop up window for the user to input the description they want to end up in the form textarea and an autofill button. When the user inputs text and pressed autofill the inputted text appears once, but then reverts.

Here's my code:

Manifest.json

{
"manifest_version": 3,
    "name": "NW Chrome Extension",
    "description": "My first chrome extension",
    "version": "1.0",
    "action": {
        "default_popup": "ext/index.html",
        "default_icon": "assets/hello_extensions.png"
    },
    "background": {
        "service_worker": "welcome/background.js"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ]
}

Index.html

        <input type="text" id="description" placeholder="Description">
        <button type="button" id="autofill">Fill</button>

Script.js

document.getElementById("autofill").addEventListener("click", () => {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            description: document.getElementById('description').value,
        }, function(response) {
            console.log("error")
        })
    })
})

Content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse, event) {
        try {
            document.getElementById("description").value = request.description

        } catch (error) {
            console.log(error)
            sendResponse({status: "Exception occurred!"})
        }
    }
)

Here's a code snip from the website form:

I've tried a few things to get this working:

Changing content.js to use document.getElementById("description").innerHTML (rather than .value)

Adding return false to content.js to prevent the form from refreshing

Specifying the button type=button in indexhtml to prevent the form from refreshing


问:
Is it possible to launch following celery commands from same terminal?
Is it possible to execute following two commands back to back in the same terminal window? I am getting celery output after executing the first one and there's no way to execute the next one without pressing "ctrl+C".

```<code># For too long queue
celery --app=proj_name worker -Q too_long_queue -c 2
# For quick queue
celery --app=proj_name worker -Q quick_queue -c 2
</code>```

My objective is to start a set of workers, each with a different concurreny, queue and loglevel. So far, I have found "celery multi" to do this but that doesn't give terminal outputs. What are my other options?

Body:
Is it possible to execute following two commands back to back in the same terminal window? I am getting celery output after executing the first one and there's no way to execute the next one without pressing "ctrl+C".

# For too long queue
celery --app=proj_name worker -Q too_long_queue -c 2
# For quick queue
celery --app=proj_name worker -Q quick_queue -c 2

My objective is to start a set of workers, each with a different concurreny, queue and loglevel. So far, I have found "celery multi" to do this but that doesn't give terminal outputs. What are my other options?


问:
Node.js — Google OAuth 2.0 for Web Server Applications -> How to use the token event
I'm trying to figure out how to use the token event as specified in Google's OAuth 2.0 documentation for server side applications (using Node.js):

Here's the code for the token event:

```<code>oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in your secure persistent database
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});
</code>```

I actually get this event to fire, but am unsure about when to check for a valid token. If I do this one every request (let's say Google Docs API request), the token event fires after I'm requesting the API, so credentials are not set correctly.

How would you go about making sure that the correct access token is set BEFORE making a request?

Google says "Once the client has a refresh token, access tokens will be acquired and refreshed automatically in the next call to the API.", which is also kind of the case, but too late.

So my question once again: How do I, in my call, wait for the token event to finish updating my access token in order to set credentials BEFORE making the request?

Thank you!

Body:
I'm trying to figure out how to use the token event as specified in Google's OAuth 2.0 documentation for server side applications (using Node.js):

Here's the code for the token event:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in your secure persistent database
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});

I actually get this event to fire, but am unsure about when to check for a valid token. If I do this one every request (let's say Google Docs API request), the token event fires after I'm requesting the API, so credentials are not set correctly.

How would you go about making sure that the correct access token is set BEFORE making a request?

Google says "Once the client has a refresh token, access tokens will be acquired and refreshed automatically in the next call to the API.", which is also kind of the case, but too late.

So my question once again: How do I, in my call, wait for the token event to finish updating my access token in order to set credentials BEFORE making the request?

Thank you!


问:
I want to draw a graph with type "QGraphicsView" on a window with type "QWidget"
I have an application with a window with the type "QWidget" like this.

```<code>from sys import exit, argv
from PyQt6.QtCore import QRectF, Qt, QTimer
from PyQt6.QtGui import QBrush, QColor, QMouseEvent, QPainter, QPen, QPaintEvent
from PyQt6.QtWidgets import QApplication, QWidget, QGraphicsView
from PyQt6.QtGui import QVector2D

targetPoint = QVector2D(1920/2, 120)
startPoint = QVector2D(1920/2, 1080 - 120)
barriers = {1:[690, 1080/2-30, 540, 60],
            2:[0-30, 0-30, 1920+60, 0+60],
            3:[0-30, 1080-30, 1920+60, 0+60],
            4:[0-30, 0+30, 0+60, 1080-60],
            5:[1920-30, 0+30, 0+60, 1080-60]}

class Window(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.framePerSecond = 60
        self.seconds = 0
        self.minutes = 0
        self.hours = 0
        self.clockCounterVariable = 0
        self.painter = QPainter(self)
        self.setWindowTitle("PyQt5 Drawing Tutorial")
        self.setGeometry(0, 0, 1920, 1080)
        self.setStyleSheet("background-color:rgb(20, 20, 20);font-size:20px;")
        self.showFullScreen()
        self.baseTimer = QTimer(self)
        self.baseTimer.timeout.connect(self.run)
        self.baseTimer.start(round((1/self.framePerSecond)*1000))
        self.clock = QTimer(self)
        self.clock.timeout.connect(self.clockCounter)
        self.clock.start(1000)

    def clockCounter(self) -> None:
        self.clockCounterVariable += 1

    def run(self) -> None:
        self.update()

    def mousePressEvent(self, a0: QMouseEvent) -> super:
        global running
        if running:
            print("pause process")
            running = False
            self.baseTimer.stop()
            self.clock.stop()
        else:
            print("continue process")
            running = True
            self.baseTimer.start(10)
            self.clock.start(1000)
        return super().mousePressEvent(a0)

    def paintEvent(self, a0: QPaintEvent) -> super:
        self.painter.begin(self)
        self.painter.setPen(QPen(QColor(20, 20, 20), -1, Qt.PenStyle.SolidLine))
        self.painter.setBrush(QBrush(QColor(80, 80, 80), Qt.BrushStyle.SolidPattern))
        for barrier in barriers:
            self.painter.drawRect(QRectF(barriers[barrier][0], barriers[barrier][1], barriers[barrier][2], barriers[barrier][3]))
        self.painter.setPen(QPen(QColor(30, 30, 30),  0, Qt.PenStyle.SolidLine))
        self.painter.setPen(QPen(QColor(20, 20, 20),  -1, Qt.PenStyle.SolidLine))
        self.painter.setBrush(QBrush(QColor(150, 30, 150), Qt.BrushStyle.SolidPattern))
        self.painter.drawEllipse(int(startPoint.x()-12), int(startPoint.y()-12), int(24), int(24))
        self.painter.setBrush(QBrush(QColor(150, 0, 0), Qt.BrushStyle.SolidPattern))
        self.painter.drawEllipse(int(targetPoint.x()-12), int(targetPoint.y()-12), int(24), int(24))
        self.painter.setPen(QPen(QColor(255, 128, 0), 1, Qt.PenStyle.SolidLine))
        self.seconds = self.clockCounterVariable
        self.minutes, self.seconds = divmod(self.seconds, 60)
        self.hours, self.minutes = divmod(self.minutes, 60)
        self.painter.drawText(QRectF(35, 30, 400, 30), Qt.AlignmentFlag.AlignLeft, "%02d : %02d : %02d" % (self.hours, self.minutes, self.seconds))
        self.painter.end()
        return super().paintEvent(a0)

    def closeWindow(self) -> None:
        print("closing window ...")
        exit(0)

if __name__ == "__main__":
    App = QApplication(argv)
    window = Window()
    try:
        exit(App.exec())
    except SystemExit:
        window.closeWindow()
</code>```

that shows something like this.

I want to draw a graph at the right-bottom corner of this with 400px width and 300px height
I know I must use "QGraphicsView" but how can I show it? how to plot it?

I want to draw a graph with type "QGraphicsView" on a window with type "QWidget".

How should I do that?

Body:
I have an application with a window with the type "QWidget" like this.

from sys import exit, argv
from PyQt6.QtCore import QRectF, Qt, QTimer
from PyQt6.QtGui import QBrush, QColor, QMouseEvent, QPainter, QPen, QPaintEvent
from PyQt6.QtWidgets import QApplication, QWidget, QGraphicsView
from PyQt6.QtGui import QVector2D

targetPoint = QVector2D(1920/2, 120)
startPoint = QVector2D(1920/2, 1080 - 120)
barriers = {1:[690, 1080/2-30, 540, 60],
            2:[0-30, 0-30, 1920+60, 0+60],
            3:[0-30, 1080-30, 1920+60, 0+60],
            4:[0-30, 0+30, 0+60, 1080-60],
            5:[1920-30, 0+30, 0+60, 1080-60]}

class Window(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.framePerSecond = 60
        self.seconds = 0
        self.minutes = 0
        self.hours = 0
        self.clockCounterVariable = 0
        self.painter = QPainter(self)
        self.setWindowTitle("PyQt5 Drawing Tutorial")
        self.setGeometry(0, 0, 1920, 1080)
        self.setStyleSheet("background-color:rgb(20, 20, 20);font-size:20px;")
        self.showFullScreen()
        self.baseTimer = QTimer(self)
        self.baseTimer.timeout.connect(self.run)
        self.baseTimer.start(round((1/self.framePerSecond)*1000))
        self.clock = QTimer(self)
        self.clock.timeout.connect(self.clockCounter)
        self.clock.start(1000)

    def clockCounter(self) -> None:
        self.clockCounterVariable += 1

    def run(self) -> None:
        self.update()

    def mousePressEvent(self, a0: QMouseEvent) -> super:
        global running
        if running:
            print("pause process")
            running = False
            self.baseTimer.stop()
            self.clock.stop()
        else:
            print("continue process")
            running = True
            self.baseTimer.start(10)
            self.clock.start(1000)
        return super().mousePressEvent(a0)

    def paintEvent(self, a0: QPaintEvent) -> super:
        self.painter.begin(self)
        self.painter.setPen(QPen(QColor(20, 20, 20), -1, Qt.PenStyle.SolidLine))
        self.painter.setBrush(QBrush(QColor(80, 80, 80), Qt.BrushStyle.SolidPattern))
        for barrier in barriers:
            self.painter.drawRect(QRectF(barriers[barrier][0], barriers[barrier][1], barriers[barrier][2], barriers[barrier][3]))
        self.painter.setPen(QPen(QColor(30, 30, 30),  0, Qt.PenStyle.SolidLine))
        self.painter.setPen(QPen(QColor(20, 20, 20),  -1, Qt.PenStyle.SolidLine))
        self.painter.setBrush(QBrush(QColor(150, 30, 150), Qt.BrushStyle.SolidPattern))
        self.painter.drawEllipse(int(startPoint.x()-12), int(startPoint.y()-12), int(24), int(24))
        self.painter.setBrush(QBrush(QColor(150, 0, 0), Qt.BrushStyle.SolidPattern))
        self.painter.drawEllipse(int(targetPoint.x()-12), int(targetPoint.y()-12), int(24), int(24))
        self.painter.setPen(QPen(QColor(255, 128, 0), 1, Qt.PenStyle.SolidLine))
        self.seconds = self.clockCounterVariable
        self.minutes, self.seconds = divmod(self.seconds, 60)
        self.hours, self.minutes = divmod(self.minutes, 60)
        self.painter.drawText(QRectF(35, 30, 400, 30), Qt.AlignmentFlag.AlignLeft, "%02d : %02d : %02d" % (self.hours, self.minutes, self.seconds))
        self.painter.end()
        return super().paintEvent(a0)

    def closeWindow(self) -> None:
        print("closing window ...")
        exit(0)

if __name__ == "__main__":
    App = QApplication(argv)
    window = Window()
    try:
        exit(App.exec())
    except SystemExit:
        window.closeWindow()

that shows something like this.

I want to draw a graph at the right-bottom corner of this with 400px width and 300px height
I know I must use "QGraphicsView" but how can I show it? how to plot it?

I want to draw a graph with type "QGraphicsView" on a window with type "QWidget".

How should I do that?


问:
Keep getting 403 when trying to get the authenticated user's email twitter api
I'm trying to get the user's email when they login so I can add it to their user document however whenever I use the await client.v1.verifyCredentials({ include_email: true }); it always returns a 403 with a message saying You are not permitted to use OAuth2 on this endpoint.

I'm using the twitter-api-v2 node.js library and using OAuth2 to login the users.

Here's the full code for more context:

```<code>let client, accessToken, refreshToken;
  try {
    const data = await twitter.loginWithOAuth2({
      code,
      codeVerifier: token.codeVerifier,
      redirectUri: callbackUrl,
    });

    client = data.client;
    accessToken = data.accessToken;
    refreshToken = data.refreshToken;
  } catch (err) {
    console.error(err);
    return res.status(400).json({ msg: "Twitter tokens have expired." });
  }

  let data;
  try {
    const response = await client.v2.me({
      "user.fields": ["profile_image_url"],
    });
    data = response.data;
  } catch (err) {
    console.error(err);
    return res
      .status(500)
      .json({ msg: "Failed to get your account from Twitter!" });
  }

  // here is the problem
  try {
    const response = await client.v1.verifyCredentials({ include_email: true });
    console.log(response);
  } catch (err) {
    console.error(err);
    return res
      .status(500)
      .json({ msg: "Failed to get your email from Twitter!" });
  }
</code>```

I have a feeling that maybe I'm not using the right permissions on the twitter developer dashboard (although I am requesting the user's email in the dashboard) or I'm not requesting the correct scopes when the OAuth link is generated so does anyone have a suggestion about how I can continue?

Thanks in advance!

Body:
I'm trying to get the user's email when they login so I can add it to their user document however whenever I use the await client.v1.verifyCredentials({ include_email: true }); it always returns a 403 with a message saying You are not permitted to use OAuth2 on this endpoint.

I'm using the twitter-api-v2 node.js library and using OAuth2 to login the users.

Here's the full code for more context:

let client, accessToken, refreshToken;
  try {
    const data = await twitter.loginWithOAuth2({
      code,
      codeVerifier: token.codeVerifier,
      redirectUri: callbackUrl,
    });

    client = data.client;
    accessToken = data.accessToken;
    refreshToken = data.refreshToken;
  } catch (err) {
    console.error(err);
    return res.status(400).json({ msg: "Twitter tokens have expired." });
  }

  let data;
  try {
    const response = await client.v2.me({
      "user.fields": ["profile_image_url"],
    });
    data = response.data;
  } catch (err) {
    console.error(err);
    return res
      .status(500)
      .json({ msg: "Failed to get your account from Twitter!" });
  }

  // here is the problem
  try {
    const response = await client.v1.verifyCredentials({ include_email: true });
    console.log(response);
  } catch (err) {
    console.error(err);
    return res
      .status(500)
      .json({ msg: "Failed to get your email from Twitter!" });
  }

I have a feeling that maybe I'm not using the right permissions on the twitter developer dashboard (although I am requesting the user's email in the dashboard) or I'm not requesting the correct scopes when the OAuth link is generated so does anyone have a suggestion about how I can continue?

Thanks in advance!


问:
Accessing URL to use issues (expo/react native app/firebase)
In my current app i want the user to pick a photo from their phone and then to use the downloadable url from firebase storage to then add it to my database.  Everything works but when a user(when they first time to pick a image) it says

TypeError:  Network request failed

code(logic/state/functions):

```<code>    const [image, setImage] = useState(null);
  const [url, setUrl] = useState(null)
  async function postImage () {
    try {
      // No permissions request is necessary for launching the image library
         let result = await ImagePicker.launchImageLibraryAsync({
           mediaTypes: ImagePicker.MediaTypeOptions.All,
           allowsEditing: true,
           aspect: [4, 3],
           quality: 1,
         });

         if (!result.canceled) {
          imgFirebase()
          setImage(result.assets[0].uri);         }

         }
         catch(E) {
          Alert.alert(
            "Alert Title",
            "My Alert Msg 1",
            [
              {
                text: "Cancel",
                onPress: () => console.log("Cancel Pressed"),
                style: "cancel"
              },
              { text: "OK", onPress: () => console.log("OK Pressed") }
            ]
          );
         }
  }

  async function imgFirebase () {
    try {
      console.log(image);
     const d = await fetch(image)
    const dd = await d.blob()
    const fileName = image.substring(image.lastIndexOf("/")+1)
    const storage = getStorage();
   const storageRef = ref(storage, fileName);
   uploadBytes(storageRef,dd).then((snapshot) => {
     getDownloadURL(snapshot.ref).then(async (url) => {

       // Create a query against the collection.
       setUrl(url)
       console.log(url)
 }).catch(e=>{
  Alert.alert(
    "Alert Title",
    "My Alert Msg 2",
    [
      {
        text: "Cancel",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel"
      },
      { text: "OK", onPress: () => console.log("OK Pressed") }
    ]
  );
 })
   });
    }
    catch(e) {
     alert(e)
    }
   }
</code>```

code(for rendered UI):

```<code> <Pressable color="#000" style={{marginTop:20,backgroundColor:"#FF35F0",padding:10,borderRadius:11,color:"#000"}} onPress={postImage}>
      <Text style={{color:"#fff",textAlign:"center",fontSize:20}}>Pick Image</Text>
    </Pressable>
</code>```

whats also weird is that after the first time getting this error and then trying to pick a image the error finally goes away.  Why does this error come up at first?  How would i fix this?

Body:
In my current app i want the user to pick a photo from their phone and then to use the downloadable url from firebase storage to then add it to my database.  Everything works but when a user(when they first time to pick a image) it says

TypeError:  Network request failed

code(logic/state/functions):

    const [image, setImage] = useState(null);
  const [url, setUrl] = useState(null)
  async function postImage () {
    try {
      // No permissions request is necessary for launching the image library
         let result = await ImagePicker.launchImageLibraryAsync({
           mediaTypes: ImagePicker.MediaTypeOptions.All,
           allowsEditing: true,
           aspect: [4, 3],
           quality: 1,
         });

         if (!result.canceled) {
          imgFirebase()
          setImage(result.assets[0].uri);         }

         }
         catch(E) {
          Alert.alert(
            "Alert Title",
            "My Alert Msg 1",
            [
              {
                text: "Cancel",
                onPress: () => console.log("Cancel Pressed"),
                style: "cancel"
              },
              { text: "OK", onPress: () => console.log("OK Pressed") }
            ]
          );
         }
  }

  async function imgFirebase () {
    try {
      console.log(image);
     const d = await fetch(image)
    const dd = await d.blob()
    const fileName = image.substring(image.lastIndexOf("/")+1)
    const storage = getStorage();
   const storageRef = ref(storage, fileName);
   uploadBytes(storageRef,dd).then((snapshot) => {
     getDownloadURL(snapshot.ref).then(async (url) => {

       // Create a query against the collection.
       setUrl(url)
       console.log(url)
 }).catch(e=>{
  Alert.alert(
    "Alert Title",
    "My Alert Msg 2",
    [
      {
        text: "Cancel",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel"
      },
      { text: "OK", onPress: () => console.log("OK Pressed") }
    ]
  );
 })
   });
    }
    catch(e) {
     alert(e)
    }
   }

code(for rendered UI):

 <Pressable color="#000" style={{marginTop:20,backgroundColor:"#FF35F0",padding:10,borderRadius:11,color:"#000"}} onPress={postImage}>
      <Text style={{color:"#fff",textAlign:"center",fontSize:20}}>Pick Image</Text>
    </Pressable>

whats also weird is that after the first time getting this error and then trying to pick a image the error finally goes away.  Why does this error come up at first?  How would i fix this?


问:
How can I dynamically store the height of a changing React component?
```<code>function Test(){
const [height, setHeight] = useState(0);

  const myRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);
return(
<div ref = {myRef}>...</div>
)
}
</code>```

This code does update the height on the first render/mount but when I change the window height, nothing happens. How can I make it update the height like I'd expect? I've also tried useEffect.
This div is inside of another div and it is set to height : 100%.

Body:
function Test(){
const [height, setHeight] = useState(0);

  const myRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  }, []);
return(

...

)
}

This code does update the height on the first render/mount but when I change the window height, nothing happens. How can I make it update the height like I'd expect? I've also tried useEffect.
This div is inside of another div and it is set to height : 100%.


问:
How can I fix this Nested For Loop script (R) to estimate Model Ages
I'm new to R (and coding in general). The data itself is taken from lead isotope analysis and are lead isotopes.

I was hoping to create a nested for loop which compared the output of an equation to a vertex of integers calculated from sample data.

I can see two issues but I don't know how to address them:
(1): '1:length(num_intervals))' references an integer but perhaps should be a series or a list (?)

(2): the output of the loop overwrites the ModelAge function.

Any help would be much appreciated.

```<code>
#Data for Testing. For obvious reasons, I can't include all my data but here are some samples to create a sample file to compile:

47      18.54400       15.590       38.427
48      18.55900       15.580       38.403
49      18.48100       15.600       38.407
50      18.37400       15.614       38.293
51      19.23800       15.673       37.272
52      18.14200       15.649       38.137
53      18.52500       15.590       38.430
54      18.55000       15.597       38.468
55      18.59200       15.662       37.972
56      18.59500       15.662       37.972
57      18.50000       15.594       38.402

#Model Age Estimations
rm(list = ls())
#library(dplyr)

#assumptions

#growth constant assumptions
decay_constant_u238 <- 1.55125E-10
decay_constant_u235 <- 9.8485E-10
decay_constant_th232 <- 4.9475E-11

#time assumptions
age_of_earth_t0 <- 4.57E9
age_of_earth_t1 <- 3.7E9

#Isotopic Assumptions - Stage 1
s1_206PB.204PB <- 9.307
s1_207PB.204PB <- 10.294
s1_208PB.204PB <- 29.476

#Isotopic Assumptions - Stage 2 (Stacey & Kramer 1975)
s2_206PB.204PB <- 11.152
s2_207PB.204PB <- 12.998
s2_208PB.204PB <- 31.230

#Isotopic Proportion Assumptions - Stage 1 (Stacey & Kramer 1975)
s1_u <- 7.19
s1_w <- 32.21
s1_k <- 4.479833102

#Isotopic Proportion Assumptions - Stage 2 (Stacey & Kramer 1975)
s2_u <- 9.74
s2_w <- 37.19
s2_k <- 3.818275154

#µ or 238U/204Pb Estimates
uranium_lead_ratio_estimates <- matrix(6:12, nrow=7, ncol=1)

#slope
slopes <-(values_207.204-s2_207PB.204PB)/(values_206.204-s2_206PB.204PB)*137.88

model_age <- data.frame(A=ingots$X206Pb.204Pb, B=ingots$X207Pb.204Pb, C=ingots$X208Pb.204Pb, Slopes=slopes, ModelAge = 1:length(ingots$X206Pb.204Pb))

#Calculated Ages
Ages_new <- 1:4 *10000000
last <- Ages_new[length(Ages_new)]
add_val <- 10000000
n_adds <- 70
Ages <- cumsum(c(last, rep(add_val, n_adds)))

#Function
ModelAgeFunction <- function(Ages){
  (exp(decay_constant_u235*age_of_earth_t1)-exp(decay_constant_u235*Ages))/(exp(decay_constant_u238*age_of_earth_t1)-exp(decay_constant_u238*Ages))
}

#Iteration
lower_bound <- 0
upper_bound <- 700000000
num_intervals <- 70
interval_width <- (upper_bound - lower_bound) / num_intervals

#Vector of Slopes
slopes <- model_age$Slopes

#Integration
for (i in 1:length(slopes))
{
  for (j in 1:length(num_intervals))
  {
    left_bound <- lower_bound + interval_width*(i-1)
    if (slopes[i] < ModelAgeFunction(left_bound + interval_width / 2))
    {
      model_age$ModelAge[j] <- (left_bound + interval_width / 2)
      break
    }

  }
}

</code>```

Body:
I'm new to R (and coding in general). The data itself is taken from lead isotope analysis and are lead isotopes.

I was hoping to create a nested for loop which compared the output of an equation to a vertex of integers calculated from sample data.

I can see two issues but I don't know how to address them:
(1): '1:length(num_intervals))' references an integer but perhaps should be a series or a list (?)

(2): the output of the loop overwrites the ModelAge function.

Any help would be much appreciated.

#Data for Testing. For obvious reasons, I can't include all my data but here are some samples to create a sample file to compile:

47      18.54400       15.590       38.427
48      18.55900       15.580       38.403
49      18.48100       15.600       38.407
50      18.37400       15.614       38.293
51      19.23800       15.673       37.272
52      18.14200       15.649       38.137
53      18.52500       15.590       38.430
54      18.55000       15.597       38.468
55      18.59200       15.662       37.972
56      18.59500       15.662       37.972
57      18.50000       15.594       38.402

#Model Age Estimations
rm(list = ls())
#library(dplyr)

#assumptions

#growth constant assumptions
decay_constant_u238 <- 1.55125E-10
decay_constant_u235 <- 9.8485E-10
decay_constant_th232 <- 4.9475E-11

#time assumptions
age_of_earth_t0 <- 4.57E9
age_of_earth_t1 <- 3.7E9

#Isotopic Assumptions - Stage 1
s1_206PB.204PB <- 9.307
s1_207PB.204PB <- 10.294
s1_208PB.204PB <- 29.476

#Isotopic Assumptions - Stage 2 (Stacey & Kramer 1975)
s2_206PB.204PB <- 11.152
s2_207PB.204PB <- 12.998
s2_208PB.204PB <- 31.230

#Isotopic Proportion Assumptions - Stage 1 (Stacey & Kramer 1975)
s1_u <- 7.19
s1_w <- 32.21
s1_k <- 4.479833102

#Isotopic Proportion Assumptions - Stage 2 (Stacey & Kramer 1975)
s2_u <- 9.74
s2_w <- 37.19
s2_k <- 3.818275154

#µ or 238U/204Pb Estimates
uranium_lead_ratio_estimates <- matrix(6:12, nrow=7, ncol=1)

#slope
slopes <-(values_207.204-s2_207PB.204PB)/(values_206.204-s2_206PB.204PB)*137.88

model_age <- data.frame(A=ingots$X206Pb.204Pb, B=ingots$X207Pb.204Pb, C=ingots$X208Pb.204Pb, Slopes=slopes, ModelAge = 1:length(ingots$X206Pb.204Pb))

#Calculated Ages
Ages_new <- 1:4 *10000000
last <- Ages_new[length(Ages_new)]
add_val <- 10000000
n_adds <- 70
Ages <- cumsum(c(last, rep(add_val, n_adds)))

#Function
ModelAgeFunction <- function(Ages){
  (exp(decay_constant_u235*age_of_earth_t1)-exp(decay_constant_u235*Ages))/(exp(decay_constant_u238*age_of_earth_t1)-exp(decay_constant_u238*Ages))
}

#Iteration
lower_bound <- 0
upper_bound <- 700000000
num_intervals <- 70
interval_width <- (upper_bound - lower_bound) / num_intervals

#Vector of Slopes
slopes <- model_age$Slopes

#Integration
for (i in 1:length(slopes))
{
  for (j in 1:length(num_intervals))
  {
    left_bound <- lower_bound + interval_width*(i-1)
    if (slopes[i] < ModelAgeFunction(left_bound + interval_width / 2))
    {
      model_age$ModelAge[j] <- (left_bound + interval_width / 2)
      break
    }

  }
}


问:
postgres two version but psql always point to one
I am having difficulties to understand how to upgrade from postgres 13 to 15 but I don't understand the process

What I did so far is I install postgres 15 so I have two version running on windows (13 -> port 5432 and 15-> port 5433)
I have pg_dump my database for backup

what I am trying to do now is to create the new database on postgres15

I have removed the PATH directory pointed to postgres 13. I have nothing now

But I dont understand my following actions below:
I go into the bin directory for postgres15 and I type psql -V I have postgres15 version
However when i try to createdb namedatabase it always point to postgres13 for some reasons

Please help to upgrade my knowledge


问:
How to show excerpt on home page listing on blogger.com?
I want to show excerpt instead of full post content on the home page post listing on my blog https://florida-psychics.blogspot.com/. I've been searching for solution but can't find any. I remember it can be done in the theme editor but I can't find that solution anywhere. How do I do it?

I tried checking the theme settings but there is no option. I checked the code but can't figure out where to change it.


问:
By using node js module (http) how next terminal path can be show
why the next path cant be show and what is the commond to show the next line path?

i tried next module but this path cant be updated


问:
Why doesn't the indirect effect equal the ACME in the mediation analysis?
I am using the mediation package and following along to this guide:

https://towardsdatascience.com/doing-and-reporting-your-first-mediation-analysis-in-r-2fe423b92171

As you can tell from the guide, when they multiplied the coefficient from the coefficients from the second and third regression analyses, they get the indirect effect that shows up as the ACME when they use the mediation package.

Looking at one of the examples on this page:

https://www.rdocumentation.org/packages/mediation/versions/4.5.0/topics/mediate

```<code>data(jobs)

jobs$job_disc <- as.factor(jobs$job_disc)
b.ord <- polr(job_disc ~ treat + econ_hard + sex + age, data=jobs,
              method="probit", Hess=TRUE)
summary(b.ord)
d.bin <- glm(work1 ~ treat + job_disc + econ_hard + sex + age, data=jobs,
             family=binomial(link="probit"))
summary(d.bin)
ordbin <- mediate(b.ord, d.bin, sims=50, treat="treat", mediator="job_disc")
summary(ordbin)
</code>```

The coefficient for treat in b.ord (IV and mediator) is 0.0758280. The coefficient for job_disc in b.bin (mediator and DV) is -0.02773. When I multiply the two numbers I get 0.0758280*-0.02773 = -0.00210271, which is the indirect effect.

When I run the mediation analysis, the ACME doesn't match the indirect effect. What do I have to gather from the previous analyses in order to obtain the ACME that matches with the coefficients in the mediation analysis? Since the first regression is a polr and the second is glm, I would assume that needs to be addressed, but I'm not sure what. Any guidance would be appreciated.

Body:
I am using the mediation package and following along to this guide:

https://towardsdatascience.com/doing-and-reporting-your-first-mediation-analysis-in-r-2fe423b92171

As you can tell from the guide, when they multiplied the coefficient from the coefficients from the second and third regression analyses, they get the indirect effect that shows up as the ACME when they use the mediation package.

Looking at one of the examples on this page:

https://www.rdocumentation.org/packages/mediation/versions/4.5.0/topics/mediate

data(jobs)

jobs$job_disc <- as.factor(jobs$job_disc)
b.ord <- polr(job_disc ~ treat + econ_hard + sex + age, data=jobs,
              method="probit", Hess=TRUE)
summary(b.ord)
d.bin <- glm(work1 ~ treat + job_disc + econ_hard + sex + age, data=jobs,
             family=binomial(link="probit"))
summary(d.bin)
ordbin <- mediate(b.ord, d.bin, sims=50, treat="treat", mediator="job_disc")
summary(ordbin)

The coefficient for treat in b.ord (IV and mediator) is 0.0758280. The coefficient for job_disc in b.bin (mediator and DV) is -0.02773. When I multiply the two numbers I get 0.0758280*-0.02773 = -0.00210271, which is the indirect effect.

When I run the mediation analysis, the ACME doesn't match the indirect effect. What do I have to gather from the previous analyses in order to obtain the ACME that matches with the coefficients in the mediation analysis? Since the first regression is a polr and the second is glm, I would assume that needs to be addressed, but I'm not sure what. Any guidance would be appreciated.


问:
How to find matching audio sample within a wave file sliding window
I have an algorithm that should be able to tell a repeat in an audio. I used sliding window to implement this. The issue with this algorithm that I'm having is it works perfectly when I create a Sin_tone, but when I take a wav file and I concatenate it with itself, it will never recognize that second half. for some reason, the second half has different sample numbers than the first half.

The main question is why would concatenating a wave file of the exact same audio cuz the samples to be different at those two points (I concatenated using Adobe audition and Adobe audacity

I can get a double[] array of all the samples, but should I run a DFT on the sections of the sample and then compare them?

This takes a beat that I concatenated so I knew for sure there was an exact repeat, and it still fails, but when I use a sin tone I created then it can find the loop successfully

```<code>package Waves;

public class FindAudioAttempt2 {

    public static void main(String[] args)
    {
        WavFile wavFile;
        double[] buffer;
        try
        {
            // Open the wav file specified as the first argument
            wavFile = WavFile.openWavFile(new File("beat_on_repeat2.wav"));

            // Display information about the wav file
            wavFile.display();

            // Find a matching loop that is 0.2 seconds
            int numFramesinCut = (int) (0.2* wavFile.getSampleRate());
            System.out.println("num frames in cut: " +numFramesinCut);
            long numFrames = wavFile.getNumFrames();
            // Create a buffer of half the frames
            int framesRead;
            // buffer size is 2 * the number of frames since it is stereo
            buffer = new double[(int) (numFrames)*2];
            framesRead = wavFile.readFrames(buffer, (int)numFrames);

            System.out.println("Buffer Length: " +buffer.length);

            HashMap<Double, ArrayList<Integer>> savedPoints = new HashMap<>();

                // Read frames into buffer

            int endPointer = buffer.length-1;
            int beginPointer = 0;
            boolean dictComplete = false;
            boolean found = false;
            for(int i=buffer.length-1-numFramesinCut; i>buffer.length/2; i--){
                if(dictComplete){
                    if(!savedPoints.containsKey(buffer[i])){
                        continue;
                    }
                    ArrayList<Integer> pointers = savedPoints.get(buffer[i]);
                    for (int p:pointers) {
                        found = checkLoops(buffer,i,p, numFramesinCut);
                        if(found){
                            beginPointer = p;
                            endPointer = i;
                            break;
                        }
                    }
                    if(found){
                        break;
                    }

                } else {
                    for (int j = 0; j < buffer.length/2; j++) {
                        handleDict(savedPoints,buffer[j],j);
                        if(buffer[i] == buffer[i]){
                            found = checkLoops(savedPoints,buffer, i,j,numFramesinCut);
                        }
                        if(found){
                            beginPointer = j;
                            endPointer = i;
                            break;
                        }

                        if(j == buffer.length/2 -1){
                            dictComplete = true;
                        }
                    }
                }
                if(found){
                    break;
                }
            }

            int sampleRate = (int)wavFile.getSampleRate();

            WavFile wavFile2 = WavFile.newWavFile(new File("beatLooping.wav"), 2, numFrames/2, 16, sampleRate);

            double[] bufferFinal = new double[endPointer-beginPointer];
            System.out.println("Final Buffer Length: " +bufferFinal.length);

            System.arraycopy(buffer, buffer.length/2 -1, bufferFinal, 0, buffer.length/2);

            wavFile2.writeFrames(bufferFinal, (endPointer-beginPointer)/2);

            // Close the wavFile
            wavFile.close();
            wavFile2.close();
        }
        catch (Exception e)
        {
           e.printStackTrace();
        }

    }

    static private boolean checkLoops(HashMap<Double, ArrayList<Integer>> savedPoints, double[] buffer, int i, int j, int framesinCut){
        int frameCount =1;
        while(frameCount < framesinCut && i<buffer.length && j<buffer.length/2){
            handleDict(savedPoints, buffer[j], j);

            if(buffer[i] != buffer[j]){
                return false;
            }
            i = i+2;
            j = j+2;
            frameCount++;
        }
        if(frameCount == framesinCut){
            return true;
        } else {
            return false;
        }
    }

    static private boolean checkLoops( double[] buffer, int i, int j, int framesinCut){
        int frameCount =1;
        while(frameCount < framesinCut && i<buffer.length && j<buffer.length/2){

            if(buffer[i] != buffer[j]){
                return false;
            }
            i = i+1;
            j = j+1;
            frameCount++;
        }
        if(frameCount == framesinCut){
            return true;
        } else {
            return false;
        }

    }

    static public void handleDict(HashMap<Double, ArrayList<Integer>> dict, Double key, int pointer){
        if(dict.containsKey(key)){
            dict.get(key).add(pointer);
        } else {
            dict.put(key,new ArrayList<Integer>(){{add(pointer);}});
        }
    }

}
</code>```

Body:
I have an algorithm that should be able to tell a repeat in an audio. I used sliding window to implement this. The issue with this algorithm that I'm having is it works perfectly when I create a Sin_tone, but when I take a wav file and I concatenate it with itself, it will never recognize that second half. for some reason, the second half has different sample numbers than the first half.

The main question is why would concatenating a wave file of the exact same audio cuz the samples to be different at those two points (I concatenated using Adobe audition and Adobe audacity

I can get a double[] array of all the samples, but should I run a DFT on the sections of the sample and then compare them?

This takes a beat that I concatenated so I knew for sure there was an exact repeat, and it still fails, but when I use a sin tone I created then it can find the loop successfully

package Waves;

public class FindAudioAttempt2 {

    public static void main(String[] args)
    {
        WavFile wavFile;
        double[] buffer;
        try
        {
            // Open the wav file specified as the first argument
            wavFile = WavFile.openWavFile(new File("beat_on_repeat2.wav"));

            // Display information about the wav file
            wavFile.display();

            // Find a matching loop that is 0.2 seconds
            int numFramesinCut = (int) (0.2* wavFile.getSampleRate());
            System.out.println("num frames in cut: " +numFramesinCut);
            long numFrames = wavFile.getNumFrames();
            // Create a buffer of half the frames
            int framesRead;
            // buffer size is 2 * the number of frames since it is stereo
            buffer = new double[(int) (numFrames)*2];
            framesRead = wavFile.readFrames(buffer, (int)numFrames);

            System.out.println("Buffer Length: " +buffer.length);

            HashMap<Double, ArrayList<Integer>> savedPoints = new HashMap<>();

                // Read frames into buffer

            int endPointer = buffer.length-1;
            int beginPointer = 0;
            boolean dictComplete = false;
            boolean found = false;
            for(int i=buffer.length-1-numFramesinCut; i>buffer.length/2; i--){
                if(dictComplete){
                    if(!savedPoints.containsKey(buffer[i])){
                        continue;
                    }
                    ArrayList<Integer> pointers = savedPoints.get(buffer[i]);
                    for (int p:pointers) {
                        found = checkLoops(buffer,i,p, numFramesinCut);
                        if(found){
                            beginPointer = p;
                            endPointer = i;
                            break;
                        }
                    }
                    if(found){
                        break;
                    }

                } else {
                    for (int j = 0; j < buffer.length/2; j++) {
                        handleDict(savedPoints,buffer[j],j);
                        if(buffer[i] == buffer[i]){
                            found = checkLoops(savedPoints,buffer, i,j,numFramesinCut);
                        }
                        if(found){
                            beginPointer = j;
                            endPointer = i;
                            break;
                        }

                        if(j == buffer.length/2 -1){
                            dictComplete = true;
                        }
                    }
                }
                if(found){
                    break;
                }
            }

            int sampleRate = (int)wavFile.getSampleRate();

            WavFile wavFile2 = WavFile.newWavFile(new File("beatLooping.wav"), 2, numFrames/2, 16, sampleRate);

            double[] bufferFinal = new double[endPointer-beginPointer];
            System.out.println("Final Buffer Length: " +bufferFinal.length);

            System.arraycopy(buffer, buffer.length/2 -1, bufferFinal, 0, buffer.length/2);

            wavFile2.writeFrames(bufferFinal, (endPointer-beginPointer)/2);

            // Close the wavFile
            wavFile.close();
            wavFile2.close();
        }
        catch (Exception e)
        {
           e.printStackTrace();
        }

    }

    static private boolean checkLoops(HashMap<Double, ArrayList<Integer>> savedPoints, double[] buffer, int i, int j, int framesinCut){
        int frameCount =1;
        while(frameCount < framesinCut && i<buffer.length && j<buffer.length/2){
            handleDict(savedPoints, buffer[j], j);

            if(buffer[i] != buffer[j]){
                return false;
            }
            i = i+2;
            j = j+2;
            frameCount++;
        }
        if(frameCount == framesinCut){
            return true;
        } else {
            return false;
        }
    }

    static private boolean checkLoops( double[] buffer, int i, int j, int framesinCut){
        int frameCount =1;
        while(frameCount < framesinCut && i<buffer.length && j<buffer.length/2){

            if(buffer[i] != buffer[j]){
                return false;
            }
            i = i+1;
            j = j+1;
            frameCount++;
        }
        if(frameCount == framesinCut){
            return true;
        } else {
            return false;
        }

    }

    static public void handleDict(HashMap<Double, ArrayList<Integer>> dict, Double key, int pointer){
        if(dict.containsKey(key)){
            dict.get(key).add(pointer);
        } else {
            dict.put(key,new ArrayList<Integer>(){{add(pointer);}});
        }
    }

}


问:
httpd disabled at runlevels , needs to be restarted for synchronizer updates on xen
I have Redhat 6.10 Synchronizer Server and xen client device setup. I am able to download updates via a manager software which run on xen client device.

But each time I want to download the update.tar

I restart the apache and then client xen device.

or I have to reboot the xen client device which I want to update then it downloads.

But sometimes even on xen client device reboot the update.tar wont download.
xen-client: downloading ....and it just keeps downloading without downloading it. It times out. I believe that for the update to download on the xen client device just restarting the xen client  or invoking the client service should be enough. There should be no need to restart apache and then restart the xen-vm-client.

I am not able to download without restarting the httpd server. ie I have to run 'service httpd restart' and then immediately 'xen-vm-client reboot' . But without this I am not able to download the update.tar by just firing 'xen-vm-client reboot' on Xen. I have to restart httpd and then xen client device for it to download.

I had an issue with Redhat 6.10. After 'yum install httpd'  and rebooting redhat it wont boot up. And then after  debugging through the boot process, I figure out that httpd service running at different runlevels on boot stops redhat from booting up. So had to
chkconfig httpd off
chkconfig httpd --del
This fixed the issue of httpd at runlevels hanging the redhat bootup. But I think this could be the reason why I have to restart httpd to get the update to download. Otherwise if I reboot the xen client device it downloads without a httpd restart. So any hints/ideas are really appreciated.

Please give me some understanding about why this is happening and how this can be solved if you know.
Once again grateful for all the help.
Regards
Shraddha

Next what I ll try is 'chkconfig httpd on' this might again cause the redhat to hangup on booting. And thus I may have to reinstall the entire Synchronizer redhat 6.10 setup. Or still trying to investigate about the issue.


问:
R8: Type com.facebook.fbreact.specs.NativeAccessibilityManagerSpec is defined multiple times

ERROR:C:\Users\user.gradle\caches\transforms-3\24d11a768227ded42c3db1fd43c69ff3\transformed\jetified-react-native-0.70.5-release-runtime.jar: R8: Type com.facebook.fbreact.specs.NativeAccessibilityManagerSpec is defined multiple times: C:\Users\user.gradle\caches\transforms-3\24d11a768227ded42c3db1fd43c69ff3\transformed\jetified-react-native-0.70.5-release-runtime.jar:com/facebook/fbreact/specs/NativeAccessibilityManagerSpec.class, C:\Users\user\ReactNative\Nasso\android\app\build\intermediates\javac\release\classes\com\facebook\fbreact\specs\NativeAccessibilityManagerSpec.class

j'ai supprimé le cache et le dossier build
ensuite ./gradlew clean
./gradlew build

si j'execute ./gradlew ensembleDebug ca marche
si 'exécute ./gradlew ensembleRelease j'obtien l'erreur .

que puise faire !


问:
jni.h: No such file or directory
I need to compile this library file using gcc compiler but getting error.

Although all tools are available.  jni.h is on the way D:\JDK 8\include

```<code>D:\JNIProject\src\main\java>gcc -I${JAVA_HOME}/include -I${JAVA_HOME}/include/win32 -o libmylib.jnilib -shared NativeClass.cpp
In file included from NativeClass.cpp:1:
NativeClass.h:2:10: fatal error: jni.h: No such file or directory
    2 | #include <jni.h>
      |          ^~~~~~~
</code>```

NativeClass.cpp

```<code>#include "NativeClass.h"
#include <stream>
#include <math>
#include <string>
#include <jni.h>
using namespace std;

JNIEXPORT void JNICALL Java_NativeClass_addOtherMethod
  (JNIEnv *, jclass, jstring st1, jstring st2) {
   // some code
}
</code>```

NativeClass.h

```<code>/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeClass */

#ifndef _Included_NativeClass
#define _Included_NativeClass
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     NativeClass
 * Method:    addOtherMethod
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_NativeClass_addOtherMethod
  (JNIEnv *, jclass, jstring, jstring);

#ifdef __cplusplus
}
#endif
#endif
</code>```

NativeClass.java

```<code>public class NativeClass {
    static {
        System.loadLibrary("lib");
    }
    public static native void addOtherMethod(String first, String second);
}
</code>```

JAVA_HOME=D:\JDK 8

I tried not to specify JAVA_HOME, but to register manually. Did not help
I tried:

gcc /I "$(JAVA_HOME)\include" /I "$(JAVA_HOME)\include\win32" -o libmylib.jnilib -shared NativeClass.cpp

and also

gcc /I "D:\JDK 8\include" /I "D:\JDK 8\include\win32" -o libmylib.jnilib -shared NativeClass.cpp

Title: jni.h: No such file or directory

Body:
I need to compile this library file using gcc compiler but getting error.

Although all tools are available.  jni.h is on the way D:\JDK 8\include

D:\JNIProject\src\main\java>gcc -I${JAVA_HOME}/include -I${JAVA_HOME}/include/win32 -o libmylib.jnilib -shared NativeClass.cpp
In file included from NativeClass.cpp:1:
NativeClass.h:2:10: fatal error: jni.h: No such file or directory
    2 | #include <jni.h>
      |          ^~~~~~~

NativeClass.cpp

#include "NativeClass.h"
#include <stream>
#include <math>
#include <string>
#include <jni.h>
using namespace std;

JNIEXPORT void JNICALL Java_NativeClass_addOtherMethod
  (JNIEnv *, jclass, jstring st1, jstring st2) {
   // some code
}

NativeClass.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeClass */

#ifndef _Included_NativeClass
#define _Included_NativeClass
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     NativeClass
 * Method:    addOtherMethod
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_NativeClass_addOtherMethod
  (JNIEnv *, jclass, jstring, jstring);

#ifdef __cplusplus
}
#endif
#endif

NativeClass.java

public class NativeClass {
    static {
        System.loadLibrary("lib");
    }
    public static native void addOtherMethod(String first, String second);
}

JAVA_HOME=D:\JDK 8

I tried not to specify JAVA_HOME, but to register manually. Did not help
I tried:

gcc /I "$(JAVA_HOME)\include" /I "$(JAVA_HOME)\include\win32" -o libmylib.jnilib -shared NativeClass.cpp

and also

gcc /I "D:\JDK 8\include" /I "D:\JDK 8\include\win32" -o libmylib.jnilib -shared NativeClass.cpp


问:
problem with scrolling a list created with input type radio (JavaScript )
I am trying to activate the list when scrolling, but the problem is that when I scroll up the lower list is activated, not the upper one. In short when I want to scroll up, it scrolls down. How can I solve it?

also you can check this link to see how it currently works.
https://vegatekhub.com/discovery-2/

let amount = 0;
let current = 1;
let max = 4;

document.addEventListener('scroll', () => {
  amount++;
  if (amount >= 50) {
    amount = 0;
    document.getElementById('r' + current).checked = false;
    //If you reach the last radio element you reset the counter
    if (current == max)
      current = 1;
    else
      current += 1;
    document.getElementById('r' + current).checked = true;

  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" name="buttons" id="r1" checked>
<input type="radio" name="buttons" id="r2">
<input type="radio" name="buttons" id="r3">
<input type="radio" name="buttons" id="r4">

<div class="controls">
  <label for="r1"><span></span>LAB & Process Development</label>
  <label for="r2"><span></span>Quality & Regulatory</label>
  <label for="r3"><span></span>Engineering & Project Management</label>
  <label for="r4"><span></span>EHS</label>
</div></code>```

Body:
I am trying to activate the list when scrolling, but the problem is that when I scroll up the lower list is activated, not the upper one. In short when I want to scroll up, it scrolls down. How can I solve it?

also you can check this link to see how it currently works.
https://vegatekhub.com/discovery-2/

let amount = 0;
let current = 1;
let max = 4;

document.addEventListener('scroll', () => {
  amount++;
  if (amount >= 50) {
    amount = 0;
    document.getElementById('r' + current).checked = false;
    //If you reach the last radio element you reset the counter
    if (current == max)
      current = 1;
    else
      current += 1;
    document.getElementById('r' + current).checked = true;

  }
});

<input type="radio" name="buttons" id="r1" checked>
<input type="radio" name="buttons" id="r2">
<input type="radio" name="buttons" id="r3">
<input type="radio" name="buttons" id="r4">

  LAB & Process Development
  Quality & Regulatory
  Engineering & Project Management
  EHS


问:
How to reduce query running time
I have table1 which contains around 1mln line of records and table2 around 3mln line of data.

I have received the below-mentioned code from my previous post (link) which is updating the table as expected, but is taking more than an hour to update just 100 lines of records.

```<code>do $$
declare
  rec record;
  current_joins text;
  current_result int;
begin
  for rec in select joins from table1 loop
     select rec.joins into current_joins;
     execute format('select count(*)
                     from (
                        select 1
                        from table2
                        group by %1$s
                        having count(*)>=1
                     ) as some_alias;',
                     current_joins)
              into current_result;
     update table1 set result=current_result where joins=current_joins;
  end loop;
end $$;
</code>```

Appreciate if somebody could provide me any alternative code to handle the above requirements.

The feature of the table can be seen from the following link (https://dbfiddle.uk/pP_9mKy3) and the previous post can be seen from the following link

Title: How to reduce query running time

Body:
I have table1 which contains around 1mln line of records and table2 around 3mln line of data.

I have received the below-mentioned code from my previous post (link) which is updating the table as expected, but is taking more than an hour to update just 100 lines of records.

do $$
declare
  rec record;
  current_joins text;
  current_result int;
begin
  for rec in select joins from table1 loop
     select rec.joins into current_joins;
     execute format('select count(*)
                     from (
                        select 1
                        from table2
                        group by %1$s
                        having count(*)>=1
                     ) as some_alias;',
                     current_joins)
              into current_result;
     update table1 set result=current_result where joins=current_joins;
  end loop;
end $$;

Appreciate if somebody could provide me any alternative code to handle the above requirements.

The feature of the table can be seen from the following link (https://dbfiddle.uk/pP_9mKy3) and the previous post can be seen from the following link


问:
How to add a Session Beans For Entity Classes in Netbeans?
Good day everyone, I have been watching this video series as a guide line for my own netbeans e commerce project but at 19:45 the teacher adds a Session Beans for Entity Classes but when I try to create one I didn’t get the option to add it. Is there a key board command to adds a Session Beans for Entity Classes? I’m on windows 11 and I’m using Apache Netbeans IDE 15.
https://www.youtube.com/watch?v=CbS4Jjd5Z98&list=PLWS58wV27xi5AFrSfru26h4KWNMv1h2XA&index=8&ab_channel=CS.Math.Educator
Teacher’s screen
My screen</p>


问:
SOAP REQUEST FROM WORDPRESS
I have wordpress website. I want to get products (and updates) from another b2b servis, with SOAP request.

I add this code in function.php :

```<code>    $request_body = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <GetProducts xmlns="http://url here">
      <username>user</username>
      <password>123456789</password>
     <productGroupCode>AV</productGroupCode>
    </GetProducts>
  </soap12:Body>
</soap12:Envelope>';

// Send the request
$response = wp_remote_post( 'SOAP URL HERE', array(
   'method' => 'POST',
   'headers' => array(
      'Content-Type' => 'application/soap+xml; charset=utf-8',
   ),
   'body' => $request_body,
) );

// Check for error
if ( is_wp_error( $response ) ) {
   // There was an error making the request
   $error_message = $response->get_error_message();
   echo "Error making request: $error_message";
} else {
   // The request was successful
   $response_code = wp_remote_retrieve_response_code( $response );
   $response_body = wp_remote_retrieve_body( $response );
   }
</code>```

When I open the home page and write an echo response I get a response, but only raw text, without tags, or separator, so I can't use that file for import, is there any idea how I can  get a response like they have :

I use Postman to test, and with Postman I get what I want with WordPress request:

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetProductsResponse xmlns="http://url">
            <GetProductsResult>
                <PRODUCT>
                    <CODE>01234</CODE>
                    <PRODUCTGROUPCODE>PHONE</PRODUCTGROUPCODE>
                    <NAME>Samsung s10</NAME>
                    <MANUFACTURER>Samsung</MANUFACTURER>
                   .... etc
</code>```

Title: SOAP REQUEST FROM WORDPRESS

Body:
I have wordpress website. I want to get products (and updates) from another b2b servis, with SOAP request.

I add this code in function.php :

    $request_body = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <GetProducts xmlns="http://url here">
      <username>user</username>
      <password>123456789</password>
     <productGroupCode>AV</productGroupCode>
    </GetProducts>
  </soap12:Body>
</soap12:Envelope>';

// Send the request
$response = wp_remote_post( 'SOAP URL HERE', array(
   'method' => 'POST',
   'headers' => array(
      'Content-Type' => 'application/soap+xml; charset=utf-8',
   ),
   'body' => $request_body,
) );

// Check for error
if ( is_wp_error( $response ) ) {
   // There was an error making the request
   $error_message = $response->get_error_message();
   echo "Error making request: $error_message";
} else {
   // The request was successful
   $response_code = wp_remote_retrieve_response_code( $response );
   $response_body = wp_remote_retrieve_body( $response );
   }

When I open the home page and write an echo response I get a response, but only raw text, without tags, or separator, so I can't use that file for import, is there any idea how I can  get a response like they have :

I use Postman to test, and with Postman I get what I want with WordPress request:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetProductsResponse xmlns="http://url">
            <GetProductsResult>
                <PRODUCT>
                    01234
                    <PRODUCTGROUPCODE>PHONE</PRODUCTGROUPCODE>
                    <NAME>Samsung s10</NAME>
                    <MANUFACTURER>Samsung</MANUFACTURER>
                   .... etc


问:
Use 2 types of authorization in Bubble.io
So Im using the Discord API and a “PUT” API call to add a user to a guild requires the OAuth guilds.join scope (which I have added) but it also requires an Authorization of "Bot " . How would I use both the access token in the “access_token” parameter and the Bot Token for Authorization? https://discord.com/developers/docs/resources/guild#add-guild-member</p>