text:
Q: Google Maps app crash reporting I've written this google maps app a while ago and I worked, but when I tried to run in on an Android device with Android version 6.0, it showed the Google map, but it didn't showed the current location of the user on the map and neither did an icon on the upper-right side to refresh the app and make the location more accurate if possible... When I run it on Android 5.1, it showed me even more errors and it didn't worked at all.
please help :(
This is the AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.francydarkcool.maps">

<!-- Google Maps for Android v2 requires OpenGL ES v2 -->
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<permission
    android:name="com.example.francydarkcool.maps.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.francydarkcool.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/xxxxx" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Welcome">
        android:label="@string/Welcome">

    </activity>
</application>
</manifest>

This is the .java file:
package com.example.francydarkcool.maps;

import ...

public class MapsActivity extends FragmentActivity {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the MapFragment and get notified when the map is ready to be used.
    MapFragment mapFragment = (MapFragment) getFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            if (ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mMap.setMyLocationEnabled(true);
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    });

    setUpMapIfNeeded();
}

protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    //Do a null check to see if the map is not already instantiated
    if (mMap == null)
        //try to obtain the map from the MapFragment.
 //           mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(onMapReady(mMap));

    {
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                if (ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                mMap.setMyLocationEnabled(true);
                // Check if we were successful in obtaining the map.
                if (mMap != null) {
                    setUpMap();
                }

            }
        });
    }
    //check if successful
    if (mMap != null) {
        setUpMap();
    }
}

private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(45.402850, 25.518595)).title("unu"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(45.402856, 25.518608)).title("doi"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(45.402834, 25.518772)).title("trei"));

    //Enable MyLocation Layer of Google Map
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }

    mMap.setMyLocationEnabled(true);

    //Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    //Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    //Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    //Get current location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    if(myLocation != null){
        double latitude = myLocation.getLatitude();
        double longitude = myLocation.getLongitude();
        }
    else
    {
        Location   getLastLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        double longitude = getLastLocation.getLongitude();
        double latitude = getLastLocation.getLatitude();
    }

    //set map type
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //Get latitude of the current location
    double latitude = myLocation.getLatitude();

    //Get longitude of the current location
    double longitude = myLocation.getLongitude();

    //Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    //Show the current location in Google Maps
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    //Zoom in GoogleMap
    mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
}

}

this is activity_maps.xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.francydarkcool.maps.MapsActivity" />

And finally, these are the errors on running on Android 6.0:
E/FirebaseCrash: Failed to initialize crash reporting
             java.lang.RuntimeException: Missing an expected resource: 'R.string.google_api_key' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
                 at com.google.firebase.crash.internal.api.FirebaseCrashApiImpl.init(:com.google.android.gms.DynamiteModulesC:1089)
                 at bqs.onTransact(:com.google.android.gms.DynamiteModulesC:60)
                 at android.os.Binder.transact(Binder.java:387)
                 at com.google.firebase.crash.internal.zzd$zza$zza.zza(Unknown Source)
                 at com.google.firebase.crash.FirebaseCrash.<init>(Unknown Source)
                 at com.google.firebase.crash.FirebaseCrash.getInstance(Unknown Source)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.google.firebase.FirebaseApp.zza(Unknown Source)
                 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                 at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                 at com.google.firebase.FirebaseApp.zzeh(Unknown Source)
                 at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                 at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
                 at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
                 at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                 at android.app.ActivityThread.installProvider(ActivityThread.java:5153)
                 at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
                 at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
                 at android.app.ActivityThread.-wrap1(ActivityThread.java)
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
                 at android.os.Handler.dispatchMessage(Handler.java:102)
                 at android.os.Looper.loop(Looper.java:148)
                 at android.app.ActivityThread.main(ActivityThread.java:5417)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

And these ones are from running the same app on Android 5.1:
E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
I/art: Not late-enabling -Xcheck:jni (already on)
W/art: Failed to find OatDexFile for DexFile /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_9-classes.dex ( canonical path /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_9-classes.dex) with checksum 0x96c9987f in OatFile /data/data/com.example.francydarkcool.maps/cache/slice-slice_9-classes.dex
W/art: Failed to find OatDexFile for DexFile /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_8-classes.dex ( canonical path /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_8-classes.dex) with checksum 0xfb6fb639 in OatFile /data/data/com.example.francydarkcool.maps/cache/slice-slice_8-classes.dex
W/art: Failed to find OatDexFile for DexFile /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_4-classes.dex ( canonical path /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_4-classes.dex) with checksum 0x91648fd3 in OatFile /data/data/com.example.francydarkcool.maps/cache/slice-slice_4-classes.dex
W/art: Failed to find OatDexFile for DexFile /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_2-classes.dex ( canonical path /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_2-classes.dex) with checksum 0x44af1327 in OatFile /data/data/com.example.francydarkcool.maps/cache/slice-slice_2-classes.dex
W/art: Failed to find OatDexFile for DexFile /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_0-classes.dex ( canonical path /data/data/com.example.francydarkcool.maps/files/instant-run/dex/slice-slice_0-classes.dex) with checksum 0x3993f84f in OatFile /data/data/com.example.francydarkcool.maps/cache/slice-slice_0-classes.dex
W/art: Verification of void com.google.firebase.FirebaseApp.<clinit>() took 273.032ms
W/art: Suspending all threads took: 16.600ms
I/art: Background sticky concurrent mark sweep GC freed 1202(325KB) AllocSpace objects, 11(244KB) LOS objects, 33% free, 1248KB/1872KB, paused 18.204ms total 30.940ms
A/FirebaseApp: Firebase API initialization failure.
               java.lang.reflect.InvocationTargetException
                   at java.lang.reflect.Method.invoke(Native Method)
                   at java.lang.reflect.Method.invoke(Method.java:372)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.zzeh(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at enter code hereandroid.app.ActivityThread.installProvider(ActivityThread.java:4999)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:4594)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4534)
                   at android.app.ActivityThread.access$1500(ActivityThread.java:151)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:135)
                   at android.app.ActivityThread.main(ActivityThread.java:5254)
                   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:903)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                Caused by: java.lang.IllegalArgumentException: Given String is empty or null
                   at com.google.android.gms.common.internal.zzab.zzhs(Unknown Source)
                   at com.google.android.gms.internal.zzafl$zza$zza.<init>(Unknown Source)
                   at com.google.firebase.auth.FirebaseAuth.zza(Unknown Source)
                   at com.google.firebase.auth.FirebaseAuth.<init>(Unknown Source)
                   at com.google.android.gms.internal.zzafw.<init>(Unknown Source)
                   at com.google.firebase.auth.FirebaseAuth.zzc(Unknown Source)
                   at com.google.firebase.auth.FirebaseAuth.zzb(Unknown Source)
                   at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at java.lang.reflect.Method.invoke(Method.java:372)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.zzeh(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:4999)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:4594)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4534)
                   at android.app.ActivityThread.access$1500(ActivityThread.java:151)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:135)
                   at android.app.ActivityThread.main(ActivityThread.java:5254)
                   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:903)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
W/ResourcesManager: Asset path '/system/framework/com.android.media.remotedisplay.jar' does not exist or contains no resources.
W/ResourcesManager: Asset path '/system/framework/com.android.location.provider.jar' does not exist or contains no resources.
D/ChimeraCfgMgr: Reading stored module config
I/DynamiteModule: Considering local module com.google.android.gms.flags:0 and remote module com.google.android.gms.flags:1
I/DynamiteModule: Selected remote version of com.google.android.gms.flags, version >= 1
I/art: Background sticky concurrent mark sweep GC freed 889(190KB) AllocSpace objects, 8(312KB) LOS objects, 12% free, 3MB/4MB, paused 5.892ms total 35.575ms
W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
I/DynamiteModule: Considering local module com.google.android.gms.crash:0 and remote module com.google.android.gms.crash:3
I/DynamiteModule: Selected remote version of com.google.android.gms.crash, version >= 3
I/art: Background partial concurrent mark sweep GC freed 878(186KB) AllocSpace objects, 8(177KB) LOS objects, 39% free, 3MB/6MB, paused 6.096ms total 49.027ms
D/ChimeraFileApk: Primary ABI of requesting process is x86
D/ChimeraFileApk: Classloading successful. Optimized code found.
I/FirebaseCrashApiImpl: FirebaseCrashApiImpl created by ClassLoader com.google.android.chimera.container.internal.DelegateLastPathClassLoader[DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/00000002/DynamiteModulesC_GmsCore_prodlmp_alldpi_release.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]]
I/DynamiteModule: Considering local module com.google.android.gms.flags:0 and remote module com.google.android.gms.flags:1
I/DynamiteModule: Selected remote version of com.google.android.gms.flags, version >= 1
E/FirebaseCrash: Failed to initialize crash reporting
                 java.lang.RuntimeException: Missing an expected resource: 'R.string.google_api_key' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
                     at com.google.firebase.crash.internal.api.FirebaseCrashApiImpl.init(:com.google.android.gms.DynamiteModulesC:1089)
                     at bqs.onTransact(:com.google.android.gms.DynamiteModulesC:60)
                     at android.os.Binder.transact(Binder.java:380)
                     at com.google.firebase.crash.internal.zzd$zza$zza.zza(Unknown Source)
                     at com.google.firebase.crash.FirebaseCrash.<init>(Unknown Source)
                     at com.google.firebase.crash.FirebaseCrash.getInstance(Unknown Source)
                     at java.lang.reflect.Method.invoke(Native Method)
                     at java.lang.reflect.Method.invoke(Method.java:372)
                     at com.google.firebase.FirebaseApp.zza(Unknown Source)
                     at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                     at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                     at com.google.firebase.FirebaseApp.zzeh(Unknown Source)
                     at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                     at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
                     at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
                     at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                     at android.app.ActivityThread.installProvider(ActivityThread.java:4999)
                     at android.app.ActivityThread.installContentProviders(ActivityThread.java:4594)
                     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4534)
                     at android.app.ActivityThread.access$1500(ActivityThread.java:151)
                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
                     at android.os.Handler.dispatchMessage(Handler.java:102)
                     at android.os.Looper.loop(Looper.java:135)
                     at android.app.ActivityThread.main(ActivityThread.java:5254)
                     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:903)
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I/FA: App measurement is starting up, version: 9256
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
D/FA: Debug logging enabled
D/FA: AppMeasurement singleton hash: 181984923
V/FA: Collection enabled
V/FA: App package, google app id: com.example.francydarkcool.maps, angular-yen-123616
V/FA: Registered activity lifecycle callback
I/FirebaseInitProvider: FirebaseApp initialization successful
W/FA: Measurement Service called with unknown id version: angular-yen-123616
V/FA: Using measurement service
V/FA: Connecting to remote service
V/FA: onActivityCreated
W/art: Suspending all threads took: 8.612ms
I/art: Background sticky concurrent mark sweep GC freed 7219(1116KB) AllocSpace objects, 29(628KB) LOS objects, 27% free, 4MB/6MB, paused 11.350ms total 48.117ms
I/zzae: Making Creator dynamically
D/ChimeraFileApk: Primary ABI of requesting process is x86
D/ChimeraFileApk: Classloading successful. Optimized code found.
I/Google Maps Android API: Google Play services client version: 9256000
I/Google Maps Android API: Google Play services package version: 9256270
I/c: Token loaded from file. Expires in: 30813655 ms.
I/c: Scheduling next attempt in 30513 seconds.
V/FA: Activity resumed, time: 125857
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                  [ 07-24 12:04:31.463  2501: 2501 D/         ]
                  HostConnection::get() New Host Connection established 0xa282ed00, tid 2501
D/Atlas: Validating map...
D/AndroidRuntime: Shutting down VM

                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.francydarkcool.maps, PID: 2501
                  java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
                      at com.example.francydarkcool.maps.MapsActivity.setUpMap(MapsActivity.java:149)
                      at com.example.francydarkcool.maps.MapsActivity.access$100(MapsActivity.java:18)
                      at com.example.francydarkcool.maps.MapsActivity$1.onMapReady(MapsActivity.java:46)
                      at com.google.android.gms.maps.MapFragment$zza$1.zza(Unknown Source)
                      at com.google.android.gms.maps.internal.zzp$zza.onTransact(Unknown Source)
                      at android.os.Binder.transact(Binder.java:380)
                      at xk.a(:com.google.android.gms.DynamiteModulesB:82)
                      at maps.af.t$5.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      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:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:1
I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 1
D/ChimeraFileApk: Primary ABI of requesting process is x86
D/ChimeraFileApk: Classloading successful. Optimized code found.
D/GoogleCertificates: com.google.android.gms.googlecertificates module is loaded
D/GoogleCertificatesImpl: Fetched 318 Google certificates
I/Process: Sending signal. PID: 2501 SIG: 9
Application terminated.

And this is the gradle.build file:
apply plugin: 'com.android.application'

android {
compileSdkVersion 24
buildToolsVersion '24.0.0'
defaultConfig {
    applicationId "com.example.francydarkcool.maps"
    minSdkVersion 16
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
productFlavors {
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.google.android.gms:play-services:9.2.1'
compile 'com.google.android.gms:play-services-maps:9.2.1'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha4'
testCompile 'junit:junit:4.12'
compile 'com.android.support:support-v4:24.1.0'
}

A: Do you have google_maps_api.xml file?
You need to register for a Google Maps API key.  For more information as to what else is needed to use Google services.  Please see the following documentation under Step 4.
https://developers.google.com/maps/documentation/android-api/start
Step 4. Get a Google Maps API key
Your application needs an API key to access the Google Maps servers. The type of key you need is a Key for Android applications. The key is free. You can use it with any of your applications that call the Google Maps Android API, and it supports an unlimited number of users.
Choose one of the following ways to get your API key:
The fast, easy way: Use the link provided in the google_maps_api.xml file that Android Studio created for you:
Copy the link provided in the google_maps_api.xml file and paste it into your browser. The link takes you to the Google API Console and supplies information via URL parameters, thus reducing the manual input required from you.
Follow the instructions to create a new project on the console or select an existing project.
Create an Android API key for your console project.
Copy the resulting API key, go back to Android Studio, and paste the API key into the  element in the google_maps_api.xml file.
A slightly less fast way: Use the credentials provided in the google_maps_api.xml file that Android Studio created for you:
Copy the credentials provided in the google_maps_api.xml file.
Go to the Google API Console in your browser.
Use the copied credentials to add your app to an existing API key or to create a new API key. For more details, see the complete process.
The full process for getting an API key: If neither of the above options works for your situation, follow the complete process.
Specifically, you can fix this issue by downloading and copying the google-services.json file for your Android app by following the steps below:
Select your app/project name and Android packagename from this link and click Continue to Choose and configure services.
Click Continue to Generate Configuration files.
Download google-services.json and copy the file to the app/ or mobile/ module directory in your Android project.


text:
Q: Why does unplugging and plugging back in my laptop power cable result in a short, sharp, immediate speed boost to all processes? So I've got a cheap, barebones Lenovo Windows 10 laptop and I've noticed a fascinating behaviour whenever I toggle (unplug and then immediately plug back in) the power cable: I get an immediate burst of what seems to be raw CPU processing speed that lasts for perhaps a minute. If I've just opened five tabs in Chromium or Firefox, for example, and they're all struggling a little to load and showing spinners, toggling the power leads them all to load to completion within seconds. I don't think it's IO-bound or related to any specific application, however, since if I'm having trouble getting a Explorer window to come up after selecting it from the taskbar, the same toggling process produces quasi-instant effects there too. Likewise, it speeds up laggy form entry on webpages that have already fully loaded and reduces the loading time of heavy-duty Qt-based GUI apps (the sort of apps that have actual loading bars on splash screens). Essentially, it's as if the clock speed temporarily increases far beyond its sane limit.
I can't see how this could possibly be related to my power options, since it only occurs after plugging the cable back in (i.e. same power profile). Although, being such a weird behaviour, I suppose it could be linked to some generic switching process in the kernel. Regardless, the power settings are essentially the same for both battery and plugged-in: the only significant difference for the CPU is that the cooling option on battery is set to Passive (Active for powered). But I can't see an obvious mechanism by which that would cause the observed phenomenon. And, in fact, I just set them both to Active to see what happens and it doesn't seem to be make any difference (though it's admittedly hard to replicate de novo).
The behaviour also doesn't ever seem to happen in normal use outside of the singular context of toggling the power. It doesn't work in reverse, either. If anything, unplugging the power slows the laptop down, despite the identical power options (maybe relevant, IDK?). The phenomenon I'm describing is consistent and replicable across months and months to the point where it can't just be a placebo effect from the laptop going from battery-slow to powered-fast (critically, the toggle takes <1 second; far too quick for the slower battery power to make a jot of difference in the grand scheme of things with a process that was hanging/lagging for minutes beforehand).
There are so many potential variables here and a non-existent presence around this phenomenon online, despite my many searches (to be fair, though, it is damn hard to know what exactly to search for in this case). I suppose it could be somehow related to disk IO (though this is an eMMC drive with a 1.2GHz base AMD 3020e, which immediately makes me think CPU over disk). Yeah, the CPU does have a 2.4GHz boost, which could also theoretically be related. But, really, it could be related to anything. That's my problem. And I'm not even really sure how to start to "diagnose" the "problem" (insofar as it needs diagnosing). I'm an experienced Windows power user and programmer but the behaviour I'm describing is so broad and ill-defined that it's utterly vexing me. There's so much invisible and inaccessible stuff in the kernel that could be happening: it only takes one small bug in the kernel or a weird interaction between a driver and the kernel to generate such strange behaviour.
I'm not expecting anyone to be able to answer this one (at least not right off the bat), but I thought I'd at least give it a shot. If SuperUser can't generate a plausible theory, nobody can, as far as I'm concerned. And in that spirit, I'd appreciate your theories, no matter how far-out they may be. This is the kind of nonsense where a small buffer overflow in some user mode program may be reporting garbage data to some kernel component over COM that flips a single boolean in a bitfield somewhere and results in a slightly different instruction being issued to a driver that is then vaguely adjacent to the battery controller, causing it to do x instead of y. That's just a dumb, arbitrary example of the kind of amplification or butterfly effect process that might be taking place in a flipped conditional in some miniscule fragment of code somewhere. Or it might be far more straightforward. Who knows, amirite? Due to the fact that I overwhelmingly prefer desktops (and non-Win10 OSs), I'm not as au fait with Windows 10 battery handling internals as I'd ideally like, and maybe someone with that knowledge can fill in some gaps.
Thanks for reading all of that and for any ideas you can offer!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent Twig from adding form-control class to the fields it generates? I have this code:
{% for key, customField in customFields %}
   {{ form_widget(formVirtualTerminal['cf_' ~ key], { 'attr': {'placeholder': customField['FieldDisplayName'], 'name': customField['FieldName'], 'class' : 'row no-gutters mb-3'} }) }}
{% endfor %}

which traverses an array and outputs some fields for it. However, for reasons unknown to me, a form-control class is generated into all these fields and that ruins the design of the page.
In this question (delete form-control in form-row symfony/twig) it's mentioned that this is part of a default Bootstrap theme and they discuss how this theme can be deactivated on application level.
However, I prefer not to do such radical changes if possible. I would like to tell Twig not to add classes.
The following is a hack which solves the problem by removing that class:
$("#custom-text-field-container .form-control").removeClass("form-control");

However, I would like to avoid writing Javascript to remove classes from fields which should never had that class in the first place.
Is there a way to tell twig not to write form-control class into these text fields?

A: You can't prevent it without making changes to the theme
You can't "tell twig not to add classes".
The form_widget does not accept any parameter to remove a class or attribute that will be later applied by the theme.
Basically, it has no control over what the template does, it only passes the template whatever parameters you want, and it's up to the form template how to use that information.
E.g. for HTML classes, the usual approach is simply to merge whatever classes you pass with whatever classes the template has set by default.

Workaround while keeping most of the form theme you are using
A simple recourse would be to create to your theme based on the form theme you are using (which seems to be 'bootstrap_4_layout.html.twig')
You'd need to rewrite only the parts that hinder you, leaving everything else as it is.
E.g. a "complete" new theme could be as short as:
{# templates/form/your_theme.html.twig #}
{% use 'bootstrap_4_layout.html.twig' %}

{% block form_widget_simple -%}
    {% if type is not defined or type != 'hidden' %}
        {%- set attr = attr|merge({class: (attr.class|default('') ~ (type|default('') == 'file' ? ' custom-file-input' : ''))|trim}) -%}
    {% endif %}
    {%- if type is defined and (type == 'range' or type == 'color') %}
        {# Attribute "required" is not supported #}
        {%- set required = false -%}
    {% endif %}
    {{- parent() -}}
{%- endblock form_widget_simple %}

This is almost the same form_widget_simple block as the original, I simply removed the form-control class that is merged with the classes you can pass through.
You can use this form only in the templates you want this custom theme by doing this in the appropriate template:
{% form_theme form 'form/your_theme.html.twig' %}

Or if you want to use it by default in all forms in your application:
# config/packages/twig.yaml
twig:
    form_themes: ['form/your_theme.html.twig']
    # ...


text:
Q: isolate cpu cores (physical or logical?) Am I right thinking that a kernel parameter 'isolcpus' accepts physical core ID? So if I have 4 physical cores, and hyper-threading enabled, which gives me total 8 cores, then I'm only allowed to specify cpu cores 1..3 in isolcpus parameter (core0 goes for OS)?
Thanks.

A: Red Hat guru Daniel Macpherson said in a Red Hat community discussion:

So you might need to restrict the kernel from accessing the CPUs you have pinned to the instance. For example, let's say I have an 8 core CPU with dual hyper-threading, which results in 16 vcpus. I want to use core 0 for my OpenStack services and cores 1-7 for instances. I'd need to tell the kernel to leave those cores alone. This means I'd need to tell the kernel to leave alone vcpus 1-7 and 9-15:
$ sudo grubby --update-kernel=ALL --args="isolcpus=1,2,3,4,5,6,7,9,10,11,12,13,14,15"
$ sudo grub2-install /dev/sda
$ sudo reboot

According to that, you specify logical CPU cores for the isolcpus kernel parameter.

A: Is open source.
Documentation/kernel-parameters.txt
isolcpus=   [KNL,SMP] Isolate CPUs from the general scheduler.
        Format:
        <cpu number>,...,<cpu number>
        or
        <cpu number>-<cpu number>
        (must be a positive range in ascending order)
        or a mixture
        <cpu number>,...,<cpu number>-<cpu number>

        This option can be used to specify one or more CPUs
        to isolate from the general SMP balancing and scheduling
        algorithms. You can move a process onto or off an
        "isolated" CPU via the CPU affinity syscalls or cpuset.
        <cpu number> begins at 0 and the maximum value is
        "number of CPUs in system - 1".

        This option is the preferred way to isolate CPUs. The
        alternative -- manually setting the CPU mask of all
        tasks in the system -- can cause problems and
        suboptimal load balancer performance.

If that isn't enough, just search the source for isolcplus and look at how is used.


text:
Q: css style content attribute I have an ordered list where I use counter in content.
Question:
How can I change color to content attribute ( NUMBERS ) only ( e.g. 1.2, 1.3, ... to red ) ?
Note: Looking for CSS only ( no HTML change ! )
HTML:

Item

Item

Item

Item

Item

Item

Item

Item

Item

CSS:
ol {
    list-style-type: none;
    counter-reset: item;
}
ol li:before {
    content: counters(item, ".")". ";
    counter-increment: item
}

Wanted output:

A: To do it for all of the numbers, just add color:red; to your css for the numbers like this
ol li:before {
    content: counters(item, ".")". ";
    counter-increment: item;
    color:red;
}

http://jsfiddle.net/ZSkLE/3/
To to do it for the lower levels (which is what it looked like you wanted to do before editing your question) you could do this..
ol li ol li:before {
    color:red;
}

and to stop the next level being red..
ol li ol li ol li:before {
    color:black;
}

http://jsfiddle.net/ZSkLE/1/


text:
Q: UIButton selector not called I have a UIButton inside a class. I want to set a target for the button like so.
[myController.dateButton addTarget:self action:@selector(showAction:) forControlEvents:UIControlEventTouchUpInside];

For some reason, the selector is never called when I press the button. I tried to debug the problem by doing the following but I get nil for the NSSet
NSSet *allTargets = [myController.dateButton allTargets];

Any suggestions on what I may be doing wrong?
The selector is defined as follows:
- (void)showAction:(id)sender
{
   // Do stuff
}

A: Maybe this be the solution, cz i dnt think there's anything wrong in your code.
When you declare your button as
UIButton* tempBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

never have the release called on that btn.
[tempBtn release];//dont do this!!

I tried this my selves and it was working fine.
- (void)viewDidLoad {
     [super viewDidLoad];

     UIButton* tempBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     tempBtn.frame = CGRectMake(50, 50, 50, 50);
     [tempBtn addTarget:self action:@selector(hello:) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:tempBtn];

}

- (void) hello:(id) sender
{
    NSLog(@"helloooo");
}


text:
Q: Access query to a macro enabled excel template using vba Im trying to put data from a query which requires a parameter into a excel template with marcos in it however I keep getting errors. Im getting the parameter from the form.
heres my code:
Private Sub exportButton_Click()
Dim XL As Excel.Application
Dim wbTarget As Workbook

Dim qdfResults As QueryDef
Dim rsResults As Recordset

'Set up refernce to the query to export

Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition

'Execute Query
Set rsResults = qdfResults.OpenRecordset()

'reference excel
Set XL = CreateObject("Excel.Application")
'refernce workbook
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documen…\folder\resultTemplate.xltm")

'clear excel sheet
wbTarget.Worksheets("marktable").Cells.ClearContents

'paste data from query to worksheet
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults

'save workbook
** 1) 'wbTarget.SaveAs ("C:\Users\user\Documents
\folder\resultTemplate1.xlsm")
** 2) wbTarget.SaveAs FileName:="C:\Users\user\Documents\folder\resultTemplate1.xlsm",

FileFormat:=xlOpenXMLWorkbookMacroEnabled

'clear variables
Set wbTarget = Nothing
Set XL = Nothing
Set qdfResults = Nothing
End Sub

with 1) i could get the data into a work book but without the macros
with 2) i can get the data in and macro but wont save properly
any suggestions?
EDIT**
by wont save properly i mean that it is creating a temperory file that i cannot save
and now it wont even created that, now its creating a file with 0 bytes and no type
cant answer by own question yet but until I can heres my working code:
The only problem I can see was that wbTarget.Close and XL.Quit werent used which caused the module to still run and the file therefore wasn't completely saved but temporary. Credit to @Gord Thompson
Private Sub exportButton_Click()

Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset

Set XL = New Excel.Application
Set wbTarget =    XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")

Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
  qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()

wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults

wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit

End Sub

A: Strange behaviour in Office automation projects can often be the result of failing to properly Close objects and Quit applications. In this case adding
wbTarget.Close

and
XL.Quit

statements appears to have resolved the issue.

A: The only problem I can see was that wbTarget.Close and XL.Quit werent used which caused the module to still run and the file therefore wasn't completely saved but temporary. Credit to @Gord Thompson
Private Sub exportButton_Click()

Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset

Set XL = New Excel.Application
Set wbTarget =    XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")

Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
  qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()

wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults

wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit

End Sub


text:
Q: Can not start composer-cli I followed the instructions to install the hyperledger tools on Ubuntu 18.04. Due to a permission problem I had to change the node_modules directory.
I can run the tools, except composer-cli (composer-cli: command not found).
Installation log:
$ npm install -g composer-cli@0.20
...

WARN engine fabric-client@1.2.1: wanted: {"node":"^8.9.0","npm":"^5.5.1"} (current: {"node":"8.10.0","npm":"3.5.2"})
    /home/asset-tracker/.npm-global/bin/composer -> /home/asset-tracker/.npm-global/lib/node_modules/composer-cli/cli.js
    /home/asset-tracker/.npm-global/lib
    └── composer-cli@0.20.4

npm WARN optional Skipping failed optional dependency /composer-cli/chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.2.4

A: Well, as seen in the log snippet. I think you should try to upgrade the version of npm.
hyperledger-composer supports Ubuntu Linux 14.04 / 16.04 LTS (both 64-bit). Installing to 18.04 might facing unexpected error. installing prereqs


text:
Q: How to save picture using ionic camera preview I'm developing a mobile application using Ionic 4. Everything is working smoothly, but i could not save the picture when i call the function takePicture(). Does it have any parameters like saveToPhotoAlbum in Ionic Camera Plugin. Do help me out.

  cameraPictureOpts: CameraPreviewPictureOptions = {
    width: window.innerWidth,
    height: window.innerHeight,
    quality: 100
  }

  takePicture() {
    let result = this.cameraPreview.takePicture(this.cameraPictureOpts);
    let picture = `data:image/jpeg;base64,${result}`;
  }

A: You can save the image in a local variable.
selectedImage: any;

pictureOpts: CameraPreviewPictureOptions = {
    width: 400,
    height: 400,
    quality: 85
};

............

takePicture() {
    console.log('take pinture');
    // take a picture
    this.cameraPreview.takePicture(this.pictureOpts).then((imageData) => {
      this.selectedImage = 'data:image/jpeg;base64,' + imageData;
      console.log('take picture ');
      this.location.back(); // go to previous page
    }, (err) => {
      console.log(err);
      this.selectedImage = 'assets/img/test.jpg';
    });
  }`

Once saved in the variable you can save it to the phone, for example using NativeStorage.
import { NativeStorage } from '@ionic-native/native-storage/ngx';

 constructor(private storage: NativeStorage) {}

saveImage() {
    this.storage.setItem('image', {property: this.selectedImage})
              .then(
                  () => {
                    console.log('Stored image!');
                  },
                  error => {
                    console.error('Error guardando la imagen', error);
                  }
          );
}

A: The ionic/native CameraPlugin .takePicture() method returns a promise. To get the value you need to change your code a bit.
  takePicture() {
    this.cameraPreview.takePicture(this.cameraPictureOpts).then(data => {
         let picture = `data:image/jpeg;base64,` + data;
    });

  }


text:
Q: How to I get a reference to the endpoint method handling current request (not the current method) I have a controller class
@RestController
public class Controller {

    @GetMapping("endpoint")
    public void endpoint() {
    }
}

and need the reference to the method handling the request i.e. Controller#endpoint().
I'm not looking for obtaining a reference to the current method but rather assume I'm in a filter or service for example and I need a reference to the endpoint method.
(The ultimate goal is to then assess wheter @SomeRelevantAnnotation is present or not deep inside my custom spring security stack but that's out of scope for this question.)
I think I could use the RequestContextHolder instance which embedds the request instance that I can then use in HandlerMapping#getHandler(request) to get a reference to the method.
Is there an easier way?


text:
Q: How do I communicate to the outside world from a Safari extension? How would I let a running process know that a context menu has been clicked in Safari?
I've read that this is not possible due to security, but that seems wrong because 1Password somehow pulls all of the information from the desktop app's database into the Safari extension. I wrote the extension to display the context menu and was trying to send an XMLRPC request to localhost, but couldn't get it to work.

A: I'm not certain of this, but I think 1Password does what it does by having a background process (1PasswordAgent) constantly polling for certain changes in the extension's local database and/or config files. For example, to initially get your passwords into the extension, the extension could set a certain flag in its localStorage db, which would get written (by Safari, not by the extension) to a file. The agent would then notice the flag in the file and copy your passwords from the main 1Password database into the extension's local database. Similarly, when the extension creates a new password entry, the agent would notice the change in the extension's database and mirror it to the 1Password database.
Perhaps you could do something similar?

A: Although I have no idea about the implementation of 1Password, LiveReload achieves the same by using WebSocket to connect to a localhost URL (handled by the application). If you do it from the global page, cross-domain limitations do not apply, so you are free to connect to any URL:
var ws = new WebSocket("ws://localhost:98765");
...

(Be careful with that localhost thing, though, Chrome on Linux wants 0.0.0.0 instead of 127.0.0.1 or localhost. At least it used to want it.)


text:
Q: Let $R$ be a ring. Find out if $R$ is a field and solve the equation $x^2-3x+1=0$ in $R$ given the following addition and multiplication tables.
Let $R$ be a ring. Find out if $R$ is a field and solve the equation $x^2-3x+1=0$ in $R$ given the following addition and multiplication tables.

If $R$ was a field then for every element $x \in R$ we need an $x^{-1}$ such that $xx^{-1}=b$ as $b$ is the identity w.r.t $(\cdot)$.
However there is no element $y$ for which $ay=b$ so $R$ cannot be a field.
To solve $x^2-3x+1=0$ I should check which element from $\{a,b,c,d\}$ makes this true?
For $a$ I have that $$aa-(a+a+a)+1= a-(a+a)+1=a-a+1=1$$ and for $b$ $$bb-(b+b+b)+1=b-(c+b)+1=b-d+1$$
for $c$ $$cc-(c+c+c)+1=a-(a+c)+1=a-c+1$$ lastly for $d$ $$dd-(d+d+d)+1=b-(c+d)+1=b-b+1=1.$$
The first and last equations seems to give me $1$, but how can I get rid of the $1$?

A: It is prudent to relabel the variables as $abcd\to0123$ so that $R\cong\mathbb Z_4$, which is indeed not a field. Then it is easy to check that $x^2-3x+1=x^2+x+1$ has no solutions in $\mathbb Z_4$, hence $R$.


text:
Q: How to change background of Android checkBox? I have android checkBox and the default background is transparent, I want it to be white so I use style:
<style name="BrandedCheckBox" parent="AppTheme">
    <item name="colorAccent">@color/cyan</item>
    <item name="colorControlNormal">@color/text_gray</item>
    <item name="colorControlActivated">@color/cyan</item>
</style>

and set checkBox theme:
<CheckBox
    android:id="@+id/check_payable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_gravity="center"
    android:theme="@style/BrandedCheckBox"/>

But the result is this:

 But I want it to to be like this:
Can any one help me on this?

A: Just use a selector drawable defining the exact look you want for each state (the drawables listed in the selector can have transparencies if you need it).
Then also ensure you set this in the xml of your checkbox:
android:background="@drawable/checkbox_background"
android:button="@null"

And to avoid some recent bugs of AppCompat Checkbox I recommend you to stick with the good old android.widget.CheckBox (you should use full path to ensure you will not use AppCompat one).
In a short future you will be able to migrate to AppCompatCheckBox from androidX. However at this moment (while I am writing this) it still have bugs with custom backgrounds when running in old api levels. I already reported one here: https://issuetracker.google.com/issues/120865686
I hope my answer is useful for you.

A: you can use android:button
   <CheckBox
       android:id="@+id/check_box"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:button="@drawable/checkbox_background" />

checkbox_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
    android:drawable="@drawable/checkbox_checked" />
<item android:state_checked="false"
    android:drawable="@drawable/checkbox_unchecked" />
</selector>

I'm Using these two images in drawable

A: white color code #FFFFFF in your color.xml

<style name="BrandedCheckBox" parent="AppTheme">
    <item name="colorAccent">@color/cyan</item>
    <item name="colorControlNormal">@color/text_gray</item>
    <item name="colorControlActivated">@color/white</item>
</style>

A: You can use code: android:background="#006C84"
<CheckBox
    android:id="@+id/cb"
    android:background="#006C84"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

In the activity you can use:
chkBox = (CheckBox)findViewById(R.id.cb);

chkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
    {
        // TODO Auto-generated method stub
        if (buttonView.isChecked())
        {
            // When Checked
            //cb.setBackgroundColor(Color.BLACK);
            chkBox.setBackgroundColor(Color.parseColor("#FF8D3F"));
        }
        else
        {
            // When Not Checked
            // Set Your Default Color.
            chkBox.setBackgroundColor(Color.parseColor("#006C84"));
        }
    }
});


text:
Q: How to display DualListBox component in readonly mode Specifying a readonly flag in a dualListBox component results in this error
Uncaught Assertion Failed!: "readonly" must either be a public property of lightningDualListbox or a global HTML attribute : false

<lightning:dualListbox aura:id="mySelector"
                       name="select things"
                       label="Select"
                       sourceLabel="Options"
                       selectedLabel="Selected"
                       options="{! v.availableItems }"
                       value="{! v.selectedItems }"
                       onchange="{! c.handleItemChange }"
                       readonly="true"/>

How do I show the dualListBox in readonly mode?

A: readonly is only available in Summer '18 (v43.0). Note that it doesn't seem to work anyways, so you'll probably want to use disabled for right now.


text:
Q: Extract cue-point or data from live video stream Does anybody know of a way I can extract timing data from any kind of live video stream?
I have tried with JWPlayer, but it is not capable of doing that.
My encoder is Streamcoders Mediasuite and I am happy to stream using whatever streamtype is necessary, in order for me to get cuepoint info (or any kind of timing info) from the stream.
Caveat - Flash and Silverlight are not an option, as the viewer-base is restricted by policy.
Thanks in advance.
Neil.


text:
Q: Running the same function in loop and saving the outputs The function slope() below generates the random b values and the values generated is used to calculate result in second function. In first run slope() will generate 15 values and calculate result for that 15 values and save in dictionary. I want to run this function for 100 times so for each set of 15 values it save the result like output for each run. I want to save the iteration number also.  Here I am trying to save in dictionary So that I can save my result later in pandas dataframe. How can run this function 100 times?? How can I save the result so that  later I can convert that result in pandas dataframe easily?
import numpy as np

# Randomly generated b values
def slope():
    b = np.random.uniform(1,2.5,15).round(2)
    return b

def psd(a):
    y = np.random.uniform(1,2.5,2).round(2)
    for i in y:
        result = y**(-a) + 1
    dictionary = {f'{a}':f'{list(result.round(5))}'}
    return dictionary

power = list(psd(x) for x in slope())

The output of above function is :
[{'2.08': '[1.40189, 1.38618]'},
 {'1.19': '[1.41358, 1.35635]'},
 {'2.0': '[1.51757, 1.61035]'},
 {'1.61': '[1.35884, 1.45538]'},
 {'1.07': '[1.38503, 1.80131]'},
 {'1.08': '[1.40485, 1.48885]'},
 {'2.37': '[1.11844, 1.66215]'},
 {'2.45': '[1.14653, 1.20226]'},
 {'1.34': '[1.3748, 1.34766]'},
 {'1.33': '[1.48239, 1.307]'},
 {'2.12': '[1.83302, 1.80152]'},
 {'1.19': '[1.46882, 1.6644]'},
 {'1.65': '[1.35917, 1.2442]'},
 {'1.61': '[1.27493, 1.24591]'},
 {'1.17': '[1.45778, 1.47483]'}]

A: Here is a sample code to call it 100 times.
import numpy as np

# Randomly generated b values
def slope():
    b = np.random.uniform(1,2.5,15).round(2)
    return b

def psd(a):
    y = np.random.uniform(1,2.5,2).round(2)
    for i in y:
        result = y**(-a) + 1
    dictionary = {f'{a}':f'{list(result.round(5))}'}
    return dictionary

# Save power in a dict with iter value as key.
data = {}
for i in range(100):
    power = list(psd(x) for x in slope())
    data.update({i: power})

# print(data)


text:
Q: Mysql fetch data with count and between date This is my table structure. I have to fetch the zip_code's range as per they created in database table in given between date.

For example in the given between dates are 4-aug-14 to 9-aug-14 i need follwing result
zip  number
90620   10
90621   5
How i write mysql query for this.

A: IS this you want the result DEMO
try
SELECT zip
    , COUNT(1) AS count
FROM table1
WHERE created BETWEEN '2014-08-04 00:00:00' AND '2014-08-08 23:59:59'
GROUP BY zip
ORDER BY count DESC

A: try :
Select zip, count(*) from table_name where created between 'from_date' and 'to_date' group by zip

A: Try this:
SELECT zip
    , COUNT(id) AS count
FROM [table]
WHERE created BETWEEN '2014-08-04 00:00:00' AND '2014-08-08 23:59:59'
GROUP BY zip
ORDER BY count DESC


text:
Q: $.get and setTimeout combination not working in IE I have to execute particular code every 1 minute, I have coded like this. Below code is working in all browsers except in IE.
Issue is: ../common/ajaxpage.aspx is hitting very first time,from the next time is not hitting but timedcount is calling for every 1 minute and variable "data" returns "not elapsed" every time even though ajaxpage.aspx is not called.
var gt_t;
$(document).ready(function () {
    gt_t = setTimeout('timedCount()', 60000);
    OnSaveBtnFix();
    OnStart();
    alert(gt_t);
});

    function timedCount() {
        alert("timed count started");
        $.get('../common/AjaxPage.aspx', { action: 'sessionexp', TypeID: 'ClientID' }, function (data) {
            alert(data);
            if (data == "Elapsed") {
                dispalySessionPopup();
                gt_t = setTimeout('timedCount()', 60000);
            }
            else if (data == "null") {
                hidePopup('popupMsg');
                document.location.href = "../Index.aspx?logout=y";
            }
            else {
                gt_t = setTimeout('timedCount()', 60000);
            }
        });
    }

A: IE is probably caching your request. You can convert your $.get call into a $.ajax call and use the cache option. jQuery will add a timestamp to the end of the request, forcing the browser to make a fresh request:
$.ajax({
    type: 'GET',
    url: '../common/AjaxPage.aspx',
    data: { action: 'sessionexp', TypeID: 'ClientID' },
    cache: false, // no caching
    success: function (data) { .... }
});

As a side note, it is considered a best-practice to use the version of setTimeout that takes a function reference, not a string. In other words:
gt_t = setTimeout('timedCount()', 60000);

could/should be rewritten:
gt_t = setTimeout(timedCount, 60000);


text:
Q: Let A⊆R be a set. Prove that A is bounded if and only if there is some M∈R such that M>0 and that |x|≤M for all x∈A. I proved the above problem as follows but received feedback that I'm not certain I understand.  Can someone help me determine where I went wrong in the proof?

Let A⊆R be a set.  Suppose M∈R where M>0 and |x|≤M for all x∈A.  Thus -M≤x≤M for all x∈A.  It is reasonable to conclude that A is bounded with an upper bound M and a lower bound -M.
Let A be bounded.  It follows that there exists a lower bound a∈R and an upper bound b∈R.  Thus |a|≤x≤|b| for all x∈A.
Let |a|≤|b|.  Then -|b|≤-|a| and -|b|≤x≤|b| for all x∈A.  It follows that -(|b|+1)0 and |x|≤M for all x∈A.
Let |b|<|a|.  Then -|a|≤x<|a| for all x∈A.  It follows that -(|a|+1)0 and |x|≤M for all x∈A.

I thought I did a pretty good job but my professor thought my two cases should be different. She also suggested that I missed a step, that I need to assume that |a|≤|b| means that x ≤-a =|a|≤|b| but I'm really not following that suggestion at all.

A:
Thus $|a|≤x≤|b|$ for all $x∈A$.

This is incorrect; you put absolute values where they don't belong. The definition of upper and lower bounds tells you that $a\le x\le b $ for all $x \in A$.

It follows that -(|b|+1)0

This looks like a broken formula.

Let $|a|≤|b|$

This is a misuse of "let". It is meant to signal the reader that some assignment has been made, like "let $c=4$". Here, $a$ and $b$ are already introduced, you can't apply "let" to them as if they were fresh variables. It's better to write:
"There are two cases. Case 1: $|a|\le |b|$. Case 2: $|a|>|b|$."
One   problem with the two final paragraphs is that you never said what $M$ is. If you want to convince the reader that $M$ exists, it helps to spell out what it is: $M=|b|$ in the first case, for example.

(You could shorten the proof with $M=\max(|a|,|b|)$, unifying the cases.)


text:
Q: NSCollectionView header display I have an NSCollectionView that has 3 sections which contains colors from a color palette. I want each section to have a header view with the name of the section. At first glance, it appears to work. On launch, it looks like this:

However, as soon as I resize the window, the header text ends up drawing outside the headers (and also inside it, somehow!):

In order to have headers in the collection view, I have a header view class named CollectionHeaderView. I register this class as a supplemental view:
    [_collection registerClass:[CollectionHeaderView class]
    forSupplementaryViewOfKind:@"UICollectionElementKindSectionHeader"
                withIdentifier:kSupplementalView];

In the collection view's delegate, I implement the method to return the view for the supplemental element:
- (NSView *)collectionView:(NSCollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSCollectionViewSupplementaryElementKind)kind
               atIndexPath:(NSIndexPath *)indexPath {
    NSView* result = [collectionView makeSupplementaryViewOfKind:kind
                                                  withIdentifier:kSupplementalView
                                                    forIndexPath:indexPath];

    if ([kind isEqualToString:@"UICollectionElementKindSectionHeader"]) {
        NSTextField* textView = ((CollectionHeaderView*)result).textField;
        switch (indexPath.section) {
            case 0:
                [textView setStringValue:@"Bright Colors"];
                break;

            case 1:
                [textView setStringValue:@"Pastel Colors"];
                break;

            case 2:
                [textView setStringValue:@"Designer Colors"];
                break;
        }

        return textView;
    }

    return nil;
}

Furthermore, if I resize the window, the header views do not move. The collection elements seem to flow around the headers, leaving things listed under the wrong section. And, as you can see in the second picture above, widening the window ends up leaving a gap between the right edge of the header and the right edge of the collection view.
The CollectionHeaderView class is very simple. It just creates a text field and draws the background and the text field:
@implementation CollectionHeaderView

- (instancetype)initWithFrame:(NSRect)frameRect {
    self = [super initWithFrame:frameRect];

    if (self != nil) {
        NSRect textFrame = frameRect;
        _textField = [[NSTextField alloc] initWithFrame:textFrame];
        _textField.editable = NO;
        _textField.bordered = NO;
        _textField.font = [NSFont fontWithName:@"Helvetica-Bold" size:14.0];
        _textField.backgroundColor = [NSColor colorWithSRGBRed:0.0 green:0.0 blue:0.0 alpha:0.0];
        [self addSubview:_textField];

        self.identifier = kSupplementalView;
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    // Drawing code here.
    NSBezierPath*   fillPath    = [NSBezierPath bezierPath];
    [fillPath appendBezierPathWithRect:dirtyRect];
    [[NSColor lightGrayColor] setFill];
    [fillPath fill];

    [_textField drawRect:dirtyRect];
}

@end

Have I implemented any of the above methods incorrectly? Is there any method I need to implement that I haven't?

A: The return value of collectionView:viewForSupplementaryElementOfKind:atIndexPath: is the supplementary view result.
- (NSView *)collectionView:(NSCollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSCollectionViewSupplementaryElementKind)kind
               atIndexPath:(NSIndexPath *)indexPath {
    NSView* result = [collectionView makeSupplementaryViewOfKind:kind
                                                  withIdentifier:kSupplementalView
                                                    forIndexPath:indexPath];

    if ([kind isEqual:NSCollectionElementKindSectionHeader]) {
        NSTextField* textView = ((CollectionHeaderView*)result).textField;
        switch (indexPath.section) {
            case 0:
                [textView setStringValue:@"Bright Colors"];
                break;

            case 1:
                [textView setStringValue:@"Pastel Colors"];
                break;

            case 2:
                [textView setStringValue:@"Designer Colors"];
                break;
        }

        return result;
    }

    return nil;
}


text:
Q: How to update ListView with BroadcastReceiver? I want update ListView from BroadcastReceiver in onReceiver event.
How to initialized ListView in this class then update to ListView:
public class CallBroadcast extends BroadcastReceiver {

    private static int pState = TelephonyManager.CALL_STATE_IDLE;

    @Override
    public void onReceive(final Context context, final Intent intent) {
        TelephonyManager telManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        telManager.listen(new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                callDAO = new CallDAO(context);
                if (configPreferenceManager.getAutoRecord()) {
                    if (state != pState) {
                        if (state == TelephonyManager.CALL_STATE_OFFHOOK && callInfoPreferenceManager.getCallState()) {
                            uri = Uri.withAppendedPath(
                                ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                Uri.encode(callInfoPreferenceManager.getPhoneNumber()));
                            projection = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                                    , ContactsContract.Contacts.PHOTO_ID
                            };

                            // START SERVICES TO RECORD CALL. AFTER IT, I WANT UPDATE MY LIST
                            sIntent = new Intent(context.getApplicationContext(),
                                    CallRecordService.class);
                            context.startService(sIntent);
                        } else if (state == TelephonyManager.CALL_STATE_RINGING && callInfoPreferenceManager.getCallState()) {
                            callInfoPreferenceManager.setPhoneNumber(incomingNumber);
                            callInfoPreferenceManager.setSending(String.valueOf(false));

                        } else if (state == TelephonyManager.CALL_STATE_IDLE && callInfoPreferenceManager.getCallState() == CALLING) {
                                callDAO.insert(callInfoPreferenceManager.getName(),
                                    callInfoPreferenceManager.getPhoneNumber(),
                                    callInfoPreferenceManager.getStartDate()
                                            + configPreferenceManager.getPathFormat());
                            callDAO.close();

                            // Record call start service
                            sIntent = new Intent(context.getApplicationContext(),
                                    CallRecordService.class);
                            context.stopService(sIntent);
                            callInfoPreferenceManager.setCallState(IDLE);

                        }
                        pState = state;
                    }
                }
            }
        }, PhoneStateListener.LISTEN_CALL_STATE);
    }//onReceive

}

In the code I posted is BroadcastReceiver class.
And I can't using getActivity() class or findViewById(a, b) when extends BroadcastReceiver.
How to fix this problem?

A: Start the activity that will populate the listview using Intents.
Intent intent = new Intent(context,Myactivity.class)
startactivity(intent);

To avoid multiple instances of same 'Myactivity', use appropriate flags in the Manifest file.
If you want to transfer data between your broadcastReceiver and 'Myactivity', either use intent.putExtra() or store the data into sharedPreferences


text:
Q: При присваивании значения слайдера выдает ошибку Пытаюсь присвоить slider'у значение, выдает ошибку
дело в том что все запускается, и работает но ошибка выдается, даже если это обычный Text
"NullReferenceException: Object reference not set to an instance of an object
fuel.FixedUpdate () (at Assets/_MyScripts/fuel.cs:20)"
Slider fuels;
float carfuel;

fuels.value = carfuel; // тут ошибка

В первый раз сталкиваюсь, что делать?
полный код скрипта:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class fuel : MonoBehaviour {

public float carfuel = 40;
public bool isCharging = false;
public Slider fuels;
public GameObject fuelEmpityMenu;

private void Start() {
    Time.timeScale = 1f;
}

void FixedUpdate () {

    if (!isCharging){
        carfuel -= Time.deltaTime;

    }
    if(isCharging){
        Debug.Log("car charging");
        carfuel = 40;
    }

    fuels.value = carfuel;

    if(carfuel <= 0){
        Time.timeScale = 0f;
        fuelEmpityMenu.SetActive(true);
    }

}

A: Ошибка NullReferenceException: Object reference not set to an instance of an object выпадает в том случае, если ссылка, по которой вы патаетесь обратиться не указывает на объект.
В вашем случае вы, видимо, забыли перетащитьSlider в соответствующее ему в инспекторе поле скрипта.


text:
Q: multiple checkbox error i am having multiple checkbox according to selected checkbox query have to perform search operation.
public class actionSupportController {
    public List<PCS_Household__c> lstQuery{get;set;}
    public List<PCS_Household__c> OnlstQuery{get;set;}
    public List<Characteristics__c> selctchr{get;set;}
    public Characteristics__c sct{get;set;}
    public string ID_c{get;set;}
    public string test{get;set;}
    public string Good_with_Cats_c{get;set;}
    public string Active_c{get;set;}
    public string HighNeed_c{get;set;}
    public string kid_friendly_c{get;set;}
    public string Non_shedder_c{get;set;}
    public string Predatory_Tendencies_c{get;set;}

    public List<Pets_Information__c> selctpet{get;set;}

    Public Boolean Good{get;set;}

    public void dochar(){
        string query='';
        system.debug('==Good_with_Cats_c=='+Good_with_Cats_c);
       query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c=\''+Good_with_Cats_c+'\' or Active__c=\''+Active_c+'\' or HighNeed__c=\''+HighNeed_c+'\' or kid_friendly__c=\''+kid_friendly_c+'\' or Non_shedder__c=\''+Non_shedder_c+'\' or Predatory_Tendencies__c=\''+Predatory_Tendencies_c+'\'';
       //query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c\''+Good_with_Cats_c+'\' or Active__c=\''+Active_c+'\'';
        system.debug('==query=='+query);
        selctchr=Database.query(query);
        system.debug('==selctchr=='+selctchr);
    }

    public PageReference incrementCounter() {
       string Query='';
        Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where ID=:test';
        system.debug('==Query=='+Query);
        OnlstQuery=Database.query(Query);
        system.debug('==OnlstQuery=='+OnlstQuery);
        return null;
    }

     public Void doSearch(){
        string Query='';
        Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where Household__c LIKE \'%'+ID_c+'%\'';
         system.debug('==ID_c=='+ID_c);
        system.debug('==Query=='+Query);
        lstQuery=Database.query(Query);
        system.debug('==lstQuery=='+lstQuery);
    }

    public void nullify(){
        lstQuery.clear();
    }

    public PageReference nextpage() {

        upsert OnlstQuery;

        return Page.cc;
    }

}

Visualforce:
<apex:page Controller="actionSupportController">
   <apex:form >
       <apex:pageBlock >
            Household Name: <apex:inputText value="{!ID_c}"/>
           </apex:pageBlock>
    <apex:pageBlock title="Characteristics Information">

        <apex:inputCheckbox value="{!Active_c}" />Active

        <apex:inputCheckbox value="{!Good_with_Cats_c}" />Good with Cats

        <apex:inputCheckbox value="{!HighNeed_c}" />HighNeed

        <apex:inputCheckbox value="{!kid_friendly_c}" />Kid Friendly

        <apex:inputCheckbox value="{!Non_shedder_c}" />Non Shedder

        <apex:inputCheckbox value="{!Predatory_Tendencies_c}" />Prediator Tendency

<apex:commandButton value="Search" action="{!dochar}" rerender="sblck"/>
    </apex:pageBlock>
    <apex:outputPanel id="sblck">
    <apex:pageBlock title="Search Results">
    <apex:pageBlockTable width="80%" value="{!selctchr}" var="eachpe">
        <apex:column width="80%" value="{!eachpe.Name}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Name__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Gender__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Height__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.pet__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Pet_Photo__c}"/>
        <apex:column width="80%" value="{!eachpe.Pet_ID__r.Status__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
    </apex:outputPanel>
       <apex:commandButton value="Request Adoption"/>
   </apex:form>
</apex:page>

A: The <apex:inputCheckBox> tag's value attribute takes object values referenced from controller. It should be of datatype Boolean.
But i can see all of your variables are of datatype String. Please change them to
public Boolean Good_with_Cats_c{get;set;}
public Boolean Active_c{get;set;}
public Boolean HighNeed_c{get;set;}
public Boolean kid_friendly_c{get;set;}
public Boolean Non_shedder_c{get;set;}
public Boolean Predatory_Tendencies_c{get;set;}

and in your constructor initialize them to false.
You need to change your query to use the boolean variables as bind variables by using : next to it.
query='SELECT Name,ID,Good_with_Cats__c,Pet_ID__r.Gender__c,Pet_ID__r.Height__c,Pet_ID__r.Name__c,Pet_ID__r.pet__c,Pet_ID__r.Pet_Photo__c,Pet_ID__r.Status__c FROM Characteristics__c where Good_with_Cats__c=:Good_with_Cats_c or Active__c=:Active_c or HighNeed__c=:HighNeed_c or kid_friendly__c=:kid_friendly_c or Non_shedder__c=:Non_shedder_c or Predatory_Tendencies__c=:Predatory_Tendencies_c';

Hope it helps.


text:
Q: Why is an XImage's data pointer null when capturing using XShmGetImage? I'm writing a program to rapidly capture images from one window, modify them, and output them to another window using Xlib with C++.  I have this working via XGetImage:
#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

const int TEST_SIZE = 512;

int main()
{
  // Open default display
  Display *display = XOpenDisplay(nullptr);
  int screen = DefaultScreen(display);
  Window rootWin = RootWindow(display, screen);
  GC graphicsContext = DefaultGC(display, screen);

  // Create new window and subscribe to events
  long blackPixel = BlackPixel(display, screen);
  long whitePixel = WhitePixel(display, screen);
  Window newWin = XCreateSimpleWindow(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, 1, blackPixel, whitePixel);
  XMapWindow(display, newWin);
  XSelectInput(display, newWin, ExposureMask | KeyPressMask);

  // Main event loop for new window
  XImage *image;
  XEvent event;
  bool exposed = false;
  bool killWindow = false;
  while (!killWindow)
  {
    // Handle pending events
    if (XPending(display) > 0)
    {
      XNextEvent(display, &event);
      if (event.type == Expose)
      {
        exposed = true;
      } else if (event.type == NoExpose)
      {
        exposed = false;
      } else if (event.type == KeyPress)
      {
        killWindow = true;
      }
    }

    // Capture the original image
    image = XGetImage(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, AllPlanes, ZPixmap);

    // Modify the image
    if (image->data != nullptr)
    {
      long pixel = 0;
      for (int x = 0; x < image->width; x++)
      {
        for (int y = 0; y < image->height; y++)
        {
          // Invert the color of each pixel
          pixel = XGetPixel(image, x, y);
          XPutPixel(image, x, y, ~pixel);
        }
      }
    }

    // Output the modified image
    if (exposed && killWindow == false)
    {
      XPutImage(display, newWin, graphicsContext, image, 0, 0, 0, 0, TEST_SIZE, TEST_SIZE);
    }
    XDestroyImage(image);
  }

  // Goodbye
  XCloseDisplay(display);
}

It generates output like this:  https://streamable.com/hovg9
I'm happy to have gotten this far, but from what I've read the performance isn't going to scale very well because it has to allocate space for a new image at every frame. In fact, without the call to XDestroyImage at the end of the loop this program fills up all 16GB of memory on my machine in a matter of seconds!
It seems the recommended approach here is to to set up a shared memory space where X can write the contents of each frame and my program can subsequently read and modify them without the need for any extra allocation.  Since the call to XShmGetImage blocks and waits for IPC I believe this means I won't have to worry about any concurrency issues in the shared space.
I've attempted to implement the XShmGetImage approach with the following code:
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <X11/Xlib.h>
#include <X11/extensions/XShm.h>
#include <X11/Xutil.h>

const int TEST_SIZE = 512;

int main()
{
  // Open default display
  Display *display = XOpenDisplay(nullptr);
  int screen = DefaultScreen(display);
  Window rootWin = RootWindow(display, screen);
  GC graphicsContext = DefaultGC(display, screen);

  // Create new window and subscribe to events
  long blackPixel = BlackPixel(display, screen);
  long whitePixel = WhitePixel(display, screen);
  Window newWin = XCreateSimpleWindow(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, 1, blackPixel, whitePixel);
  XMapWindow(display, newWin);
  XSelectInput(display, newWin, ExposureMask | KeyPressMask);

  // Allocate shared memory for image capturing
  Visual *visual = DefaultVisual(display, 0);
  XShmSegmentInfo shminfo;
  int depth = DefaultDepth(display, screen);
  XImage *image = XShmCreateImage(display, visual, depth, ZPixmap, nullptr, &shminfo, TEST_SIZE, TEST_SIZE);
  shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT | 0666);
  shmat(shminfo.shmid, nullptr, 0);
  shminfo.shmaddr = image->data;
  shminfo.readOnly = False;
  XShmAttach(display, &shminfo);

  // Main event loop for new window
  XEvent event;
  bool exposed = false;
  bool killWindow = false;
  while (!killWindow)
  {
    // Handle pending events
    if (XPending(display) > 0)
    {
      XNextEvent(display, &event);
      if (event.type == Expose)
      {
        exposed = true;
      } else if (event.type == NoExpose)
      {
        exposed = false;
      } else if (event.type == KeyPress)
      {
        killWindow = true;
      }
    }

    // Capture the original image
    XShmGetImage(display, rootWin, image, 0, 0, AllPlanes);

    // Modify the image
    if (image->data != nullptr) // NEVER TRUE.  DATA IS ALWAYS NULL!
    {
      long pixel = 0;
      for (int x = 0; x < image->width; x++)
      {
        for (int y = 0; y < image->height; y++)
        {
          // Invert the color of each pixel
          pixel = XGetPixel(image, x, y);
          XPutPixel(image, x, y, ~pixel);
        }
      }
    }

    // Output the modified image
    if (exposed && killWindow == false)
    {
      XShmPutImage(display, newWin, graphicsContext, image, 0, 0, 0, 0, 512, 512, false);
    }
  }

  // Goodbye
  XFree(image);
  XCloseDisplay(display);
}

Somehow, the images are still being captured and sent to the new window, but the data pointer within the XImage is always null.  I can't modify any of the contents and any usage of the XGetPixel and XPutPixel macros will fail.  Notice in this video that none of the colors are being inverted like before:  https://streamable.com/dckyv
This doesn't make any sense to me.  Clearly the data is still being transferred between the windows, but where is it in the XImage structure?  How can I access it via code?

A: It turns out I wasn't reading the signature for shmat correctly.  It doesn't have a void return type, it returns a void pointer.  This needs to be assigned directly to the XImage's data pointer in order for the data pointer to do anything.
In the call to XShmPutImage the shared memory location is referenced internally rather than the XImage's data pointer which is why this was still working even without utilizing the return value from shmat.
Here's the working code, along with a few other additions which I made for error handling and teardown:
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <X11/Xlib.h>
#include <X11/extensions/XShm.h>
#include <X11/Xutil.h>

const int TEST_SIZE = 512;

static int handleXError(Display *display, XErrorEvent *event)
{
  printf("XErrorEvent triggered!\n");
  printf("error_code: %d", event->error_code);
  printf("minor_code: %d", event->minor_code);
  printf("request_code: %d", event->request_code);
  printf("resourceid: %lu", event->resourceid);
  printf("serial: %d", event->error_code);
  printf("type: %d", event->type);
  return 0;
}

int main()
{
  // Open default display
  XSetErrorHandler(handleXError);
  Display *display = XOpenDisplay(nullptr);
  int screen = DefaultScreen(display);
  Window rootWin = RootWindow(display, screen);
  GC graphicsContext = DefaultGC(display, screen);

  // Create new window and subscribe to events
  long blackPixel = BlackPixel(display, screen);
  long whitePixel = WhitePixel(display, screen);
  Window newWin = XCreateSimpleWindow(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, 1, blackPixel, whitePixel);
  XMapWindow(display, newWin);
  XSelectInput(display, newWin, ExposureMask | KeyPressMask);

  // Allocate shared memory for image capturing
  XShmSegmentInfo shminfo;
  Visual *visual = DefaultVisual(display, screen);
  int depth = DefaultDepth(display, screen);
  XImage *image = XShmCreateImage(display, visual, depth, ZPixmap, nullptr, &shminfo, TEST_SIZE, TEST_SIZE);
  shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT | 0777);
  image->data = (char*)shmat(shminfo.shmid, 0, 0);
  shminfo.shmaddr = image->data;
  shminfo.readOnly = False;
  XShmAttach(display, &shminfo);
  XSync(display, false);
  shmctl(shminfo.shmid, IPC_RMID, 0);

  // Main event loop for new window
  XEvent event;
  bool exposed = false;
  bool killWindow = false;
  while (!killWindow)
  {
    // Handle pending events
    if (XPending(display) > 0)
    {
      XNextEvent(display, &event);
      if (event.type == Expose)
      {
        exposed = true;
      } else if (event.type == NoExpose)
      {
        exposed = false;
      } else if (event.type == KeyPress)
      {
        killWindow = true;
      }
    }

    // Capture the original image
    XShmGetImage(display, rootWin, image, 0, 0, AllPlanes);

    // Modify the image
    if(image->data != nullptr) // NEVER TRUE.  DATA IS ALWAYS NULL!
    {
      long pixel = 0;
      for (int x = 0; x < image->width; x++)
      {
        for (int y = 0; y < image->height; y++)
        {
          // Invert the color of each pixel
          pixel = XGetPixel(image, x, y);
          XPutPixel(image, x, y, ~pixel);
        }
      }
    }

    // Output the modified image
    if (exposed && killWindow == false)
    {
      XShmPutImage(display, newWin, graphicsContext, image, 0, 0, 0, 0, 512, 512, false);
    }
  }

  // Goodbye
  XShmDetach(display, &shminfo);
  XDestroyImage(image);
  shmdt(shminfo.shmaddr);
  XCloseDisplay(display);
}


text:
Q: 3d.io api at React project Does 3d.io support React components at future ? Now, I need to find dom element utilized "ref" from component to retrieve io3d objects.

  render () {
    // this.props.elements is the state from getAframeElements
    if (this.props.sceneId !== '') {
      this.props.elements.forEach( (item) => {
        this.refs.scene.appendChild(item)
      })
    }
    return (
      <a-entity ref="scene">
      </a-entity>
    )
}

Do you have any guides how to use 3d.io at React project ? Or I need to use document.querySelector after componentDidMount event at React.

A: A few things here:

*

*How to use react and 3d.io

Most 3dio-js methods return plain js objects and arrays that you can use with any javascript library.
Here's how you could use io3d.furniture.search in a react component: https://jsfiddle.net/wo2xpb9g/

*How to combine react and a-frame

There is the aframe-react project that will make combining a-frame and react easier https://github.com/ngokevin/aframe-react
As of newer versions of react it seems possible to combine a-frame and react directly like you've done, here's an example: https://codepen.io/cassiecodes/pen/akXWjo?editors=1010

*How to use io3d.scene.getAframeElements with react

getAframeElements is a convenience method which converts sceneStructure into real a-frame DOM nodes. In react projects, real DOM nodes are generated by react itself.
There are two possibilities,

*

*Instead of getAframeElements, convert sceneStructure from io3d.scene.getStructure into react virtual DOM yourself. Hopefully a community library will be published for this soon.

*Keep the a-frame DOM separate from react. This is the approach sometimes used to combine react with libraries such as D3, which directly manipulate the DOM... that approach is discussed with examples here: https://medium.com/@Elijah_Meeks/interactive-applications-with-react-d3-f76f7b3ebc71


text:
Q: Getting AJAX content loaded when scrolled with Selenium Wedriver I am using Selenium WebDriver to get the content of a site. (Note: the site has no API. Wish it did.) The site uses AJAX to dynamically load content when the user scrolls. To get that content, I've been using Javascript  to scroll down and then trying to access the content using findElements().
To be clear about the setup, the page contains several nested elements, one of which is a div with the "GridItems" class (no name or id). This div contains many child elements with the "Item" class (again, no name or id, just the class). I want to get every element with class "Item" in the div. About 25 items are accessible when the page first loads (not necessarily visible in the current window, but available in the DOM), and scrolling down loads more.
My main issues are as follows: first, I want to stop scrolling when I get to the bottom. However, I can't figure out what stopping condition to use. How can I determine when I've reached the bottom of the page? Window.scrollheight won't work, because that will give the height of the existing window, not what it will be after it's finished adding more content. I've thought of testing if an element at the bottom of the page is visible/clickable, but if it's not, it may be just because it hasn't loaded yet, not because it hasn't been reached. Even using a Wait may not work because if it times out, I don't know if it's because it hasn't reached the bottom, or just because it's taking a long time to load.
The second problem is that when I scroll down, it loads some more elements, but eventually, scrolling down loads more from the bottom and drops the top ones of the DOM. This means that I can't just scroll down to the bottom and then use findElements() to get all Items, because many of the first ones will be gone. I know how many items to expect, so currently, I'm doing the following:
    int numitems = 135;
    List<WebElement> newitems;
    List<WebElement> allitems = new ArrayList<WebElement>(50);

    do {
        //scroll down the full length of the visible window three times
        for(int i=0; i < 3; i++)
        {
            //scroll down
            js.executeScript("window.scrollTo(0, document.body.offsetHeight)");

        }

        //check how many items are now available
  //if it runs too fast, it may get to the next line before it finishes scrolling;
  //make it wait until the desired div is visible
    WebElement cont =  (new WebDriverWait(driver, 100))
.until(ExpectedConditions.presenceOfElementLocated(By.className("GridItems")));

       //get all Items in the div
        newitems = cont.findElements(By.className("Item"));

    //add all the items extracted after scrolling 3 times to the list
        allitems.addAll(newitems);

    //repeat until there are more items in the general list than are expected
    //to be found. This is hacky; I wish there was a better stopping condition
    }while(numitems > allitems.size());

That is, I scroll the page three times, get all elements available after the scrolling, and add them to a list. I repeat this until there are more elements in the list than I was expecting to be found.
The problem with this is that since scrolling adds a different number of items to the DOM each time, there is often overlap between what is added to the allitems list at each iteration. The Elements are just objects with unique ids an contain no information about the actual HTML, so I can't check if they're duplicated. I may also lose some items if the scrolling doesn't overlap perfectly. Also, since I've scrolled down, the earlier items in the list that have fallen off the top lose their connection to the DOM and then I get a StaleElementReferenceException when I try to process them.
I can process each item as I get it, I suppose, though it will make the code clunky. This will also allow me to check its actual content and find the duplicates. I'm not sure that this will ensure that I don't skip any.
Does anyone have any suggestions for how best to do this? Am I missing something very important/obvous here? The other questions here on SO about AJAX content loading address somewhat different problems. (e.g. I generally don't have an issue with content not loading and having to wait for it, though I did include a Wait.) It seems that there should be a better way of doing this - is there?
Sorry for the long-winded post; I hope it was clear.
Thank you so much,
bsg
Edit:
I realize that the accepted answer only answers part of the question. For the rest of it, I found that scrolling down one screen at a time and getting all new elements each time meant that I didn't lose any. After each scroll, I got all elements loaded and did some processing to save the content of each one. This introduces a lot of redundancy, which I used a HashSet to eliminate. I stop scrolling when I reach the bottom, as determined by the code in the accepted answer. Hope this helps.

A: How can I determine when I've reached the bottom of the page?
JS doesn't work well for that, so I used jQuery to determine that. Once I reach the bottom this evaluates to true:
$(document).height() == ($(window).height() + $(window).scrollTop();
Is there anything that distinguishes their uniqueness? Your flickr example contains images, the url to the image could be use for this, by using WebElement.getAttribute("src") to create a unique identifier.


text:
Q: Is there a way to render color using the interweave library in React? I am using the interweave library in React to render a string of HTML code, but it does not render color (the style tag is not supported since it is technically CSS, not HTML). Does anyone know a way to get color to render through the library, maybe with an alternative tag? The "font" tag is also unsupported.
Background: I am getting a string of HTML text from the server-side of an application and trying to render the HTML of the resulting string variable on the front-end).
Link to the Interweave library: https://github.com/milesj/interweave
import React from "react"
import { Markup } from 'interweave';

export default class Formating extends React.Component{
    render(){
        return <Markup content={this.props.string}/>
    }
}

A: I would use the transform prop provided by interweave, a quick example to highlight text within  tags below:
import React from "react"
import Interweave, { Node } from 'interweave';

export default function MyComponent(props) {

    const transformText = (node: HTMLElement, children: Node[]):React.ReactNode => {
        if (node.tagName.toLowerCase() === "b") {
        return {children};
    }
  };

    return(
        return <Interweave content={props.string} transform={transformText}/>
    )
}

See https://interweave.dev/docs/parser#replacing-elements


text:
Q: What is the options parameter of spark_write_csv dplyr function? I was looking for a way to make spark_write_csv to upload only a single file to S3 because I want to save the regression result on S3. I was wondering if options has some parameter which defines number of partitions. I could not find it anywhere in the documentation. Or is there any other efficient way to upload resultant table to S3?
Any help is appreciated!

A: options argument is equivalent options call on the DataFrameWriter (you can check DataFrameWriter.csv documentation for a full list of options specific to CSV source) and it cannot be used to control the number of the output partitions.
While in general it is not recommended, you can use Spark API to coalesce data and convert it back to sparklyr tbl:
df %>%
  spark_dataframe() %>%
  invoke("coalesce", 1L) %>%
  invoke("createOrReplaceTempView", "_coalesced")

tbl(sc, "_coalesced") %>% spark_write_csv(...)

or, in the recent versions, sparklyr::sdf_coalesce
df %>% sparklyr::sdf_coalesce()


text:
Q: How to implement 'use case control' object in (iOS) MVC? In an MVC architecture pattern (for e.g., in iOS) there is a controller per view. In UML there is a concept of having Control object per use case to encapsulate an use case, which may span more than one view. Sometimes a same view can support multiple use case, in which case it would be nice to have multiple 'use case control' objects.
Should i create a separate 'control' object apart from iOS 'Controller' to encapsulate the use case?
Any idea on how to implement 'use case control' object in iOS MVC? I am really interested in the concept of having control object for an use case, rather than per (use case fragment) view.