text:
Q: Open layers features not disappearing after vectorSource.clear() and refresh in React Using OpenLayers 7.1.0 and React 18.2.0, I have a map with some region boxes displayed on a vector layer using GeoJSON data handed in as a prop to my VectorLayer component.
When the features prop changes, a useEffect is fired which is supposed to be clearing the old features off the map and rendering only the new ones. New features are rendered as expected, but they appear on top of the old ones which are not being removed.
After attempting to remove the old features by calling clear() and refresh() on the source and renderSync() on the map, and before adding the new features to the source, console.log(vectorLayer.GetSource().GetFeatures()) shows an empty array but the old features are still visible. I've tried creating a whole new source and even tried creating a whole new layer without success.
I referenced this example to set up the structure of the map context and the basic layers:
https://medium.com/swlh/how-to-incorporate-openlayers-maps-into-react-65b411985744
VectorLayer.js:
import {useContext, useEffect, useState} from 'react';
import MapContext from "../MapContext";
import OLVectorLayer from 'ol/Layer/Vector';
import VectorSource from "ol/source/Vector";
import {createBox} from "ol/interaction/Draw";
import {Draw} from "ol/intraction";
import {GeoJSON} from "ol/format";

const VectorLayer = ({source, style, zIndex = 0, canDraw, onShapeDrawn, features}) => {
    const {map} = useContext(MapContext);
    //const [vectorLayer, setVectorLayer] = useState(null);
    let vectorSource = new VectorSource({wrapX: true});
    let vectorLayer = new OLVectorLayer({
        source: vectorSource,
        style
    });

    const drawBox = new Draw({
        source: vectorSource,
        type: 'Circle',
        geometryFunction: createBox(),
    });

    // "Constructor"
    useEffect(() => {
        if (!map) return;

        // let vectorLayer = new OLVectorLayer({
        //     source: vectorSource,
        //     style
        // });

        map.addLayer(vectorLayer);
        vectorLayer.setZIndex(zIndex);

        if( canDraw )
        {
            map.addInteraction(drawBox);

            if( onShapeDrawn != null ) {
                drawBox.on('drawend', (e) => {
                    onShapeDrawn(e);
                })
            }
        }

        //setVectorLayer(vectorLayer);

        return () => {
            if (map) {
                map.removeLayer(vectorLayer);
            }
        }
    }, [map]);

    // update map if features prop changes
    useEffect( () => {
        console.log('new # of features');
        console.log(features?.features?.length);
        if (features?.features?.length) { // may be empty on first render
            // vectorLayer.getSource().clear();
            // vectorLayer.getSource().refresh();
            // map.renderSync();
            // console.log('old source features after clear and refresh');
            // console.log(vectorLayer.getSource().getFeatures());
            map.removeLayer(vectorLayer);

            // let featureSource = new VectorSource({
            //     wrapX: true
            // })

            // featureSource.addFeatures(new GeoJSON().readFeatures(features,
            //     {dataProjection:'EPSG:4326', featureProjection:'EPSG:4326'}));

            // vectorLayer = new OLVectorLayer({
            //     source: featureSource,
            //     style
            // });
            vectorSource.clear();
            vectorSource.refresh()
            vectorSource.addFeatures(new GeoJSON().readFeatures(features,
                {dataProjection:'EPSG:4326', featureProjection:'EPSG:4326'}));

            // set features to map
            // vectorLayer.setSource(featureSource);
            map.addLayer(vectorLayer);
            vectorLayer.setZIndex(zIndex);
            map.renderSync();
        }

    },[features])

    // Enabled/Disabled draw interaction when canDraw bool prop changes
    useEffect(() => {
        if (!map) return;
        console.log(`vector layer canDraw: ${canDraw}`);
        if( canDraw )
        {
            map.removeLayer(vectorLayer);
            map.addLayer(vectorLayer);
            vectorLayer.setZIndex(zIndex);

            map.addInteraction(drawBox);

            if( onShapeDrawn != null ) {
                drawBox.on('drawend', (e) => {
                    onShapeDrawn(e);
                })
            }
        } else {
            console.log('removing draw interaction');
            map.getInteractions().pop();
        }
    }, [canDraw]);

    return null;
}

export default VectorLayer;

I've just left in the commented-out code to show a few different things I have tried. If it's a bit confusing to look through I'd be happy to clean it up some more.

A: I think your vector layer is re-created on each render.
Put creation of the vectorLayer outside the component function or use a useMemo :
const vectorLayer = useMemo(()=> {
    let vectorSource = new VectorSource({wrapX: true});
    let vectorLayer = new OLVectorLayer({
        source: vectorSource,
        style
    });
    return vectorLayer
},  []);

Then use the vectorLayer to access the source.

A: Sorry for the late reply, thought I had already come back and updated this!
I was able to resolve the issue by restructuring the code of VectorLayer.js to ensure that the source, layer, and interactions were only being created once. The issue was caused by their ol_uid being regenerated on new renders.
VectorLayer.js
import {useContext, useEffect, useState} from 'react';
import MapContext from "../MapContext";
import OLVectorLayer from 'ol/Layer/Vector';
import VectorSource from "ol/source/Vector";
import {createBox} from "ol/interaction/Draw";
import {Draw} from "ol/interaction";
import {GeoJSON} from "ol/format";

const VectorLayer = (props) => {
    const {style, zIndex = 0, canDraw, onShapeDrawn, featureCollection} = props;
    const {map} = useContext(MapContext);

    const [isInstantiated, setIsInstantiated] = useState(false);

    const [vectorLayer, setVectorLayer] = useState(null);
    const [vectorSource, setVectorSource] = useState(null);
    const [drawBox, setDrawBox] = useState(null);

    useEffect(() => {
        if (!map || isInstantiated) return;

        setVectorSource(new VectorSource({wrapX: true}));

        setIsInstantiated(true);
    },[map]);

    useEffect(() => {
        if(!map || !vectorSource) return;

        setDrawBox(new Draw({
            source: vectorSource,
            type: 'Circle',
            geometryFunction: createBox(),
        }));

        setVectorLayer(new OLVectorLayer({
            source: vectorSource,
            style
        }));
    }, [vectorSource]);

    useEffect(() => {
        if(!map || !vectorLayer) return;

        map.addLayer(vectorLayer);
        vectorLayer.setZIndex(zIndex);

        if( canDraw )
        {
            map.addInteraction(drawBox);

            if( onShapeDrawn != null ) {
                drawBox.on('drawend', (e) => {
                    onShapeDrawn(e);
                })
            }
        }

        return () => {
            if (map) {
                map.removeLayer(vectorLayer);
            }
        }
    }, [vectorLayer]);

    // update map if features prop changes
    useEffect( () => {
        if(!map || !vectorLayer) return;

        map.removeLayer(vectorLayer);
        vectorSource.clear();

        if (featureCollection?.features?.length) { // may be empty on first render
            vectorSource.addFeatures(new GeoJSON().readFeatures(featureCollection,
                {dataProjection:'EPSG:4326', featureProjection:'EPSG:4326'}));
        }

        map.addLayer(vectorLayer);
        vectorLayer.setZIndex(zIndex);
    }, [featureCollection])

    // Enable/Disable draw interaction when canDraw bool prop changes
    useEffect(() => {
        if (!map || !vectorLayer || !drawBox) return;

        console.log(`vector layer canDraw: ${canDraw}`);
        if( canDraw )
        {
            map.removeLayer(vectorLayer);

            map.addInteraction(drawBox);

            if( onShapeDrawn != null ) {
                drawBox.on('drawend', (e) => {
                    onShapeDrawn(e);
                })
            }

            map.addLayer(vectorLayer);
            vectorLayer.setZIndex(zIndex);
        } else {
            console.log('removing draw interaction');
            //map.getInteractions().pop();
            map.removeInteraction(drawBox);
        }
    }, [canDraw]);

    return null;
}

export default VectorLayer;

Thanks for the help everyone!


text:
Q: Workaround for session rate-limiting/throttling in LogRocket Since LogRocket doesn't have an inbuilt way to rate-limit the number of sessions, is there a way to do it by ourselves? Suggestions please.

A: The best solution I've come up with is to ignore specific users and environments so we can basically ignore test automation users and local development. Otherwise we end up using 4k sessions a week before even getting production sessions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert String AnyName into Camelcase I'm working for a while with Microsoft Power Query M and I have the situation that I need to transform names in the first column into Camelcase.
I receive the data in form Any_Name. First step I do is to replace _ by "":
 #"Replaced Value" = Table.ReplaceValue(#"Expanded {0}","_","",Replacer.ReplaceText,{"Column1.dbColumnName"})

The output of the above function for each cell in the first colum is AnyName and I need now to transform the first char into a lowercase character to have a Camelcase String.
How is it possible to do so? Since there is no function for it. I was thinking about to take the first char by splitting the Text with Text.Split. This function does only allow the splitting at the desired character. But not at the number of the character. So it is not possible to say split at charpos 0. The transformation into upper case shall be done with Text.Upper. The usage of Text.PadStart could be used to add the transformed char again.
My problem is that I do know how to apply this on all cells in the first column.

A: You can use
let
    Source = #table(type table[Name = text],{{"MarcelBeug"},{"IrgendwPointer"}}),
    camelCase = Table.TransformColumns(Source,{"Name", each Text.Lower(Text.Start(_,1))&Text.Range(_,1)})
in
    camelCase


text:
Q: How to catch Stripe Invalidrequest exception error in Android I am following this link to implement stripe in Android. When I enter test card number from diners or discover, I am getting the below error.

E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.xxxxx.app, PID: 11990
java.lang.RuntimeException: Request-id: req_edpbJzvr4Zkk9V
com.stripe.android.exception.InvalidRequestException: Your card is not supported.
at android.os.Parcel.writeException(Parcel.java:1590)
at com.stripe.android.PaymentController$Result.writeToParcel(PaymentController.kt)
at android.os.Parcel.writeParcelable(Parcel.java:1505)
at android.os.Parcel.writeValue(Parcel.java:1411)
at android.os.Parcel.writeArrayMapInternal(Parcel.java:733)
at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
at android.os.Bundle.writeToParcel(Bundle.java:1133)
at android.os.Parcel.writeBundle(Parcel.java:773)
at android.content.Intent.writeToParcel(Intent.java:9247)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3511)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1526)
at android.app.Activity.startActivityForResult(Activity.java:4399)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4358)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at com.stripe.android.view.AuthActivityStarter$Host.startActivityForResult$stripe_release(AuthActivityStarter.kt:33)
at com.stripe.android.PaymentRelayStarter$Companion$create$1.start(PaymentRelayStarter.kt:28)
at com.stripe.android.PaymentRelayStarter$Companion$create$1.start(PaymentRelayStarter.kt:21)
at com.stripe.android.StripePaymentController$Companion.handleError(StripePaymentController.kt:899)
at com.stripe.android.StripePaymentController$Companion.access$handleError(StripePaymentController.kt:838)
at com.stripe.android.StripePaymentController$ConfirmStripeIntentCallback.onError(StripePaymentController.kt:542)
at com.stripe.android.ApiOperation.dispatchResult(ApiOperation.kt:40)
at com.stripe.android.ApiOperation.access$dispatchResult(ApiOperation.kt:13)
at com.stripe.android.ApiOperation$execute$1$1.invokeSuspend(ApiOperation.kt:32)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: Request-id: req_edpbJzvr4Zkk9V
com.stripe.android.exception.InvalidRequestException: Your card is not supported.
at com.stripe.android.StripeApiRepository.handleApiError(StripeApiRepository.kt:875)
at com.stripe.android.StripeApiRepository.makeApiRequest$stripe_release(StripeApiRepository.kt:919)
at com.stripe.android.StripeApiRepository.fetchStripeModel(StripeApiRepository.kt:903)
at com.stripe.android.StripeApiRepository.confirmSetupIntent(StripeApiRepository.kt:212)
at com.stripe.android.StripePaymentController$ConfirmStripeIntentTask.getResult$stripe_release(StripePaymentController.kt:524)
at com.stripe.android.ApiOperation$execute$1.invokeSuspend(ApiOperation.kt:22)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:561)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:727)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:667)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:655)

This is the code I am using
binding.payButton.setOnClickListener {

        val card = binding.cardInputWidget.paymentMethodCard
        val nameText = binding.nameInput.text.toString()

        binding.progressBar.visibility = View.VISIBLE

        if (nameText.isEmpty()) {
            Utilities.alertBoxSingleBtn(this, "Please enter the card holder name")
            binding.progressBar.visibility = View.GONE
            return@setOnClickListener
        }

        val billingDetails = PaymentMethod.BillingDetails.Builder()
                .setName(nameText)
                .build()
        if (card != null) { // Create SetupIntent confirm parameters with the above
            binding.payButton.isEnabled = false
            val paymentMethodParams = PaymentMethodCreateParams.create(card, billingDetails)
            val confirmParams = ConfirmSetupIntentParams.create(paymentMethodParams, clientSecretKey!!)
            stripe.confirmSetupIntent(this, confirmParams)

        } else {
            Utilities.alertBoxSingleBtn(this, "Invalid card details")
            binding.payButton.isEnabled = true
            binding.progressBar.visibility = View.GONE
        }
    }

I experimented by using try-catch around all statements. But none of the statement is catching the exception. Please help with the issue


text:
Q: Jquery Autocomplete source within same file I'm trying to implement this script within Wordpress (http://af-design.com/blog/2010/05/12/using-jquery-uis-autocomplete-to-populate-a-form/) getting the Array from Wordpress database. The issue is that Wordpress database connect $wpdb won't work calling an external php like demo_cities.php
Can you tell me what the source would be if I integrate the demo_cities.php into the HTML? Is this even possible?
Can I create the array in Wordpress page and just call the rest of the script as it is?
Thanks
HTML

<form action="#" method="post">

City

         <input type="text" name="city" id="city" value="" />

State

         <input type="text" name="state" id="state" value="" />

Zip

         <input type="text" name="zip" id="zip" value="" />

</form>

demo_cities.php
<?php

// Data could be pulled from a DB or other source
$cities = array(
    array('city'=>'New York', state=>'NY', zip=>'10001'),
    array('city'=>'Los Angeles', state=>'CA', zip=>'90001'),
    array('city'=>'Chicago', state=>'IL', zip=>'60601'),
    array('city'=>'Houston', state=>'TX', zip=>'77001'),
    array('city'=>'Phoenix', state=>'AZ', zip=>'85001'),
    array('city'=>'Philadelphia', state=>'PA', zip=>'19019'),
);

// Cleaning up the term
$term = trim(strip_tags($_GET['term']));

// Rudimentary search
$matches = array();
foreach($cities as $city){
    if(stripos($city['city'], $term) !== false){
        // Add the necessary "value" and "label" fields and append to result set
        $city['value'] = $city['city'];
        $city['label'] = "{$city['city']}, {$city['state']} {$city['zip']}";
        $matches[] = $city;
    }
}

// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);

?>


text:
Q: App Crashes on Some Devices | Memory Issue? So I recently finished initial development of my app. I'd been using my phone(OnePlus 2) the entire time for debugging and things were generally fine.
I decided to take some help from friends and family for testing the app and some have reported that the app crashes on startup. So I got hold of my mom's phone (Galaxy S5) and decided to logcat the error on that.
Logcat
04-16 10:23:02.400 3229-3229/? I/Timeline: Timeline: Activity_launch_request id:com.test.drawernav time:3576923
04-16 10:23:02.730 3229-3229/? V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable-xxhdpi-v4/abc_ic_ab_back_mtrl_am_alpha.png
04-16 10:23:02.835 3229-3229/? V/BitmapFactory: DecodeImagePath(decodeResourceStream3) : res/drawable/bg.jpg
04-16 10:23:02.885 3229-3229/? I/art: Alloc sticky concurrent mark sweep GC freed 1308(219KB) AllocSpace objects, 5(80KB) LOS objects, 6% free, 118MB/126MB, paused 381us total 23.063ms
04-16 10:23:02.895 3229-3229/? I/art: Clamp target GC heap from 134MB to 128MB
04-16 10:23:02.895 3229-3229/? I/art: Alloc partial concurrent mark sweep GC freed 481(22KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 118MB/128MB, paused 346us total 9.467ms
04-16 10:23:02.915 3229-3229/? I/art: Clamp target GC heap from 134MB to 128MB
04-16 10:23:02.915 3229-3229/? I/art: Alloc concurrent mark sweep GC freed 58(14KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 118MB/128MB, paused 392us total 18.452ms
04-16 10:23:02.915 3229-3229/? I/art: Forcing collection of SoftReferences for 43MB allocation
04-16 10:23:02.935 3229-3229/? I/art: Clamp target GC heap from 134MB to 128MB
04-16 10:23:02.935 3229-3229/? I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 7% free, 118MB/128MB, paused 521us total 17.392ms
04-16 10:23:02.980 3229-3229/? E/art: Throwing OutOfMemoryError "Failed to allocate a 45619212 byte allocation with 9890668 free bytes and 9MB until OOM"
04-16 10:23:02.980 3229-3229/? D/skia: --- allocation failed for scaled bitmap
04-16 10:23:02.985 3229-3229/? D/AndroidRuntime: Shutting down VM
04-16 10:23:03.010 3229-3229/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.test.drawernav, PID: 3229
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.drawernav/com.test.drawernav.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.v4.widget.DrawerLayout
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:145)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                  Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.v4.widget.DrawerLayout
                                                     at android.view.LayoutInflater.createView(LayoutInflater.java:640)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
                                                     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
                                                     at com.test.drawernav.MainActivity.onCreate(MainActivity.java:32)
                                                     at android.app.Activity.performCreate(Activity.java:6221)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:145)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                  Caused by: java.lang.reflect.InvocationTargetException
                                                     at java.lang.reflect.Constructor.newInstance(Native Method)
                                                     at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                     at android.view.LayoutInflater.createView(LayoutInflater.java:614)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
                                                     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
                                                     at com.test.drawernav.MainActivity.onCreate(MainActivity.java:32)
                                                     at android.app.Activity.performCreate(Activity.java:6221)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:145)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                  Caused by: java.lang.OutOfMemoryError: Failed to allocate a 45619212 byte allocation with 9890668 free bytes and 9MB until OOM
                                                     at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:741)
                                                     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:562)
                                                     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1014)
                                                     at android.content.res.Resources.loadDrawableForCookie(Resources.java:3723)
                                                     at android.content.res.Resources.loadDrawable(Resources.java:3596)
                                                     at android.content.res.TypedArray.getDrawable(TypedArray.java:750)
                                                     at android.view.View.<init>(View.java:3939)
                                                     at android.view.ViewGroup.<init>(ViewGroup.java:511)
                                                     at android.view.ViewGroup.<init>(ViewGroup.java:507)
                                                     at android.support.v4.widget.DrawerLayout.<init>(DrawerLayout.java:351)
                                                     at android.support.v4.widget.DrawerLayout.<init>(DrawerLayout.java:347)
                                                     at java.lang.reflect.Constructor.newInstance(Native Method)
                                                     at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                     at android.view.LayoutInflater.createView(LayoutInflater.java:614)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
                                                     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
                                                     at com.test.drawernav.MainActivity.onCreate(MainActivity.java:32)
                                                     at android.app.Activity.performCreate(Activity.java:6221)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:145)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

The main activity is called after a Splash Screen (which runs on every phone) is displayed for 5 seconds. The main activity houses a navigation drawer around which the entire application has been designed.
MainActivity.java
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ActionBarDrawerToggle drawerToggle;
    private ActionBar actionBar;
    private DrawerLayout drawerLayout;
    private ListView navList;
    private FragmentTransaction fragmentTransaction;
    private FragmentManager fragmentManager;

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

        navList = (ListView) findViewById(R.id.navigationdrawer);
        ArrayList<String> navArray = new ArrayList<String>();
        navArray.add("Home");
        navArray.add("About Us");
        navArray.add("Our Work");
        navArray.add("Locate Us");
        navArray.add("Contact Us");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_1,
                navArray);
        navList.setAdapter(adapter);
        navList.setOnItemClickListener(this);
        navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open_drawer, R.string.close_drawer);

        drawerLayout.setDrawerListener(drawerToggle);

        actionBar = getSupportActionBar();
        assert getSupportActionBar() != null;
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        loadSelection(0);
    }

    private void loadSelection(int i){
        navList.setItemChecked(i, true);

        switch (i){
            case 0:
                HomeFragment homeFragment = new HomeFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder, homeFragment)
                        .commit();
                break;

            case 1:
                AboutUsFragment aboutUsFragment = new AboutUsFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder, aboutUsFragment)
                        .commit();
                break;

            case 2:
                HelplineFragment ourWorkFragment = new OurWorkFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder, ourWorkFragment)
                        .commit();
                break;

            case 3:
                LocateFragment locateFragment = new LocateFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder, locateFragment)
                        .commit();
                break;

            case 4:
                LocateFragment contactFragment = new ContactUsFragment();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentholder, contactFragment)
                        .commit();
                break;

        }

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            if (drawerLayout.isDrawerOpen(navList)) {
                drawerLayout.closeDrawer(navList);
            } else {
                drawerLayout.openDrawer(navList);
            }

        }
           return super.onOptionsItemSelected(item);
        }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        loadSelection(position);
        drawerLayout.closeDrawer(navList);
    }

}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerLayout"
    android:background="@drawable/bg"
    >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragmentholder">    </FrameLayout>

    <ListView
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:id="@+id/navigationdrawer"
        android:layout_gravity="start"
        android:background="#ccddccdd"
        ></ListView>

</android.support.v4.widget.DrawerLayout>

HomeFragment.java
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class HomeFragment extends Fragment {

 //   ViewFlipper topFlipper;
    ViewFlipper bottomFlipper;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        TextView textView = (TextView)view.findViewById(R.id.home_fragment_text);

        bottomFlipper = (ViewFlipper)view.findViewById(R.id.bottomFlipper);
        bottomFlipper.setAutoStart(true);
        bottomFlipper.setFlipInterval(2000);
        bottomFlipper.startFlipping();

    return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.drawernav.HomeFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <TextView
            android:layout_marginTop="10dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="10dp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/home_fragment_text"
            android:text="@string/home_fragment_text"
            android:textSize="27sp"
             />

        <ViewFlipper
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_gravity="bottom"
            android:layout_weight="2"
            android:id="@+id/bottomFlipper">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomFlipper1"
                android:src="@drawable/flipper1"/>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomFlipper2"
                android:src="@drawable/flipper2"/>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomFlipper3"
                android:src="@drawable/flipper3"/>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomFlipper4"
                android:src="@drawable/flipper4"/>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomFlipper5"
                android:src="@drawable/flipper5"/>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomFlipper6"
                android:src="@drawable/flipper6"/>

        </ViewFlipper>

</LinearLayout>

</FrameLayout>

Its got something to do with memory allocation is what I gather, but I have no idea how to fix it.

A:
Unable to start activity
  ComponentInfo{com.test.drawernav/com.test.drawernav.MainActivity}:
  android.view.InflateException: Binary XML file line #2:

Its an inflate exception,
the image you are referring in your res/drawable might have higher pixel resolution.
its consuming a lot of memory. so try minimizing that src image.


text:
Q: How to prove that doubly regular tournaments are regular? A doubly regular tournament is a tournament such that every two vertices have $j$ common out-neighbours. How can we prove such a tournament is $2j+1$-regular?

A: Let $v$ be any vertex, $U$ be a set of its out-neighbours. The restriction of your tournament to $U$ is $j$-out-regular, thus $|U|=2j+1$.


text:
Q: Nokia 925 denim os as mass storage How to connect Nokia lumia 925 denim os as mass storage in windows 8 or mac os, so i could explore root folder, I basically need this for copying app data?
I ve tried the Guide "Put the phone in mass storage mode" mentioned in Mass_storage_mode_and_boot_configuration_data
But it ain't work in my device, it is just restarting normally.

A: Normally you can only browse shared folders such as Documents, Pictures, Music and Videos.
However there's a tool which allows to locate and fetch files inside IsolatedStorage, have a look at the Codeplex page: https://isostorespy.codeplex.com/


text:
Q: Trying to populate gmaps4rails with multiple json strings in one page I hope I am asking this right, so please let me know if I'm way off.
The problem is trying to build a homepage that draws from multiple controllers, to display the nearest locations from multiple controllers, ie. food, businesses, ect.
Right now the individual listings pages have maps drawn from their respective
@json = Controller.all.to_gmaps4rails

How would I do something like :
@json = Controller1 Controller2 .all.to_gmaps4rails

I hope this isnt a noob question and I'm just having a bad day. Thanks guys!
edit 12.5.2011 @seanhill - this is one of the models, the other sections are very close to this format. First off, I wasn't even sure if my homepage requires it's own model, as it doesn't interact with the db at all, more pulling data from controllers that do the work. Thanks for the response Sean!
class Dining < ActiveRecord::Base
validates_uniqueness_of :name, :message => "already exists"

attr_accessible :name, :address, :cuisine, :latitude, :longitude, :about, :facebook, :twitter, :phone, :website
geocoded_by :address
after_validation :geocode, :if => :address_changed?

acts_as_gmappable :process_geocoding => false

def gmaps4rails_address
    "#{self.address}"
end

def gmaps4rails_infowindow
    "
#{self.name}

#{self.cuisine}
"
end

def self.search(search)
    if search
        where('name LIKE ?', "%#{search}%")
    else
        scoped
    end
end

end

A: Try this
holder = Controller1.all
holder << Controller2.all
@json = holder.flatten.map{|h| {lng: h.longitude, lat: h.latitude, class: h.class.to_s}}.to_json

Make sure to change longitude and latitude based on your column names and use js to manipulate the markers based upon class.
As the @Sean Hill said you shouldn't be calling .all on controllers but I think you have a slight misunderstanding of how things are working.  Assuming you have a Model called Dining and another called Shop, when you call Dining.all or Shop.all inside class DiningsController < ApplicationController, you are calling .all on either the Dining Model or the Shop Model not on the DiningsController.
The information you display through a controller is only limited by the methods you call in it although it is best practice ensure the main focus of the information displayed is related to the respective controller.
So what you are really trying to do is get the records from multiple models and group them together to display them in a single map.
With that said the answer should read something like this
holder = Dining.all # Takes all Dining records returned as an array and sets them to holder variable
holder << Shop.all # Pushes the Shop records array into the holder with the dining records
holder.flatten!# Next we flatten the array so we only have a single array.

# Then we use the map method to run the given code one time for each instance
# in the holder array to extract the info we need. The results for every instance
# in holder are returned in an array which we then convert to_json.
@json = holder.map{|h| {lng: h.longitude, lat: h.latitude, class: h.class.to_s}}.to_json

A: @json1 = something.to_gmaps4rails
@json2 = something.to_gmaps4rails

@json = (JSON.parse(@json1) + JSON.parse(@json2)).to_json

A: I populated the map with my initial data of festivals, and then added the rides to it with javascript with this code,
<% content_for :scripts do %>

<%end%>

In the rides controller I had this
def rides_gmap
    @rides = Ride.all
    @json = @rides.to_gmaps4rails do |ride, marker|
      marker.infowindow render_to_string(:partial => "/rides/infowindow", :locals => { :ride => ride})
      marker.picture({
                'picture' => view_context.image_path("orange-dot.png"),
                'width'   => 20,
                'height'  => 20
               })
      marker.title "#{ride.address}"
      marker.json({:ride_id => ride.id, :ride_festivaltype => ride.festival.festivaltype
    end
    respond_with @json
  end

I hope this helps.


text:
Q: What did `uniq -t` do? I have some old code from 2003 which uses -t option for uniq command. It throws an error since that option is probably not supported anymore.
Here's the piece which uses the command:
egrep -n "{ IA32_OP" ia32-decode.c | \
    awk '{ print $1 $3 $4 }' | \
    sort -t '(' +1 | \
    uniq -t ':' -f 1 | \
    sed 's/\(.*\)\:IA32_OP(\(.*\)),/#define IA32_OP_\2 \1/g' >> ia32_opcodes.h

What did that option do back then? What can I substitute that command with?

A: Given the man entry for the -f option:

-f, --skip-fields=N
         avoid comparing the first N fields

I think it is fairly safe to assume that -t specifies the field separator (this is also the case for sort in the line above). The combination of the two options would make uniq only operate on the part of the line following the first colon.

A: The only reference I could find to -t is in this patch on a GNU mailing list, which contains among other clues, this:
+  -t, --separator=S     use a character in string S as field separator\n\

This apparently was a GNU extension but no longer in use. It appears to allow selecting a delimiting character for fields other than spaces or tabs.  Try replacing
uniq -t ':' -f 1 | \

with
sed 's/:/ /' | \
uniq -f 1 | \

which will replace : with spaces which uniq recognizes the field separator.


text:
Q: JSTL and c:when test condition how can I check and use userLoggedIn to testify the condition.
I am new and I have search alot. there must be a silly mistake.
index.jsp

    <c:choose>
        <c:when test="${userLoggedIn == 1}">
             Welcome <c:out value="${loginID}" /> | Logout
        </c:when>
        <c:otherwise>Log-in</c:otherwise>
    </c:choose>

some verification servlet
int userLoggedIn = 0;

if(loginID.equals("guest@guest.com") && password.equals("guest")){
    userLoggedIn = 1;
    getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
    //     out.println("login successful");

} else {
    //   getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
    out.println("login failed");
}

A: You need to store the information in the desired scope, which is usually the session scope for case of logged-in users.
Add the following line after userLoggedIn = 1;.
request.getSession().setAttribute("userLoggedIn", userLoggedIn);

That's basically all you need to change.

Unrelated to the concrete problem, this int (and boolean as commented by BevynQ) approach is rather "primitive". You'd usually store the entire User entity obtained from the DB in the session instead. E.g.
User user = userService.find(username, password);

if (user != null) {
    request.getSession().setAttribute("user", user);
    response.sendRedirect("home");
} else {
    request.setAttribute("message", "Unknown login, please try again");
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}

with
<c:when test="${not empty user}">

which allows easy access of all its properties like

Welcome, <c:out value="${user.name}" />


text:
Q: WORDPRESS: Disable comments in "News" Category and Enable in "Blog" Category? I have a News page that displays all the posts within the "News" Category. This category has sub-categories such as "Merchandise, Music, Events" ect.
I am aiming to remove comments from ALL News/Sub-category posts but only display them with the "Blog" Category posts.
Right now I have my single.php set up so posts with the "Gallery" post_format structure are displayed differently.
Here is the single.php file//
http://pastebin.com/YNf3TxT6
I am wondering what I have to fix in order to get this working...

A: Edit: For future viewers, here is the updated paste from the conversation below for a single.php that will only show the comments template if the post is in the "Blog" Category: pastebin.com/y9ZtCN5U
Assuming you put your Blog posts on a page separate from your news posts, you should be able to use different templates based on category.
http://codex.wordpress.org/Category_Templates
So, you could make a category-blog.php template file that doesn't include the comments code.
If all of your categories are being listed on the same page, use this instead of the in_category stuff on line 50.
<?php
foreach (get_the_category() as $category) {
    if ( $category->name == 'Blog' ) {
        comments_template();
    }
}
?>

Not 100% sure that will work, but try it out and let me know what happens.


text:
Q: Create shape from typescript interface Warning: I've never used Typescript before.
I'm working with web components and I'm interested in creating a file that defines the properties (and potentially events) that will affect the component. I've done research on Typescript and I like the concise way it seems to be able to describe the shape of an object. This is what I have so far:
/* defining the keys (and which are optional) */
interface IX {
    hidden?: boolean;
    selected?: boolean;
    disabled?: boolean;
    size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
    onChange?: (event: any): void;
}

/* setting defaults */
export const ix: IX = {
    hidden: false,
    selected: false,
    disabled: false,
}

While I'm not currently using Typescript in my project (nor am I entirely convinced that I need to in order for this to work) I'm looking for a solution that would take a file that looks like the above and output some schema that defines the component's shape. Perhaps something like this:
export const ixShape = {
    hidden: {
          type: 'boolean',
          optional: true,
          'default': false,
    },
    /* and so on */
}

This can happen at build time, doesn't need to be run time. If I need a bundler like Rollup, I can leverage that also. What solutions are out there currently (if any)?


text:
Q: Chrome on PC using  I am trying to do a multiple input field across all browsers (except IE) and I am having trouble with Chrome from a PC. The problem is not that Chrome doesn't support input multiple, it is that Chrome ignores multiple when I put it into a tag, UNLESS it is just a .html file. For .html.erb, .html.haml, and .html.slim, it ignores the multiple part.
This code for slim:
input{type="file" name="file" class="native-file-input" multiple="multiple"}
This code for haml:
%input{type: "file", name: "file", class: "native-file-input", multiple: "multiple"}
and this code for erb:
<input type="file" name="file" class="native-file-input" multiple>
Those all produce:
<input class="native-file-input" name="file" type="file" >
in the Chrome browser on PC. I don't understand why it won't add multiple. If I inspect the element and add multiple to the end, then I can input multiple files. So, it is clear to me that Chrome supports multiple, there is just some bug getting Chrome to create multiple from .erb, .haml, or .slim. Also, all this work on Mac no problem.

A: Maybe in other browsers multiple: 'some_string' validates to true but typically you want this:
%input{type: "file", name: "file", class: "native-file-input", multiple: true}


text:
Q: Uploading and saving images in mvc 3 before post I have a problem with images in my web app. let say I have a form where there are some text fields, dropdowns, upload ajax control for multiple image upload and button Save.
I know how to upload images and posting a form and saving everything to database but the problem is that I want to achieve the following user experience:
User can upload multiple images and browser after successful upload shows thumbnail (this I know how to do it)...the problem here is that I do not want to save images to db before button save is pressed. Is there any convinient how to save temporary images...I have tried temp table which after button is pressed, copies all images to image table but here is browser refresh problem that looses all the data and images stay in a temp table. Can you use a session for storing temporary images or any other way (I think session is not particulary good idea for such things.)

A: One easy way to achieve that is to use the HTML5 File API and display a thumbnail once the user selects a file to upload. You don't even need to waste bandwidth as everything happens on the client. Once the user submits the form, then the image will be uploaded to the server.
Another possibility is to use one of the gazillions of available AJAX upload controls such as Uploadify, Valums Ajax Upload, Uploadify, the jQuery form plugin, ... which will allow you to upload the file to the server using an AJAX request so that you can resize it there and return the resized image to the client that you could display the thumbnail on the client.


text:
Q: Counting number of executions in a recursive fibonacci method I am trying to implement a count variable 'e' that stores the number of times the recursive function below has executed, but I am getting an error as below. I would sincerely appreciate an explanation of the concept as I also tried declaring the variable above the function to no avail. Also, alternative solutions are welcome.
def fibonacci(n, e):
    e[0] += 1
    if n < 2:
        return n
    return fibonacci(n-1, e) + fibonacci(n-2, e), e

given_index = 8
count = [0]
result = fibonacci(given_index, count)
print("Traditional recursive Fibonacci sequence solution:", result, "Execution:", result)

Output:
   TypeError: can only concatenate tuple (not "int") to tuple

Updated answer with alternate implementation:
I was able to implement this functionality in an alternate way. I am leaving it here for reference.
def fibonacci(n):
    global calculations
    calculations += 1
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

given_index = 8
global calculations
calculations = 0
print("Traditional recursive Fibonacci sequence solution:", fibonacci(given_index), "Executions:", calculations)

A: return fibonacci(n-1, e)[0] + fibonacci(n-2, e)[0], e

You are returning a tuple and you are adding them together like integers. You can change by indexing the first values as to avoid the tuples and get the value itself.
Can also do the same
result, count = fibonacci(given_index, count)

Also others raise valid points in different ways to solve the problem.

A:
TypeError: can only concatenate tuple (not "int") to tuple
occurs when we try to concatenate a tuple and an integer . Here when you are returning fibonacci(n-1, e) + fibonacci(n-2, e), e for n<=2 fibonacci() will return an integer and e is a tuple so when you go deep in the recursion it would give this error, better to remove the e and just return fibonacci(n-1, e) + fibonacci(n-2, e)


text:
Q: Why does rectX and rectY become NaN? rectX and rectY are initialized as 0. Afterwards I'm adding 0 to either 0, or a small amount. I do not understand why it would become NaN all of the sudden. Can someone help me understand?

const context = document.querySelector("#background").getContext("2d");
let rectX = 0;
let rectY = 0;
let movingSpeed = 50;
let secondsPassed = 0;
let oldTimeStamp = 0;
let timePassed = 0;

// Listen to the onLoad event
window.onload = init;

// Trigger init function when the page has loaded
function init() {
  background.width = window.innerWidth;
  background.height = window.innerHeight;

  // Request an animation frame for the first time
  // The gameLoop() function will be called as a callback of this request
  window.requestAnimationFrame(gameLoop);
}

function gameLoop(timeStamp) {
console.log("timestamp", timeStamp);
  // Calculate how much time has passed
  secondsPassed = (timeStamp - oldTimeStamp) / 1000;
  oldTimeStamp = timeStamp;

  // Pass the time to the update
  update(secondsPassed);
  draw();

  window.requestAnimationFrame(gameLoop);
}

function update(secondsPassed) {
  // Use time to calculate new position
  rectX += movingSpeed * secondsPassed;
  rectY += movingSpeed * secondsPassed;
  console.log("rect", rectX, rectY);
}

function draw() {
  context.fillStyle = "#ff8080";
  context.fillRect(rectX, rectY, 150, 100);
}
gameLoop();
* {
  box-sizing: border-box;
  overflow: hidden;
  outline: none;
  margin: 0;
  border: 0;
  padding: 0;
  display: default;
}

html {
  background-color: dimgrey;
}

body {
  background-color: rgb(255, 93, 93);
}

canvas {
  image-rendering: pixelated;
  position: absolute;
  top: 0;
  left: 0;
}

#background {
  background-color: rgb(17, 17, 17);
}
<canvas id="background"></canvas>

All it does it add number to an initial number of 0. So how does JS suddenly see it as not a number?
Some other text.

A: The other answers are correct, but here's how to fix it.
requestAnimationFrame does not get a timeStamp as a parameter, so instead use performance.now() (more precise than Date.now().getTime()) to initialize the timeStamp

/** @format */

// Declare as variable
const context = document.querySelector("#background").getContext("2d");
let rectX = 0;
let rectY = 0;
let movingSpeed = 50;
let secondsPassed = 0;
let oldTimeStamp = performance.now();
let timePassed = 0;

// Listen to the onLoad event
window.onload = init;

// Trigger init function when the page has loaded
function init() {
  background.width = window.innerWidth;
  background.height = window.innerHeight;

  // Request an animation frame for the first time
  // The gameLoop() function will be called as a callback of this request
  window.requestAnimationFrame(gameLoop);
}

function gameLoop() {
  const timeStamp = performance.now()
  // Calculate how much time has passed
  secondsPassed = (timeStamp - oldTimeStamp) / 1000;
  oldTimeStamp = timeStamp;

  // Pass the time to the update
  update(secondsPassed);
  draw();

  window.requestAnimationFrame(gameLoop);
}

function update(secondsPassed) {
  // Use time to calculate new position
  rectX += movingSpeed * secondsPassed;
  rectY += movingSpeed * secondsPassed;
}

function draw() {
  context.fillStyle = "#ff8080";
  context.fillRect(rectX, rectY, 150, 100);
}
gameLoop();
* {
  box-sizing: border-box;
  overflow: hidden;
  outline: none;
  margin: 0;
  border: 0;
  padding: 0;
  display: default;
}

html {
  background-color: dimgrey;
}

body {
  background-color: rgb(255, 93, 93);
}

canvas {
  image-rendering: pixelated;
  position: absolute;
  top: 0;
  left: 0;
}

#background {
  background-color: rgb(17, 17, 17);
}
<canvas id="background"></canvas>

A: As 'mplungjan' mentioned. You can call the loop initially with 0 as a parameter. It fixes the problem quite simply. -> gameloop() as gameloop(0).
The actual proper way to do it, however, is to call the loop initially as window.requestAnimationFrame(gameLoop);.

A: You call gameLoop(); without parameters. So  secondsPassed = (undefined - oldTimeStamp) / 1000; becomes undefined so eventuall you end up with rectX += movingSpeed * undefined;


text:
Q: Simple web-scraping code won't run but no error First post here! I can't seem to get this code to work
python script on VScode
All I did was try to work step by step with this tutorial
https://www.youtube.com/watch?v=RvCBzhhydNk
https://github.com/Vidito/webscraping_housing/blob/main/main.py
but when I run the code, the terminal just gives me nothing (please check image). I am baffled and I am not sure what I am doing wrong. Any help would be appreciated!
from bs4 import BeautifulSoup
import requests

url= "https://www.pararius.com/apartments/amsterdam?ac=1"
page = requests.get(url)

soup = BeautifulSoup(page.content, 'html.parser')
lists = soup.find_all('section', class_="listing-search-item")

for list in lists:
    title = list.find('a', class_="listing-search-item__link--title").text.replace('\n', '')
    location = list.find('div', class_="listing-search-item__location").text.replace('\n', '')
    price = list.find('span', class_="listing-search-item__price").text.replace('\n', '')
    area = list.find('span', class_="illustrated-features__description").text.replace('\n', '')

    info = [title, location, price, area]
    print(info)```

Nana

A: It doesn't print anything, because the find_all function doesn't find anything. The class for the section is called "listing-search-item listing-search-item--list listing-search-item--for-rent" not only listing-search-item. You can use attribute selectors to match everything that starts with what you have right now.
Don't use "list" as a variable name, there is already a built-in function called list.

A: This is because you have run across fairlane before you get the texts from the site https://www.pararius.com/apartments/amsterdam, it's in order to check whether you a robot.
You can add print(soup) after soup = BeautifulSoup(page.content, 'html.parser'). You will find the outputs were not you are looking for.


text:
Q: Swift files for new class or struct I am new to Swift development and wanted to ask a question related to Swift files.
If I am making a project is it a good or general practice to use only one struct or class in one file? Do you need to create a different .swift file for every new struct or class ?

A: It's not necessary. But create a different .swift file for every new struct or class help you more easy to maintain source code when your codebase is large

A: It's common to make a new file per type (struct/class/enum) with the file named for the type, but there are exceptions to the rule. If the type definition is small, and closely related to some other type, then it can be easier to read if it's in the same file with the other type definition - that's quite common with enums. Or if the type is nested in an enclosing type, then it's often written inline. But this is a matter of personal preference.


text:
Q: Hashed and heap indexed object storage table insert and query performance This question is partly to ask advice and assure this design is sane. I state the the desired properties upfront here, then go in more detail in the rationale and follow up with the design and example query and test data.

*

*To locate the right row should be fast.

*It would nice to avoid index fragmentation as much as possible.

*A fair assumption is that some types have pattern than UPDATE the row as often as SELECT it after INSERT while other SELECT more than UPDATE. It is not plausible to think the same entity would be queried with a high-frequency. More likely occasionally.

*A fair assumption is that UPDATE calls dominate as the application updates the state, with occasional SELECT queries. The application doesn't make a difference if it either updates or inserts other than that when inserting it doesn't have a valid version when issuing the call (i.e. etag/ROWVERSION). If it fails, it just reads the latest etag and retries if the developer so chooses. DELETE can be (maybe should be) a soft delete where a flag is set and it means more like reset than a delete. When a reset is followed by a upsert, it just sets the IsDeleted bit to 0 in the following design.

I'm trying to design a table that may hold arbitrary objects serialized by the application either in binary, XML or JSON form. The reason for not using only a binary blob is that a desirable property is to be able to manipulate the objects in the store.
It can be assumed there can be millions or even hundreds of millions of these objects stored. It's OK for not to consider "enterprise grade" features such as table partitioning. I'm more concerned about of the "basic design" and if it sane. This is partially a learning exercise for me.
The application will have a unique ID per object per class type by design and it uses these two to uniquely to both store and to locate a given object in the database. The class type is one's usual outernamespace.innernamespace.class and the ID can be taken to be on average about 50 characters (could be of randomish 32 bit integers, GUIDs or something user-defined). Both ID and the type are 16-bit Unicode characters. Because it is desirable to locate the objects quickly, both the unique ID and the type are hashed to 32 bit integers by the application and stored in the database as of type INT. The code handles the mapping from the hashed unsigned integer to INT in the database and back.
I read an interesting blog post by Thomas Kejser Clustered Index vs. Heap and based on that it looks like following design without a clustered heap and using a heap is the way to go.
But is it so? The following design is a bit simplified in that I'd like to avoid committing to certain design without first being more sure it works. I will add a column for version and likely split the ObjectType to a separate table in order avoid storing the type name multiple times in its entirety. I modify the sample query to either always return all three payload fields and let the application handle picking the right one or modify it to correctly return only the one with actual data and set the type to VARBINARY(MAX), I don't know if this conversion has adverse performance penalties.
I have further questions:

*

*When an object is deleted and if I'd like to save on storage but avoid index fragmentation, would it be useful to set the *Payload fields to NULL, but otherwise leave the row? If I use the MAX on VARBINARY and NVARCHAR, I understand they will be stored separately from the table and setting it to NULL may not be that a much saving in the following ObjectStore table, but I wonder if it could be a saving elsewhere.

*Are there better ways of organizing the DELETE than with the IsDeleted. I'm not sure what could be the ratio of either set or not set on this bit. One assumption that could be made is that a cleanup operation perhaps could be done that physically removes the deleted rows from the DB and defragments the table. I left it out of the index and it is not in a filtered index as this should work also on SQL Server Standard.

*From a DBA perspective, would it be an OK arrangement to make it so the DBA can modify the SELECT, INSERT (not shown here) and UPDATE (not shown here) queries correspondingly so that that the system can, say, further optimize the system by type by storing some of them to separate tables?
5. What's wrong with my query? I have also a bug in the query in that with the given example it should return only one the other one of the duplicate rows, but I can't figure out what's the problem. In the most common case, without hash collision, the query looks like being a index seek using the index.

*Would roughly something like this work also for MySQL?
Phew! That was a lot of text. I hope this would be useful to others too. If it matters, I plan to utilize ADO.NET on using this table (maybe with streaming).
DROP TABLE ObjectStore;
CREATE TABLE ObjectStore
(
    -- These are for the book keeping. The application calculates
    -- these hashes, which are unsigned 32 integers mapped to
    -- the *Id fields. The mapping is done in the code. The
    -- *Name columns contain the corresponding clear name fields.
    --
    -- If there are duplicates
    ObjectId INT NOT NULL,
    ObjectIdName NVARCHAR(512) NOT NULL,
    ObjectType INT NOT NULL,
    ObjectTypeName NVARCHAR(512) NOT NULL,

    -- The usage of the payload records is exclusive in that
    -- only one is populated at any given time and two others
    -- are NULL. When all three are returned, the application
    -- knows how to handle the situation.
    PayLoadBinary VARBINARY(MAX) NULL,
    PayloadXml XML NULL,
    PayLoadJson NVARCHAR(MAX) NULL,

    -- Informational field, no other use.
    ModifiedOn DATETIME2(3) NOT NULL,

    -- If this particular object has been deleted from the database
    -- or not. The objects can be inserted, deleted and reinserted.
    -- Would it be beneficial to set the Payload* columns to NULL
    -- to save space but still to avoid index fragmentation?
    IsDeleted BIT NOT NULL

    -- The following would in principle be the primary key, but hashing can produce
    -- collisions.
    -- CONSTRAINT PK_ObjectStore PRIMARY KEY NONCLUSTERED (ObjectId, ObjectType)
);
CREATE NONCLUSTERED INDEX IX_ObjectStore ON ObjectStore(ObjectId, ObjectType) INCLUDE(IsDeleted, PayLoadBinary, PayLoadJson, PayloadXml);

SELECT
    PayLoadBinary,
    PayloadXml,
    PayLoadJson
FROM
    ObjectStore
WHERE
    ObjectId = @objectId
    AND ObjectType = @objectType
    AND IsDeleted = 0
    AND ObjectIdName = @objectIdName
    AND ObjectTypeName = @objectTypeName;

Some test data with a simulated collision
INSERT INTO ObjectStore
(
    ObjectId,
    ObjectIdName,
    ObjectType,
    ObjectTypeName,
    PayLoadBinary,
    PayloadXml,
    PayLoadJson,
    ModifiedOn,
    IsDeleted
)
VALUES
(
    1,
    N'First',
    1,
    N'FirstType',
    NULL,
    NULL,
    N'{ "id": First, "field1": "Red", "field2": 1.0, "objects": ["birch", "pine"] }',
    GETUTCDATE(),
    0
 );

-- Simulate a collision.
INSERT INTO ObjectStore
(
    ObjectId,
    ObjectIdName,
    ObjectType,
    ObjectTypeName,
    PayLoadBinary,
    PayloadXml,
    PayLoadJson,
    ModifiedOn,
    IsDeleted
)
VALUES
(
    1,
    N'First',
    1,
    N'NonFirstType',
    NULL,
    NULL,
    N'{ "id": First, "field1": "Green", "field2": 1.2, "objects": ["pine", "birch"] }',
    GETUTCDATE(),
    0
);

INSERT INTO ObjectStore
(
    ObjectId,
    ObjectIdName,
    ObjectType,
    ObjectTypeName,
    PayLoadBinary,
    PayloadXml,
    PayLoadJson,
    ModifiedOn,
    IsDeleted
)
VALUES
(
    2,
    N'Second',
    2,
    N'SecondType',
    NULL,
    NULL,
    N'{ "id": First, "field1": "Green", "field2": 2.0, "objects": ["oak", "juniper"] }',
    GETUTCDATE(),
    0
);

DECLARE @objectId   AS INT = 1;
DECLARE @objectIdName AS NVARCHAR(512) = N'First';
DECLARE @objectType AS INT = 1;
DECLARE @objectTypeName AS NVARCHAR(512) = N'FirstType';

<edit: A relevant SO post When should a primary key be declared non-clustered?. Here it could be expected there can be a plenty of INSERT and UPDATE operations happening at once. I'm unsure about hardware or the patterns, but having a general feeling of the way to go is what I'm researching here.

A: (The comments below apply to MySQL; some may apply to other engines.)

*

*UUIDs slow things down because of their random nature.

*Don't use Unicode; use utf8.  (Better yet, CHARACTER SET utf8mb4)

*InnoDB keeps index fragmentation low by design.

*Rule of Thumb: In a table with millions of rows, a "point query" via the PRIMARY KEY can be expected to take about as long as one disk hit.  InnoDB uses a "clustered" PRIMARY KEY organized in a BTree.

*Normalize your class names.  Short integers are more efficient than medium sized strings, especially since there is a lot of repetition.

*Hash indexes are not available.  They are useless for scans and not much better than BTrees for point queries.  (Competing products are better at providing the rarely useful features, such as hash and bitmap indexes, than MySQL.)

*Fetching a record is the dominant cost in any operation.  Function calls, expression evaluation, character sets, collations, conversion, VARBINARY, etc., are insignificant in comparison.

*Data is stored in blocks, so freeing row(s) may lead to freeing blocks.  Quit worrying about fragmentation.  You have not indicated whether you are likely to be deleting 10% of the rows (not a big deal), or 90% (maybe an issue).

*Segregating the DBA from the developer is folly.

*Approximately 10% of the SQL rows in your sample code would cause syntax error in MySQL.  SQL implementations are very much not compatible.  If you try to have code that works between engines, you will have to leave out some performance features.

*"Objects" and "Relational databases" are alien to each other.


text:
Q: Mocking a Python class static variable with Pytest I am trying to properly create mocks for a class that has a dependency on a system library. Currently the code makes a connection to a socket for the library when being tested, and I am trying to remove that dependency.
class A:
    SETTING_VARIABLE = "CONFIG_VALUE"

    def __init__(self):
        self.system_connector = library.open(self.SETTING_VARIABLE)

import A

class B:
    INSTANCE_OF_A = A()

When class A is instantiated, it uses SETTING_VARIABLE to connect to a system library, which it can not do during a unit test, and my test suite fails during test collection. The library connector I am using can be configured to run in unit test mode, but requires a different configuration to be passed, so in this case SETTING_VARIABLE would need to be instantiated to "TEST_VALUE".
My test class test_B is failing as soon as B is imported when it tries to make a connection to the system library (I have disabled access to the socket for it). How can I set up Python mocking so that I can replace the value of the static variable defined by A?
One thing that I have tried to do from test_B:
import A
A.SETTING_VARIABLE = "TEST_VALUE"

This does seem to work, however is there a cleaner way to do this for unit tests?

A: Old but gold. Here is how this problem can be solved.
The B class needs to be changed to initialize INSTANCE_OF_A in its constructor. Then you can mock the SETTING_VARIABLE using patch.object.
Complete example with patch.object as instruction or decorator:
A.py:
class A:
    SETTING_VARIABLE = "CONFIG_VALUE"

    def __init__(self):
        self.system_connector = library.open(self.SETTING_VARIABLE)

B.py:
from A import A

class B:
    def __init__(self):
        self.INSTANCE_OF_A = A()

test_B.py
import unittest
from unittest.mock import patch

from A import A
from B import B

class BTestCase(unittest.TestCase):

    @patch.object(A, "SETTING_VARIABLE", "TEST_VALUE")
    def test_b_with_decorator(self):
        INSTANCE_OF_B = B()

    def test_b_with_instruction(self):
        with patch.object(A, "SETTING_VARIABLE", "TEST_VALUE"):
            INSTANCE_OF_B = B()


text:
Q: How do entropy-based estimators relate to more conventional ML, least square, and GMM estimators Over the years i have done a lot of analysis,  mostly of parameters of linear approximations to the data or a forecast, and I have used linear and nonlinear least squares, maximum likelihood, and GMM estimators, and I think i have learned a lot about each of these, though there is surely much more to know.
But I have never tried to estimate anything by maximizing or minimising its own entropy or some cross-entropy, and I do not feel like I have even the crudest sort of handle of when to use them, or what their advantages or disadvantages are relative to the aforementioned estimators which I studied in grad school. This in contrast to maximum entropy distributions, about which I believe I grasp the basics. I'd love to have an explanation, but if i don't get one in a few days I will accept a pointer to a nice clear explanation.
If my question displays ignorance about what I am trying to ask, which I think is quite possible, then I would appreciate some suggestion about how to reformulate it to be less ambiguous, rather than some insults or questions designed to highlight my ignorance rather than relieve it.


text:
Q: Fix table footer to the bottom of the page while keeping the columns the correct size Example html:

        Full Example 20'
        Full Example 40'
        Total Full Examples TEU
        Full Something 20'
        Full Something 40'
        Total Full Something TEU
        Total Full Eg/Some 20'
        Total Full Eg/Some 40'
        Total Full Eg/Some XYZ

        Report D/T
        Equipment
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something
        OTHER THING
        Something

        Fri 01-Feb-19 (00:00)
        Feb.2019

        16,131

        13,889

        43,909

        20,474

        14,334

        49,142

        36,605

        28,223

        93,051

        Tue 01-Jan-19 (00:00)
        Jan.2019

        16,131

        13,889

        43,909

        20,474

        14,334

        49,142

        36,605

        28,223

        93,051

        Sat 01-Dec-18 (00:00)
        Dec.2018

        16,131

        13,889

        43,909

        20,474

        14,334

        49,142

        36,605

        28,223

        93,051

        Thu 01-Nov-18 (00:00)
        Nov.2018

        16,131

        13,889

        43,909

        20,474

        14,334

        49,142

        36,605

        28,223

        93,051

        Mon 01-Oct-18 (00:00)
        Oct.2018

        16,131

        13,889

        43,909

        20,474

        14,334

        49,142

        36,605

        28,223

        93,051

        Totals:

        145,179

        125,001

        395,181

        184,266

        129,006

        442,278

        329,445

        254,007

        837,459

(please ignore the classes that don't appear in the style tag)
When the footer-fixed class is not applied, the footer columns match with the rest of the table. What might be the easiest way of making them line up when footer-fixed is applied?

A: If I understood you well, you can use CSS Grid for that. Make your head and foot fixed and the body scrollable with the height you want to.
table {
  display: inline-grid;
  grid-template-areas:
  "head-fixed"
  "body-scrollable"
  "foot-fixed";
}

thead {
  grid-area: head-fixed;
}

tbody {
  grid-area: body-scrollable;
  overflow: auto;
  height: calc(100vh - 100px);
}

tfoot {
  grid-area: foot-fixed;
}

th, td {
  min-width: 80px;
}

https://jsfiddle.net/5zy9ujd3/
(play resizing the result area to check if that's what you're looking for)
Hope this help :)

A: Probably could check position: sticky, but it quite new API so be careful with old browsers. MDN


text:
Q: iPhone: Valid signing identity not found annoying error I know that this is very common problem and I have gone through almost all the similar threads out here but no luck! This started happening after I renewed my membership with Apple!
I have confirm that I have private and public key in Key Chain, the required certificate listed under My Certificate, have my development certificate, and AWDR certificated installed but still under XCode organizer I get message saying "profile doesn't match any valid certificate/private key pair in default key chain". I also restarted mac twice.
Also I have confirmed everything mentioned at http://developer.apple.com/library/ios/#qa/qa1618/_index.html
What else to do? I have been scratching my head since last 3-4 hours now without any luck!
Thanks.

A: You could try and have a look at the project.pbxproj located inside the .xcodeproj package (open it by right clicking and select 'Show package contents'). Search the file for PROVISIONING_PROFILE and make sure everything checks out to the correct profiles. I've had problems in the past when Xcode doesn't really update this file but when I do it manually it works.

A: After so much pain I exported keys from other MAC where it works and imported on my Machine and RESTARTED MAC then it started working!
I could have revoked the certificates and create them from scratch so while generating CA Authority request certificate private keys would be generated on my machine. Learn to save these keys in .p12 format on shared location so that you simply need to double click to install it again!


text:
Q: Laravel Redis Failed work:queue --tries=3 --stop-when-empty I have Queue work failed issue with Laravel 5.7 when i dispatch my job into redis queue.So any one can help on this?
public function forgotPassword(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => 'required|email',
    ]);
    if ($validator->fails()) {
        return response()->json(['error' => $validator->errors()], 401);
    }
    $input = $request->all();
    $users = User::where('email', $input['email'])
    ->where('is_active', false)
    ->firstOrFail();
    if (!$users) {
        return response()->json(['error' => 'Bad request'], 400);
    }

    $user_id = $users->id;

    $this->dispatch(
        new SendEmailCommand($user_id)
    );

    $success['message'] = 'Your request has been processed successfully. Please check your email.';
    $success['response'] = true;

    return response()->json(['success' => $success], $this->successStatus);
}

and This is My SendEmailCommand.php
class SendEmailCommand extends Command implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wasel-sendEmail:verify{user}';
    public $tries = 3;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sending Email to authorized email.';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $user_id = $this->argument('user');
        $users = User::find($user_id);
        $bar = $this->output->createProgressBar(count($users));
        $email = $users->email;

        try {
            Mail::to($email)->send(new SendEmailMailable());
            $bar->advance();
            Log::info('otp fetched successfully.'.$email);
            //$bar->advance();
        } catch (Exception $e) {
            $this->error('Something went wrong!'.$e->getMessage());
        }

        $message = '--Sending Email through SMTP Command--';
        Log::info($message);
        $bar->finish();
        $this->info('Done!');
        //return $this->release(10);
    }

    /**
     * Determine the time at which the job should timeout.
     *
     * @return \DateTime
     */
    public function retryUntil()
    {
        return now()->addSeconds(10);
    }
}

Also I have Laravel.log Max attempts exceeded
    [2018-09-26 20:21:54] local.ERROR: App\Console\Commands\SendEmailCommand has been attempted too many times or run too long. The job may have previously timed out. {"exception":"[object] (Illuminate\\Queue\\MaxAttemptsExceededException(code: 0): App\\Console\\Commands\\SendEmailCommand has been attempted too many times or run too long. The job may have previously timed out. at /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Queue/Worker.php:401)
[stacktrace]
#0 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(321): Illuminate\\Queue\\Worker->markJobAsFailedIfAlreadyExceedsMaxAttempts('redis', Object(Illuminate\\Queue\\Jobs\\RedisJob), 3)
#1 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(277): Illuminate\\Queue\\Worker->process('redis', Object(Illuminate\\Queue\\Jobs\\RedisJob), Object(Illuminate\\Queue\\WorkerOptions))
#2 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(118): Illuminate\\Queue\\Worker->runJob(Object(Illuminate\\Queue\\Jobs\\RedisJob), 'redis', Object(Illuminate\\Queue\\WorkerOptions))
#3 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\\Queue\\Worker->daemon('redis', 'default', Object(Illuminate\\Queue\\WorkerOptions))
#4 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\\Queue\\Console\\WorkCommand->runWorker('redis', 'default')
#5 [internal function]: Illuminate\\Queue\\Console\\WorkCommand->handle()
#6 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)
#7 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#8 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(Illuminate\\Foundation\\Application), Array, Object(Closure))
#9 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Container/Container.php(564): Illuminate\\Container\\BoundMethod::call(Object(Illuminate\\Foundation\\Application), Array, Array, NULL)
#10 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\\Container\\Container->call(Array)
#11 /usr/local/var/www/wasel-jwt/vendor/symfony/console/Command/Command.php(251): Illuminate\\Console\\Command->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#12 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))
#13 /usr/local/var/www/wasel-jwt/vendor/symfony/console/Application.php(886): Illuminate\\Console\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#14 /usr/local/var/www/wasel-jwt/vendor/symfony/console/Application.php(262): Symfony\\Component\\Console\\Application->doRunCommand(Object(Illuminate\\Queue\\Console\\WorkCommand), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#15 /usr/local/var/www/wasel-jwt/vendor/symfony/console/Application.php(145): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#16 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#17 /usr/local/var/www/wasel-jwt/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#18 /usr/local/var/www/wasel-jwt/artisan(37): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))
#19 {main}
"}

Also I have tried to change queue.php failed_job connection into redis
'failed' => [
        'database' => env('DB_CONNECTION', 'mysql'),
        'table' => 'failed_jobs',
    ],

I have tried this job to run but unable to run this job.Please help me out?


text:
Q: Extract urls from string with JavaScript I am working on a link preview script like fb uses it for example. The user creates a post that could potentially include links. On every keyup i test if the last key has been the space key and if that was the case i run my function:
function link_preview(event)
{
    var replyText = $("#answer_two").val();

    if(event.keyCode == 32)
    {
        var match = /^(?:[a-z]*?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i.exec(replyText);

        if(match!="")
        {

            var preview = match[0];
        }
    }
}

So the user types a text that includes a link. When the link is detected a preview is shown with the information fetched from this url. The user has the option to close this preview and to add another link and this is exactly where my problems start. I can not access the second url and ignore the first. And all this gets even more complicated if a third url would be added to the mix.
Has anyone a suggestion on how to work this?

A: Have you tried adding the global parameter to you're regex of "g" next to you're "i" at the end of your regex so it looked something like:
/^(?:[a-z]*?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/gi
in this case you will get multiple matches across a string in which you will need to loop through.
reference at actual fix: http://jsfiddle.net/ps1rf1uw


text:
Q: Ember.js with Rails 3.1 getting error "Unable to find template" I'm trying to setup Ember.js with Rails 3.1 and I'm getting the following error in the Firebug console:
uncaught exception: Error: <(subclass of App.ListOrdersView):ember201> - Unable to find template "app/templates/orders/list".

I followed this guide. Here is my manifest file, which correctly loads all the js:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require vendor/ember
//= require vendor/ember-rest
//= require_tree ./../lib
//= require app/app
//= require_tree ./../app/models
//= require_tree ./../app/controllers
//= require_tree ./../app/views
//= require_tree ./../app/helpers
//= require_tree ./../app/templates
//= require_self

This is the handlebar template app/templates/order/list.handlebars:

      ID
      Name

  {{#each orders}}
    {{view App.ShowOrderView orderBinding="this"}}
  {{/each}}

And the Rails view file app/views/orders/index.html.haml
%script{:type => "text/x-handlebars"}
  = hb 'view App.ListOrdersView'

:javascript
  $(function() {
    App.ordersController.loadAll(#{@orders.to_json.html_safe});
  });

Finally the gems for Ember.js, in Gemfile:
# Ember
gem 'ember-rails'
gem 'hamlbars', :git => "https://github.com/jamesotron/hamlbars.git"
gem 'rasputin'

A: check the paths, maybe they should be
//= require_tree ./app/models
//= require_tree ./app/controllers
//= require_tree ./app/views
//= require_tree ./app/helpers
//= require_tree ./app/templates

Unable to find template app/templates/order*s*/list
This is the handlebar template app/templates/order/list.handlebars:
see the path difference in s

A: You should probably use either ember-rails or rasputin, but using both gems together might lead to unpredictable behavior. Since they both attempt to register and precompile your handlebars templates, they are redundant in purpose but their usage differs.
If you look at the readme for rasputin, you'll see that templates get registered without templates in their path. Therefore, if you want to use this gem, you'll need to declare your template as app/orders/list instead of app/templates/orders/list in App.ListOrdersView.

A: I ran into similar issues when changing template definitions and ember gems. Although the error was the same (complaining about the template path - even though the paths all seemed correct), all it took was a rake assets:clean to get things sorted out.


text:
Q: How can i profile a device for memory and cpu vise, to decide image resolution for heavy image processing? I have an app which takes photo and then process it in NDK. The image processing is really havy and i want to take different resolution images on different phones. So my simple logic is taking higher resolution image for powerfull images and taking lower res. images on low end devices. There are three criteria first two are memory and cpu, if i take a full res image on low end phone like galaxy s it will crash during the image processing because of lack of memory. And it will take forever to process image. Third one is camera picture sizes. So here is my question, how can i profile a device and decide for the resolution of the image?
PS: I am doing image processing with OPENCV so GPU is not an option.
PS2: Since i can't make comments i should clarify that i am not trying to profile my own code i am trying to profile devices that users will use.

A: I suggest Valgrind. It supports ARM-based and X86 Android for profiling and memory leak detection.


text:
Q: Python Selenium geckodriver path My script look that way:
from selenium import webdriver
driver = webdriver.Firefox(executable_path='/bin/geckodriver.exe')
driver.get('http://inventwithpython.com')

There is an error like this:
Traceback (most recent call last):
  File "/home/natalia/.local/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 76, in start
    stdin=PIPE)
  File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
    raise child_exception_type(errno_num, err_msg)
PermissionError: [Errno 13] Permission denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "slm.py", line 4, in <module>
    driver = webdriver.Firefox(executable_path='/bin/geckodriver.exe')
  File "/home/natalia/.local/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 164, in __init__
    self.service.start()
  File "/home/natalia/.local/lib/python3.5/site-packages/selenium/webdriver/common/service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver.exe' executable may have wrong permissions.

I put geckodriver to folder bin.. And now I don't know what to do.
Please give ma an advice.


text:
Q: Lifecycle of a script or a plugin in Javascript or jQuery I'm almost new to web developing and I'm facing to Javascript/jQuery. I would like to understand how a script is executed in an html page. I'm a C/Java programmer and references to these languages could help me.
I understood that a script can be inserted in the header or at the end of the body if we want to execute it after the page is loaded. I know that a function can be called by a DOM event (I associate events to interrupt signals). What I would like to know is if a script like this:
<script type="text/javascript">
//<![CDATA[
var i=10;
if (i<5)
  {
  // some code
  }
//]]>
</script>

in the body or in the head element is executed only once or is executed continuously. Does jQuery behave in the same way as Javascript?
What about plugins? Do they live for all the time a page is shown (like a parallel thread) or are they event driven (they are called by clicking/resizing etc or using timers)?
I know that is a very general question and that probably it cannot be explained in a few lines but some basic explanation and a link to some documentation would be very appreciated.
Thank you!

A: jQuery is just a library written in JavaScript that mainly simplifies DOM manipulation and working with AJAX requests. If you want to understand how JS works, forget about jQuery for a moment.
Regarding script execution: The browser parses the HTML and creates a DOM out of it. When the browser encounters a <script> tag and its content, it creates a DOM element for it, adds it to the tree and executes the code. Then it continues parsing the next tag, which implies that the code is only executed once.
The reason for executing the script during parsing is that the script can already manipulate the HTML right away (using, e.g. document.write (not good practice though)) and therefore change what the parser has to parse. Script execution can be deferred using the defer attribute, until the document is fully parsed (I haven't seen the attribute very often in live code until now though).
All script tags share the same scope, the global scope and the execution environment persists until you navigate away or reload the page. So, defining a variable in one script and accessing it in the other is perfectly valid and in fact is what you are doing when you include libraries like jQuery in your page.
<script>
    var foo = 'bar';
</script>
<!-- other HTML code -->
<script>
    alert(foo);
</script>

You might find the HTML documentation about scripts helpful.

A: The script will execute top-to-bottom, once, just like anything else you load in the page. However, part of that loading will be to interact with the DOM (Document Object Model, or the browser's internal representation of the webpage), including registering event handlers etc.; thereafter events like clicks, AJAX responses, etc. can trigger JS functions.
If you're used to Java UI development, then callbacks and event-based programming will be familiar to you; if you're used to procedural coding then it'll be a bit of a learning curve.

A: The code above will only execute once.
jQuery is javascript based and yes, of course, behaves the same way as javascript. jQuery makes javascript easier, and also deals with browser specific issues.
Javascript code is executed at runtime if it is written like in your example, but it may also be event driven. The lifecycle of the results of your code remain until you refresh your browser page. The lifecycle of a javascript may also be continuous if you are using timers.

A: Some scripts just create functions and objects that can be called by events later, some scripts actually do something to the DOM as the page loads, some scripts just register listeners.
jQuery and their plugins just create object/functions that can later be called by event handlers.