text:
Q: limit scrolling and zooming Google Maps Android API v2 I've added GroundOverlay to map and want to limit scrolling and zooming within this area.
How to limit scrolling within some bounds on android google maps?
Is it possible to get instantly motion points from MapFragment?
Please, help me.

A: Too bad that google doesn't let us intercept and block the user, i found that MaciejGórski's answer is the one that suits best to my needs.
I wanted to share my solution (Based on his answer) with you.
First i defined the bounds and max/min zoom:
private final LatLngBounds BOUNDS = new LatLngBounds(new LatLng(41.8138,12.3891), new LatLng(41.9667, 12.5938));
private final int MAX_ZOOM = 18;
private final int MIN_ZOOM = 14;

Then i created this little function to test if current camera bounds are outside of max bounds and return the difference in latitude and longitude.
/**
 * Returns the correction for Lat and Lng if camera is trying to get outside of visible map
 * @param cameraBounds Current camera bounds
 * @return Latitude and Longitude corrections to get back into bounds.
 */
private LatLng getLatLngCorrection(LatLngBounds cameraBounds) {
    double latitude=0, longitude=0;
    if(cameraBounds.southwest.latitude < BOUNDS.southwest.latitude) {
        latitude = BOUNDS.southwest.latitude - cameraBounds.southwest.latitude;
    }
    if(cameraBounds.southwest.longitude < BOUNDS.southwest.longitude) {
        longitude = BOUNDS.southwest.longitude - cameraBounds.southwest.longitude;
    }
    if(cameraBounds.northeast.latitude > BOUNDS.northeast.latitude) {
        latitude = BOUNDS.northeast.latitude - cameraBounds.northeast.latitude;
    }
    if(cameraBounds.northeast.longitude > BOUNDS.northeast.longitude) {
        longitude = BOUNDS.northeast.longitude - cameraBounds.northeast.longitude;
    }
    return new LatLng(latitude, longitude);
}

Then the Handler that controls the overscroll (And overzoom) limiting it every 100ms.
/**
 * Bounds the user to the overlay.
 */
private class OverscrollHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        CameraPosition position = mMap.getCameraPosition();
        VisibleRegion region = mMap.getProjection().getVisibleRegion();
        float zoom = 0;
        if(position.zoom < MIN_ZOOM) zoom = MIN_ZOOM;
        if(position.zoom > MAX_ZOOM) zoom = MAX_ZOOM;
        LatLng correction = getLatLngCorrection(region.latLngBounds);
        if(zoom != 0 || correction.latitude != 0 || correction.longitude != 0) {
            zoom = (zoom==0)?position.zoom:zoom;
            double lat = position.target.latitude + correction.latitude;
            double lon = position.target.longitude + correction.longitude;
            CameraPosition newPosition = new CameraPosition(new LatLng(lat,lon), zoom, position.tilt, position.bearing);
            CameraUpdate update = CameraUpdateFactory.newCameraPosition(newPosition);
            mMap.moveCamera(update);
        }
        /* Recursively call handler every 100ms */
        sendEmptyMessageDelayed(0,100);
    }
}

This handler must be defined as a field inside current class (I did this in a class that extends SupportMapFragment)
private OverscrollHandler mOverscrollHandler = new OverscrollHandler();

And lastly it must be called for the first time, i did it at the end of onActivityCreated to be sure that map exists.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mContext = getActivity();
    mMap = getMap();
    mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
    mMap.addTileOverlay(new TileOverlayOptions().tileProvider(new VexLocalTileProvider(getResources().getAssets())));
    CameraUpdate upd = CameraUpdateFactory.newLatLngZoom(new LatLng(41.87145, 12.52849), 14);
    mMap.moveCamera(upd);
    mOverscrollHandler.sendEmptyMessageDelayed(0,100);
}

Hope you will find it useful!

A: Instead of using new and shiny push technology which is onCameraChange, you may try to use old poll technology: map.getCameraPosition() or map.getProjection().getVisibleRegion(). You can then check if returned value is what you like and if not, map.moveCamera(...).
Basically you need a Handler, which will get the value of camera position in handleMessage and you send messages to this handler every 10ms or so. Inside handleMessage do sendEmptyMessageDelayed.
You can also use Runnable instead of Message (but that's a matter of taste).

A: limit zoom you can user this code
private GoogleMap mMap;
// Set a preference for minimum and maximum zoom.
mMap.setMinZoomPreference(6.0f);
mMap.setMaxZoomPreference(14.0f);

A: In maps API v2 there's a Min/MaxZoomLevel on the GoogleMap class, but I don't know if you can set it in any way.
Another approach would be to add a
GoogleMap.OnCameraChangeListener

to your map and by implementing
public void onCameraChange(CameraPosition cameraPosition);

To restrict the visible area, using GoogleMap.moveCamera(cameraPosition)
That is if you wish the user to be able to scroll or zoom "some".
You can also totally deactivate the scroll/zoom events via GoogleMapOptions

A: Constraining the camera has (finally!) been added as a feature as part of the release of Google Play Services 9.4 -- you can call setLatLngBoundsForCameraTarget(LatLngBounds bounds) to set the allowed panning area.
// Create a LatLngBounds that includes the city of Adelaide in Australia.
final LatLngBounds ADELAIDE = new LatLngBounds(
    new LatLng(-35.0, 138.58), new LatLng(-34.9, 138.61));

// Constrain the camera target to the Adelaide bounds.
mMap.setLatLngBoundsForCameraTarget(ADELAIDE);

You can find a thorough explanation in the documentation: Restricting the user's panning to a given area and a sample activity in GitHub.

A: May be it is too late, but here is my solution:

*

*Disabled built-in GoogleMap's gestures.

*Added custom gestures (for scrolling, fling and scaling).

*Checking for allowed area when processing events.

*Set bounds/zoom manually with standard Map's functions.
And here is my example:
[UPDATED]
There was a problem - when touch events were recieved before map was initialized.
check null values in onInterceptTouchEvent
Also I have discovered that my solution is slightly slowly than build-in function.
import android.content.Context;
import android.graphics.Point;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.VisibleRegion;

public class RestrictedMapView extends MapView {

    public static float MAX_ZOOM = 20;
    public static float MIN_ZOOM = 5;
    public static float MIN_ZOOM_FOR_FLING = 7;

    public static double MAX_LONGITUDE = 183.61;
    public static double MIN_LONGITUDE = 159.31;
    public static double MAX_LATITUDE = -32.98;
    public static double MIN_LATITUDE = -53.82;

    public static double DEF_LATITUDE = -41.78;
    public static double DEF_LONGITUDE = 173.02;
    public static float DEF_ZOOM = 7;

    private Handler mHandler = new Handler();
    private Context mContext;
    private VisibleRegion mLastCorrectRegion = null;
    private boolean mIsInAnimation = false;

    public RestrictedMapView(Context c, AttributeSet a, int o) {
        super(c, a, o);
        init(c);
    }
    public RestrictedMapView(Context c, AttributeSet a) {
        super(c, a);
        init(c);
    }
    public RestrictedMapView(Context c) {
        super(c);
        init(c);
    }

    public RestrictedMapView(Context c, GoogleMapOptions o) {
        super(c, o);
        init(c);
    }

    private GestureDetector mGestureDetector = null;
    private GestureDetector.SimpleOnGestureListener mGestudeListener =
            new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (mIsInAnimation) return false;
            GoogleMap map = getMap();
            LatLng target = map.getCameraPosition().target;
            Point screenPoint = map.getProjection().toScreenLocation(target);
            Point newPoint = new Point(screenPoint.x + (int)distanceX, screenPoint.y + (int)distanceY);
            LatLng mapNewTarget = map.getProjection().fromScreenLocation(newPoint);
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
                    mapNewTarget,map.getCameraPosition().zoom);
            tryUpdateCamera(update, 0);
            return true;
        }

        @Override
        public boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (mIsInAnimation) return false;
            GoogleMap map = getMap();
            double zoom = map.getCameraPosition().zoom;
            if (zoom < MIN_ZOOM_FOR_FLING)
                return false;
            int velocity = (int) Math.sqrt(velocityX * velocityX + velocityY * velocityY);
            if (velocity < 500) return false;
            double k1 = 0.002d; /*exipemental*/
            double k2 = 0.002d;/*exipemental*/

            LatLng target = map.getCameraPosition().target;
            Point screenPoint = map.getProjection().toScreenLocation(target);
            Point newPoint = new Point(screenPoint.x - (int)(velocityX * k1 * zoom * zoom/*exipemental*/),
                    screenPoint.y - (int)(velocityY * k1 * zoom * zoom/*exipemental*/));
            LatLng mapNewTarget = map.getProjection().fromScreenLocation(newPoint);
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
                    mapNewTarget,map.getCameraPosition().zoom);
            tryUpdateCamera(update, (int)(velocity * k2 * zoom * zoom) /*exipemental*/);
            return true;
        }
    };
    private ScaleGestureDetector mScaleGestureDetector = null;
    private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleGestudeListener =
            new ScaleGestureDetector.SimpleOnScaleGestureListener() {

        @Override
        public boolean onScale (ScaleGestureDetector detector) {
            if (mIsInAnimation) return false;

            GoogleMap map = getMap();
            double zoom = map.getCameraPosition().zoom;

            double k = 1d / detector.getScaleFactor();
            int x = (int) detector.getFocusX();
            int y = (int) detector.getFocusY();
            LatLng mapFocus = map.getProjection().
                    fromScreenLocation(new Point(x, y));
            LatLng target = map.getCameraPosition().target;

            zoom = zoom + Math.log(detector.getScaleFactor()) / Math.log(2d);
            if (zoom < MIN_ZOOM)
                if (zoom == MIN_ZOOM) return false;
                else zoom = MIN_ZOOM;
            if (zoom > MAX_ZOOM)
                if (zoom == MAX_ZOOM) return false;
                else zoom = MAX_ZOOM;

            double dx = norm(mapFocus.longitude) - norm(target.longitude);
            double dy = mapFocus.latitude - target.latitude;
            double dk = 1d - 1d / k;
            LatLng newTarget = new LatLng(target.latitude - dy * dk,
                    norm(target.longitude) - dx * dk);

            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(newTarget, (float) zoom);
            tryUpdateCamera(update, 0);
            return true;
        }
    };

    private void tryUpdateCamera(CameraUpdate update, int animateTime) {
        GoogleMap map = getMap();
        final VisibleRegion reg = map.getProjection().getVisibleRegion();
        if (animateTime <= 0) {
            map.moveCamera(update);
            checkCurrentRegion(reg);
        } else {
            mIsInAnimation = true;
            map.animateCamera(update, animateTime, new GoogleMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    mIsInAnimation = false;
                    checkCurrentRegion(reg);
                }
                @Override
                public void onCancel() {
                    mIsInAnimation = false;
                    checkCurrentRegion(reg);
                }
            });
        }
    }

    private void checkCurrentRegion(VisibleRegion oldReg) {
        GoogleMap map = getMap();
        VisibleRegion regNew = map.getProjection().getVisibleRegion();
        if (checkBounds(regNew)) {
            mLastCorrectRegion = regNew;
        } else {
            if (mLastCorrectRegion != null)
                oldReg = mLastCorrectRegion;
            mIsInAnimation = true;
            map.animateCamera(CameraUpdateFactory.newLatLngBounds(
                    oldReg.latLngBounds, 0),
                    200, new GoogleMap.CancelableCallback() {
                        @Override
                        public void onFinish() {
                            mIsInAnimation = false;
                        }
                        @Override
                        public void onCancel() {
                            mIsInAnimation = false;
                        }
                    });

        }
    }

    /**
     *
     *
     * @param lonVal
     * @return
     */
    private double norm(double lonVal) {
        while (lonVal > 360d) lonVal -= 360d;
        while (lonVal < -360d) lonVal += 360d;
        if (lonVal < 0) lonVal = 360d + lonVal;
        return lonVal;
    }

    private double denorm(double lonVal) {
        if (lonVal > 180d) lonVal = -360d + lonVal;
        return lonVal;
    }

    private boolean checkBounds(VisibleRegion reg) {
        double left = Math.min(
                Math.min(norm(reg.farLeft.longitude), norm(reg.nearLeft.longitude)),
                Math.min(norm(reg.farRight.longitude), norm(reg.nearRight.longitude)));
        double right = Math.max(
                Math.max(norm(reg.farLeft.longitude), norm(reg.nearLeft.longitude)),
                Math.max(norm(reg.farRight.longitude), norm(reg.nearRight.longitude)));
        double top = Math.max(
                Math.max(reg.farLeft.latitude, reg.nearLeft.latitude),
                Math.max(reg.farRight.latitude, reg.nearRight.latitude));
        double bottom = Math.min(
                Math.min(reg.farLeft.latitude, reg.nearLeft.latitude),
                Math.min(reg.farRight.latitude, reg.nearRight.latitude));

        boolean limitBounds = left < MIN_LONGITUDE || right > MAX_LONGITUDE ||
                bottom < MIN_LATITUDE || top > MAX_LATITUDE;
        return !limitBounds;
    }

    private void init(Context c) {
        try {
             MapsInitializer.initialize(c);
         } catch (GooglePlayServicesNotAvailableException e) {
             e.printStackTrace();
         }
        mContext = c;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                GoogleMap map = getMap();
                if (map != null) {
                    getMap().getUiSettings().setZoomControlsEnabled(false);
                    map.getUiSettings().setAllGesturesEnabled(false);
                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(DEF_LATITUDE, DEF_LONGITUDE), DEF_ZOOM));
                    mLastCorrectRegion = map.getProjection().getVisibleRegion();
                    mGestureDetector = new GestureDetector(mContext, mGestudeListener);
                    mScaleGestureDetector = new ScaleGestureDetector(mContext, mScaleGestudeListener);
                } else mHandler.post(this);
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (mGestureDetector != null) mGestureDetector.onTouchEvent(event);
        if (mScaleGestureDetector != null) mScaleGestureDetector.onTouchEvent(event);
        return super.onInterceptTouchEvent(event);
    }
}

Definition within my xml-layout of fragment:
<com.package....RestrictedMapView
    android:id="@+id/mapview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

In xml file it is possible to define custom zoom/location buttons and set click listeners for manual manipulating camera (in this case you have to check MAX_ZOOM and MIN_ZOOM, and check if the current location is within the allowed bounds).


text:
Q: How does self.class.where retrieve information from the database? One object orientated way to retrieve information from the database is to use those three methods, chained together.
You can create an instance method like this:
def "find_friend"
    self.class.where({friend_id: user_id})
end

and then call it like this:
# @user_friendship == <UserFriendship id: 1, friend_id: 2, user_id: 1>

@user_friendship.find_friend

and if we have a user_friendships table like this:
| id | friend_id | user_id |

| 1  | 1         | 3       |
| 2  | 2         | 1       |
| 3  | 3         | 2       |

Then the find_friend method would return the second record (The one with an id of 2)
@user_friendship.find_friend #=> <UserFriendship id: 2, friend_id: 2, user_id: 1>

Now, firstly is my understanding correct?
Secondly, how does this actually work? self.class.inspect simply returns what appears to be a hash of the model table's schema:
self.class.inspect #=> `UserFriendship(id: integer, friend_id: integer, user_id: integer)`

So how is it possible to run a query on this simple hash?
self.class.where({friend_id: user_id})

A: Where is a class method so it can be called like so.
UserFriendship.where({friend_id: user_id})

Every Ruby object knows it's own class type so self.class.where({friend_id: user_id}) is the same thing.  self.class resolves to UserFriendship, you can then call the where method passing in a hash of key value pairs to pull back the record needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: find main class in java Why java can't find my main?
this is my first java code
package MyPacage;

public class MyClass {

  public static void main(string[] args) {
    System.out.println("Hello world!");
}
}

A: public class Main {
public static void main(String[] args) {
    System.out.println("Hello world!");
}


text:
Q: c# : DLLImport for a particular dll not working, although an example app shows it working, How can i resolve this? I am trying to import a dll using relative paths
private const string LzoDll32Bit = @"lib32\lzo_32.dll";

    #region Dll-Imports

    [DllImport(LzoDll32Bit, EntryPoint = "lzo_version_string")]
    private static extern IntPtr lzo_version_string32();
    [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_1_compress", CallingConvention = CallingConvention.Cdecl)]
    private static extern int lzo1x_1_compress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
    [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_decompress", CallingConvention = CallingConvention.Cdecl)]
    private static extern int lzo1x_decompress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
    [DllImport(LzoDll32Bit, EntryPoint = "__lzo_init_v2", CallingConvention = CallingConvention.Cdecl)]
    private static extern int __lzo_init_v2_32(uint v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9);

    #endregion

{"Unable to load DLL 'lib32\lzo_32.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"}

Now here is the weird thing,
http://wallaceturner.com/lzo-for-c, the link for the site where i downloaded a sample project to see how to work with the lzo compressor in c#.net.
And when i run the project it successfully works. I see no other dependencies apart from what i have in my project.
I am using .Net4.5.2 in both of them.
Here is my full source code for that class
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace TradeAlgo
{
    public class LZOCompressor
    {
        private static TraceSwitch _traceSwitch = new TraceSwitch("Simplicit.Net.Lzo", "Switch for tracing of the LZOCompressor-Class");
        private const string LzoDll32Bit = @"lib32\lzo_32.dll";

        #region Dll-Imports

        [DllImport(LzoDll32Bit, EntryPoint = "lzo_version_string")]
        private static extern IntPtr lzo_version_string32();
        [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_1_compress", CallingConvention = CallingConvention.Cdecl)]
        private static extern int lzo1x_1_compress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
        [DllImport(LzoDll32Bit, EntryPoint = "lzo1x_decompress", CallingConvention = CallingConvention.Cdecl)]
        private static extern int lzo1x_decompress32(byte[] src, int src_len, byte[] dst, ref int dst_len, byte[] wrkmem);
        [DllImport(LzoDll32Bit, EntryPoint = "__lzo_init_v2", CallingConvention = CallingConvention.Cdecl)]
        private static extern int __lzo_init_v2_32(uint v, int s1, int s2, int s3, int s4, int s5, int s6, int s7, int s8, int s9);

        #endregion

        private byte[] _workMemory = new byte[16384L * 4];

        public LZOCompressor()
        {
            int init = 0;
            init = __lzo_init_v2_32(1, -1, -1, -1, -1, -1, -1, -1, -1, -1);

            if (init != 0)
            {
                throw new Exception("Initialization of LZO-Compressor failed !");
            }
        }

        public byte[] Compress(byte[] src)
        {
            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: trying to compress {0}", src.Length));
            }
            byte[] dst = new byte[src.Length + src.Length / 64 + 16 + 3 + 4];
            int outlen = 0;
            lzo1x_1_compress32(src, src.Length, dst, ref outlen, _workMemory);

            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: compressed {0} to {1} bytes", src.Length, outlen));
            }
            byte[] ret = new byte[outlen + 4];
            Array.Copy(dst, 0, ret, 0, outlen);
            byte[] outlenarr = BitConverter.GetBytes(src.Length);
            Array.Copy(outlenarr, 0, ret, outlen, 4);
            return ret;
        }

        public byte[] Decompress(byte[] src)
        {
            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: trying to decompress {0}", src.Length));
            }
            int origlen = BitConverter.ToInt32(src, src.Length - 4);
            byte[] dst = new byte[origlen];
            int outlen = origlen;
            lzo1x_decompress32(src, src.Length - 4, dst, ref outlen, _workMemory);

            if (_traceSwitch.TraceVerbose)
            {
                Trace.WriteLine(String.Format("LZOCompressor: decompressed {0} to {1} bytes", src.Length, origlen));
            }
            return dst;
        }
    }
}

Please let me know if i am missing any details, would gladly provide anything required. Thanks.

A: I see the dll's are include in the project, make sure you set the dll's Properties for 'Copy To Output Directory' to 'Copy if newer'. Possibly they are not creating the folders with the dll's in them in your 'Release' folder.


text:
Q: Javascript objects understand a variable as string instead of a variable I have two questions about javascript and objects. The first one is:
I have this part of code:
  const handleAnotherStep = () => {
    let procedures =
      {key:
        {
          stepType: {
            stepCode: {
              language: stepText,
              timeout,
              nextInstruction,
            }
          }
        }
      }
    setProcedures(procedures)
    console.log(procedures)
  }

The key, stepType, stepCode, language, stepText, timeout and nextInstruction are in a useState(). The problem is: the console.log of this is:
[![enter image description here][1]][1]
But it should be like this :
[![enter image description here][2]][2]
You see? Instead of s'tepType', what should be written was the content of the stepType variable. Instead of the 'Key' the content of the key should be there. You get my point? Please, help me, I'm struggling in this and I'm newbie with JS. The nextInstruction and timeout are working just fine. I thin the javascript thinks the key, stepType, stepCode and language are a string, instead of a variable.

A: Use [var] to get the value of a variable as the key and for the value, you can give the variable itself.
  const handleAnotherStep = () => {
    let procedures =
      {[key]:
        {
          [stepType]: {
            [stepCode]: {
              [language]: stepText,
              timeout,
              nextInstruction,
            }
          }
        }
      }
    setProcedures(procedures)
    console.log(procedures)
  }

And for your second question to add a method to handle adding of steps you need not check because you just want to add an object so I think you can simply give,
  const handleAnotherStep = () => {
    let newProcedures =
      {[key]:
        {
          [stepType]: {
            [stepCode]: {
              [language]: stepText,
              timeout,
              nextInstruction,
            }
          }
        }
      }
    setProcedures({...prevProcedures, ...newProcedures})
    console.log(procedures)
  }

Note: Also immediately logging the procedure after setting the state will not give the correct value.


text:
Q: ERROR getting 'android:label' attribute: attribute is not a string value I have this error "ERROR getting 'android:label' attribute: attribute is not a string value" when trying to publish my application to android market.
Some time ago this app was already published successfully on market, but when I apply minor changes in AndroidManifest.xml (changing versionCode and versionName) I get this error constantly.
I looked to all similar topics here, such as:
Android Market Publishing Issues
"ERROR getting 'android:icon' attribute: attribute is not a string value" when trying to upload to the Android Market
The file is invalid: ERROR getting 'android:name' attribute: attribute is not a string value
but none of these solution helped me. Do you know any other reason of such an error?
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.samsung.att.deskhome" android:versionCode="12" android:versionName="2.3">
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<application android:icon="@drawable/mainmenu_icon_homemount" android:label="@string/app_name">
<activity android:name=".CradleMain" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" android:launchMode="singleTask" >
<meta-data android:name="android.dock_home" android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
<activity android:name=".CradleHomeSettings" android:label="@string/cradle_home_settings" android:launchMode="singleTask" android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
<activity android:name=".CradleWeatherSettings" android:label="@string/cradle_weather_settings" android:launchMode="singleTask" android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
<activity android:name=".CradleWallpaperChooser" android:label="@string/pick_wallpaper" android:screenOrientation="nosensor" android:finishOnCloseSystemDialogs="true" android:configChanges="locale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DESK_DOCK" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<uses-sdk android:maxSdkVersion="10" />
</manifest>

A: Whenever you get an error from the play store while uploading make sure to execute that same command locally to get proper output. The output retrieved from the online console is misleading.
An example from my own code, this is what I got on the online console:
Failed to run aapt dump badging:
W/ResourceType( 4560): Failure getting entry for 0x7f0601c6 (t=5 e=454) in package 0 (error -75)
ERROR getting 'android:label' attribute: attribute is not a string value

And a local run of that same tool (found at build-tools in sdk dir)
aapt dump badging /path/to/your/apk

revealed useful information like the position where the check failed:
package: name='X' versionCode='X' versionName='X'
sdkVersion:'7'
targetSdkVersion:'17'
uses-permission:'android.permission.INTERNET'
...
uses-permission:'android.permission.WRITE_EXTERNAL_STORAGE'
uses-feature-not-required:'android.hardware.camera'
uses-feature-not-required:'android.hardware.camera.autofocus'
application-label:'Photo Tools'
application-label-zh:'摄影工具'
application-label-nl:'Photo Tools'
application-label-fr:'Photo Tools'
application-label-es:'Photo Tools'
application-label-it:'Photo Tools'
application-label-ru:'Photo Tools'
application-icon-160:'res/drawable/phototools_icon.png'
application-icon-240:'res/drawable/phototools_icon.png'
application-icon-320:'res/drawable/phototools_icon.png'
application-icon-480:'res/drawable/phototools_icon.png'
application: label='Photo Tools' icon='res/drawable/phototools_icon.png'
launchable-activity: name='be.hcpl.android.phototools.PhotoToolsActivity'  label='Photo Tools' icon=''
W/ResourceType(30945): Failure getting entry for 0x7f0601c6 (t=5 e=454) in package 0 (error -84)
ERROR getting 'android:label' attribute: attribute is not a string value

A: To investigate, I followed the following methodology:

*

*comment out the activities one by one

*build the signed release

*run aapt dump badging /path/to/your/apk

*see errors and repeat

This allowed me to narrow down to the root the of my problem. Just a string without resource instead the label was not being used in the app. I removed the label attribute as a fix.

A: read @hcpl answer, if you cannot finsd the error look for the next activity listed in manifest. in his post:
launchable-activity: name='be.hcpl.android.phototools.PhotoToolsActivity'  label='Photo Tools' icon=''
W/ResourceType(30945): Failure getting entry for 0x7f0601c6 (t=5 e=454) in package 0 (error -84)
ERROR getting 'android:label' attribute: attribute is not a string value

You might think the problem is related to PhotoToolsActivity but it is about the next activity which does not get log because it aapt crashes

A: Check the values/strings.xml and values-xx/strings.xml
You should be sure that everyone word in values/strings.xml must have corresponding word under values-xx/strings.xml .

A: In my case, the default string.xml was missing, accidentally deleted from the project.
I use:
disable 'ExtraTranslation'
disable 'MissingTranslation'

in the gradle, so I've no evidence of the missing string.xml file.


text:
Q: How to make bootstrap-tour work? I have this code in a page. I'm trying to make bootstrap-tour work but it's not happening. What am I doing wrong? What am I missing here?
<!DOCTYPE html>

    <link href="bootstrap.css" rel="stylesheet">
    <link href="bootstrap-tour.css" rel="stylesheet">
    <link href="bootstrap-tour.min.css" rel="stylesheet">


text:
Q: Differences when tuning neural network with two output variables using caret and neuralnet packages I'm using caret package and 'neuralnet' model so as to find the best tuning parameters for a neural network based on a data set which contains several predictors transformed by PCA. This data set also contains two output numeric variables, so I want to model these two variables against the predictors. Thus, I'm performing regression.
When using the package 'neuralnet', I get the desired output: a network whose output layer consists of two neurons, corresponding to the two output variables that I want to model, as you can see from the following code.
library(neuralnet)
neuralnet.network <- neuralnet(x + y ~ PC1 + PC2, train.pca.groundTruth, hidden=2, rep=5, algorithm = "rprop+", linear.output=T)

> head(compute(neuralnet.network, test.pca[,c(1,2)])$net.result)
            [,1]         [,2]
187 0.5890781796 0.3481661367
72  0.7182396668 0.4330461404
107 0.5854193907 0.3446555435
228 0.6114171607 0.3648684296
262 0.6727465772 0.4035759540
135 0.5559830113 0.3288717153

However, when using the same model with train function from caret package, the output consists of just one single variable, named '.outcome', which is in fact the sum of the two variables. This is the code:
paramGrid <- expand.grid(.layer1 = c(2), .layer2 = 0, .layer3 = 0)
ctrl <- trainControl(method = "repeatedcv", repeats = 5)
set.seed(23)
caret.neuralnet <- train(x + y ~ PC1 + PC2, data = train.pca.groundTruth, method = "neuralnet", metric = "RMSE", tuneGrid = paramGrid, trControl = ctrl, algorithm = "rprop+", linear.output = T)

> head(predict(caret.neuralnet, test.pca[,c(1,2)]))
[1] 0.9221328635 1.1953289038 1.0333353272 0.9561434406 1.0409961115 0.8834807926

Is there any possibility to prevent caret train function from interpreting the symbol '+' in a formula as summation but as the specification of several output variables, just as neuralnet does? I've tried the x-y form, though it doesn't work.
I would like to know whether there is any form to do that without training separate models for each output variable.
Thank you so much!

A: train doesn't support multiple outcomes so the intended symbolic formula x + y resolves to a literal one adding x and y.
Max


text:
Q: Appending an array within a post rather than creating a new post I am trying to make a comment section for my open source social media app. I have a table of posts. When you click a post in this table, it takes you to the MainViewController, where you can read the comments on those posts and post your own comment. The Post class is as follows:
import Foundation

class Post {
var id:String
var title: String
var text:String
var createdAt:Date
var comment: [String] = []

init(id: String, title: String,text:String,  timestamp:Double, comment: [String] = []) {
    self.id = id
    self.title = title
    self.text = text
    self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)

}
static func parse(_ key:String, data:[String:Any]) -> Post? {
    if let title = data["text"] as? String,
        let text = data["title"] as? String,
        let timestamp = data["timestamp"] as? Double {
        return Post(id: key, title: title,  text: text, timestamp:timestamp, comment: [])
        }

    return nil
    }
}

And the MainTextViewController has the following code:
import Foundation
import UIKit
import Firebase

class MainTextView: UIViewController, UITextViewDelegate{

@IBOutlet weak var titleText: UILabel!
@IBOutlet weak var mainText: UILabel!

@IBOutlet weak var commentsTable: UITableView!
@IBOutlet weak var commentPlaceHolder: UILabel!
@IBOutlet weak var newCommentLabel: UITextView!
weak var delegate:NewPostVCDelegate?

@IBAction func reply(_ sender: UIButton) {

// Firebase code here
    let postRef = Database.database().reference().child("posts").childByAutoId()

    let postObject = [
        "comment": newCommentLabel.text,
        "timestamp": [".sv": "timestamp"]
        ] as [String : Any]

    postRef.setValue(postObject, withCompletionBlock: { error, ref in
        if error == nil {
            self.delegate!.didUploadPost(withID: ref.key!)
            self.dismiss(animated: true, completion: nil)
        }  else {
            // Handle error

        }
    })
    newCommentLabel.text = String()
    commentPlaceHolder.isHidden = false
}
var post: Post?

// MARK: - View Controller LifeCycle

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.setMain()

}
override func viewDidLoad() {
    super.viewDidLoad()
    print(delegate!)
    commentsTable.dataSource = post?.comment as? UITableViewDataSource
    newCommentLabel.delegate = self

}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return post!.comment.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->   UITableViewCell {
    let cell = UITableViewCell()
    let label = UILabel(frame: CGRect(x:0, y:0, width:200, height:50))
    cell.addSubview(label)
    return cell
}

// UITableViewDelegate Functions

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 50
}

private func setMain() {
    guard let post = self.post else {
        return
    }

    titleText.text = post.text
    mainText.text = post.title
}
func textViewDidChange(_ commentView: UITextView) {

    commentPlaceHolder.isHidden = !newCommentLabel.text.isEmpty

    }
}

Here is my database structure:
  {
  "posts" : {
    "-LhaxLOSY3UI7tDUrCA_" : {
      "text" : "Nelson",
      "timestamp" : 1560800488059,
      "title" : "Hey\t"
    },
    "-LhaxbnjgDP7tdb7Eq_4" : {
      "text" : "Lol",
      "timestamp" : 1560800558514,
      "title" : "How's it going"
    },
    "comment" : {
      "comment" : "Howdy"
    }
  }
}

I want that when I make a comment, it appends the comments array for the post with a new comment. Then everyone can see the comments in the commentsTable as a collection of strings from the array with the oldest one on top.
At the moment, creating a new comment makes a new post in Firebase with just a comment as a single string and a timestamp. How would you fix this issue so that the post button appends the table and the commentsTable shows the strings from the array? Let me know if you need me to post more details. Thank you for the help.

A: Without going overboard with a bunch of code, conceptually, if you want to have a series of posts, and then each post can additionally have comments, here's one option for a structure.
posts
   post_id_0
      text: "some text"
      timestamp: "20190601"
      title: "post title"
      post_uid: "uid_0"

comments
   comment_id_0
      belongs_to_post: "post_id_0"
      comment: "a comment about the post"
      timestamp: "20190601"
      comment_uid: "uid_49"
   comment_id_1
      belongs_to_post: "post_id_0"
      comment: "check out that first post!"
      timestamp: "20190602"
      comment_uid: "uid_102"

users
   uid_0
      name: "Leroy"

then attach observers to posts and comments. When a new post is posted, you'll be notified of that post and can add it to your tableView datasource and refresh the tableView.
When a new comment is added, you'll be notified of that comment and add it to the comments dataSource and reload the comments tableView. To add a new post:
let thisPostRef = your_firebase.posts.childByAutoId()
thisPostRef.setValue(your_post_data)

and to add a comment
let postKey = the_post.key
let commentRef = your_firebase.comments.childByAutoId()
commentRef.setValue(your_comment_data)

and your_comment_data would include a child node 'belongs_to_post: postKey'
You can also watch for comments on certain posts, made by certain users or even query for comments by date or in a date range.
Code wise, both posts and comments nodes are created with .childByAutoId - it's best practice to disassociate node keys from the data they contain, unless it going to be static data, like a uid.
If you want to add a bit more flexibility, you could keep a child node within each posts of it's related comments as well.
posts
   post_id_0
      text: "some text"
      timestamp: "20190601"
      title: "post title"
      post_uid: "uid_0"
      comments:
         comment_id_0: true
         comment_id_1: true

but that depends on what kinds of queries you want to run.
Note: I separate the comments structure from the posts the posts node as denormalizing  your data is very beneficial when running queries.


text:
Q: Handle multiple messages with Queue get() Thanks to @user5402 for the previous solution.
I am trying to handle multiple messages that are queued up. Here is the code:
import sys
import socket
from multiprocessing import Process, Queue

UDP_ADDR = ("", 13000)

def send(m):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(m, UDP_ADDR)

def receive(q):
    buf = 1024
    Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    Sock.bind(UDP_ADDR)
    while True:
        (data, addr) = Sock.recvfrom(buf)
        q.put(data)

In the client function I want to handle multiple messages, that have knock on affects.
def client():
    q = Queue()
    r = Process(target = receive, args=(q,))
    r.start()

    print "client loop started"
    while True:
        m = q.get()
        print "got:", m
        while m == "start":
            print "started"
            z = q.get()
            if z == "stop":
                return
    print "loop ended"
    r.terminate()

So when start is sent, it then goes into a while loop that is infinitely printing "started", and waiting for the stop message to come through. The above client code does not work.
Here is the code to start the function:
if __name__ == '__main__':
    args = sys.argv
    if len(args) > 1:
        send(args[1])
    else:
        client()

A: You can write the client loop like this:
print "client loop started"
while True:
    m = q.get()
    print "waiting for start, got:", m
    if m == "start":
      while True:
        try:
          m = q.get(False)
        except:
          m = None
        print "waiting for stop, got:", m
        if m == "stop":
          break

Based on your comments, this would be a better approach:
import sys
import socket
import Queue as Q
import time
from multiprocessing import Process, Queue

UDP_ADDR = ("", 13000)

def send(m):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(m, UDP_ADDR)

def receive(q):
    buf = 1024
    Sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    Sock.bind(UDP_ADDR)
    while True:
      (data, addr) = Sock.recvfrom(buf)
      q.put(data)

def doit():
  # ... what the processing thread will do ...
  while True:
    print "sleeping..."
    time.sleep(3)

def client():
  q = Queue()
  r = Process(target = receive, args=(q,))
  r.start()

  print "client loop started"
  t = None   # the processing thread
  while True:
      m = q.get()
      if m == "start":
        if t:
          print "processing thread already started"
        else:
          t = Process(target = doit)
          t.start()
          print "processing thread started"
      elif m == "stop":
        if t:
          t.terminate()
          t = None
          print "processing thread stopped"
        else:
          print "processing thread not running"
      elif m == "quit":
        print "shutting down"
        if t:
          t.terminate()
          t = None  # play it safe
        break
      else:
        print "huh?"
  r.terminate()

if __name__ == '__main__':
  args = sys.argv
  if len(args) > 1:
    send(args[1])
  else:
    client()


text:
Q: Trying to add data from parse to an NSMutableArray in IOS So, I am able to successfully perform a query of my parse database. This query matches the logged in user with all objects that have the logged in user in the key user. The object I'm querying has keys "email" "firstName" "lastName" "friendUserName" and "phoneNumber"
I would like to be able to store all the phone numbers into a mutable array named phoneNumbers. The code I am trying to use to do this is.
int i=0;

            for (PFObject *object in objects) {

                NSLog(@"%@", objects[i]);

                phonenumber = object[@"phoneNumber"];
                NSLog(@"%@", phonenumber);

               [phoneNumbers[i] addObject:phonenumber];

                NSLog(@"%@", phoneNumbers[i]);
                i=i+1;
            }

When I run this code the output for the code NSLog(@"%@", phoneNumbers[i]);
comes out a null both times. All other outputs are as expected.

A: The following should work for you:
NSMutableArray *phoneNumbers = [NSMutableArray new];

for (PFObject *object in objects) {
    NSLog(@"%@", object);

    // Assuming your phone numbers are stored as strings - use a different data type if necessary
    NSString *phoneNumber = object[@"phoneNumber"];
    NSLog(@"%@", phoneNumber);

    [phoneNumbers addObject:phoneNumber];
}

NSLog(@"%@", phoneNumbers);

If you're just adding items to the end of a mutable array, you don't need to worry about the index of the items.
The place you were going wrong was when trying to add the object to your array. You were doing this:
[phoneNumbers[i] addObject:phonenumber];

Which is actually saying "fetch the object at index i in the phoneNumbers array, and tell it to add the phone number object". However, presumably your array is empty or not initialised, which means addObject will be sent to a nil object and so not have any effect. Instead, you simply need to tell the phoneNumbers array itself to add the object.


text:
Q: How to bind multiple select components to a single Angular 6+ reactive forms without emitting duplicate changes I need to bind multiple input components to a single angular reactive form, but I have two problems:

*

*out of the box only the form where the user input happens is updated

*if I use [(ngModel)] it works but it also triggers a second change event

How can I keep two select components in sync with the data model without triggering a 2nd event?
template
<select [(ngModel="foo")] [formControl]="bar">
   <option *ngFor="let foo in foos" [value]="foo.value"> {{foo.name}}</option>
</select>
<select [(ngModel="foo")] [formControl]="bar">
   <option *ngFor="let foo in foos" [value]="foo.value"> {{foo.name}}</option>
</select>

component
foo = '';
bar: FormControl;
...
formControl.valueChanges.subscribe(data => ...//this is called two times)

A: Manually patching the events while omitting an event does propagates the new value to every bound element in the template.
bar.valueChanges.subscribe(data => bar.patchValue(data , { emitEvent: false }))


text:
Q: How to get all records before any specified month in mysql I want to select all records before any specified month using mysql. Here is my attempted statement:
SELECT SUM(amount) as allPreviousAmount FROM `fn_table`
WHERE MONTH(transdate) < 1 AND YEAR(transdate) = YEAR(CURRENT_DATE())

transdate is datetime data type.
I have data on December 2018. But this does not select the data. Then I remove the Year part, still no data is selected. The transdate is 2018-12-31 15:59:41.
Please fix it and explain why this is not working.

A: Multiply year by 100 add month (on both sides) and compare.
set @dt1 = '2019-10-01';

select  @dt1,current_date,
            year(@dt1) * 100 + month(@dt1),
            case
                when year(@dt1) * 100 + month(@dt1) < year(current_date) * 100 + month(current_date) then
                    'Less than'
                else 'other'
                end as result;

------------+--------------+--------------------------------+-----------+
| @dt1       | current_date | year(@dt1) * 100 + month(@dt1) | result    |
+------------+--------------+--------------------------------+-----------+
| 2019-10-01 | 2019-11-14   |                         201910 | Less than |
+------------+--------------+--------------------------------+-----------+
1 row in set (0.00 sec)

A: This will do (assuming there are no future dates):
SELECT SUM(amount) as allPreviousAmount
FROM `fn_table`
WHERE MONTH(transdate) < ? OR YEAR(transdate) < YEAR(CURRENT_DATE())

Replace ? with the month that you want the results for.


text:
Q: Getting error on page which is removed from project I tried to used tiny MCE editor in my angular project and first time it works perfectly but after that it was giving me error like theme path not found etc. Then I did some changes according to the documentation and it works, but after that again it was giving me an strange error that editor component not found on my component html where tiny MCE was used. So I planned to use some other editor and removed the line from html code but still I was getting the same error even the line is commented.
Now I have removed the component from my project but getting same error even the component does not exist in project.
What I have tried
Uninstalled all node modules and installed again
, Clean cache
but still no luck.
Please help


text:
Q: Pandas dataframe slice left assignment I want to do a left assignment of one column's values between DataFrame slices where the indexes don't match.
df = pd.DataFrame(data=[('A', '20210101', 5.0),
                        ('B', '20210101', 3.0),
                        ('C', '20210101', 2.0),
                        ('A', '20210102', 0.0),
                        ('C', '20210102', 0.0),
                        ('A', '20210103', 0.0),
                        ('C', '20210103', 0.0),
                        ('D', '20210103', 0.0)],
                  columns=('Name', 'Date', 'Dollars')).set_index(['Name', 'Date'])
dft = df.groupby(df.index.get_level_values('Date'))
dates = list(dft.groups.keys())
df0 = dft.get_group(dates[0]).reset_index(level=1)
df1 = dft.get_group(dates[1]).reset_index(level=1)
df2 = dft.get_group(dates[2]).reset_index(level=1)

Is there a single expression that will work whether the left slice's indexes are a subset or a superset of the right slice's?  The following attempt fails when left is a subset:
df0.loc[df1.index, 'Dollars'] = df1.Dollars  # Works because every key in df1 is in df0
df0.loc[df2.index, 'Dollars'] = df2.Dollars  # KeyError: "['D'] not in index"

A: If you want the missing index in the left DataFrame
You can do a index union on df0.index and df2.index by Index.union followed by reindex() before assigning values of  df2.index to df0, as follows:
df0 = df0.reindex(df0.index.union(df2.index))
df0.loc[df2.index, 'Dollars'] = df2.Dollars  # then this run successfully

Result:
print(df0)

          Date  Dollars
Name
A     20210101      0.0
B     20210101      3.0
C     20210101      0.0
D          NaN      0.0

If you don't want the missing index in the left DataFrame
commonKeys = df0.index.intersection(df2.index)
df0.loc[commonKeys, 'Dollars'] = df2.loc[commonKeys].Dollars

Result df0:
          Date  Dollars
Name
A     20210101      0.0
B     20210101      3.0
C     20210101      0.0


text:
Q: Can a superuser (with 'root' access) manipulate data on a database installed on the server? I am inquiring as to what access a user with the 'root' password on a Linux server has.  On this server, a database is installed.  If someone logs into 'root' do they now have full control (the ability to read, modify, delete, execute) data within that database?
Thank you kindly for your assistance.

A: Short answer yes: root can impersonate any account and read everything is not encrypted.


text:
Q: Can't suppress messages in blogdown/knitr Here is a blog post created with blogdown
The R chunk of code begins with
```{r, echo = FALSE, message = FALSE, warning = FALSE}

However, three messages appear each time I read a shapefile using sf::st_read
How do I prevent these messages from appearing in the post?
Does the answer lie in this page about knitr options?

A:
Moving an apparent solution initially posted in the comments to a full answer. Reasoning outlined in this meta discussion

I think st_read is just printing output normally, this won't be affected by message = FALSE or warning = FALSE. If you don't need any output from the chunk you can do results = 'hide' in the chunk options, otherwise I think you can stop it printing using st_read(..., quiet = TRUE)

Originally posted by Marius in the comments


text:
Q: What is the difference of "__and__" and "__rand__" in class set? I read the book "Fluent Python" by Luciano Ramalho. In the description of class set, he writes:
s & z   # s.__and__(z)   - intersection of s and z
z & s   # s.__rand__(z)   - inversion operator &

I can't understand. Why in the second case he doesn't write: z.__and__(s). The author said: "intersection of s and z" != "inversion operator &".
Is __and__ and __rand__ equal for set() or not?

A:
I can't understand. Why in the second case he doesn't write:
  z.__rand__(s).

Because that's the very point of the reverse operators. They as well exist in the form of __radd__, __rsub__ and so on.
If, when doing a & b, calling a.__and__(b) does not exist or returns NotImplemented, it tries (as a "last resort") to call b.__rand__(a).
See the relevant part of Python's documentation for details.
In your example, probably the class of z doesn't implement __and__, so it falls back to s which supplies __rand__.


text:
Q: Unable to process JSON from Jersey via Jackson on Deserialization of polymorphic type I used the JsonTypeInfo to correctly deserialize the json to appropriate sub-types
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
public abstract class Car {

}

public class Audi extends Car {
   // Getters and Setters
}

public class Merc extends Car {
   // Getters and Setters
}

For the following structure - Map<String, Car> info
Here is my sample JSON
{
   info: {
      "xyz": {
         type: "Audi"
      },
      "abc": {
         type: "Merc"
      }
   }
}

The above JSON does not deserialize correctly and get the error 400: Unable to process JSON. What am I missing here ?

A: Two things, the JSON is incorrect because the properties needs to be between quotes:
{
   "info": {
      "xyz": {
         "type": "Audi"
      },
      "abc": {
         "type": "Merc"
      }
   }
}

And the second, try to add this annotation to the abstract class:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = Audi.class, name = "Audi"),
    @JsonSubTypes.Type(value = Merc.class, name = "Merc")})
abstract class Car {

It basically indicates the subtypes and the names associated.


text:
Q: What is meant by the tuple notation in Linear Algebra? I am taking a course in linear algebra.  A question on an assignment is as follows:

Let $A$ and $B$ be $n\times n$ real matrices.  Show that if $(x,Ay) = (x,By)$ for all x and y in $\mathbb{R}^n$, then $A=B$.

I am quite confused as to the notation of

$(x,Ay) = (x,By)$

This would appear to me to be two tuples, but the question doesn't make a lot of sense if that is the case, for one this statement would be trivially equivalent to
$$Ay = By$$
And the variable $x$ would be entirely useless.  After this reduction the remainder of the proof would still be rather trivial as $\forall y \in \mathbb{R}^n : Ay = By$ is essentially the definition of equality.
I couldn't think of anything else that this notation might represent and I truly doubt that a question this simple would be asked, so I tried to do some searching both on math.se, the duck duck go and of course my notes for the course.
What does this notation mean?

I don't know if anyone intends to do this, but I would really appreciate if no one mentioned the solution or suggested any methods for solving the problem.  I would like to solve this myself and would consider this to ruin the problem.


text:
Q: Running RPT from Crystal Reports 2008 and exporting to PDF I'm trying to run a report automatically and silently.
I found this script:
#include <GUIConstants.au3>
AutoItSetOption("WinTitleMatchMode", 2)

Dim $sReportName
Dim $objCRApp
Dim $objCRReport
Dim $objCRViewer
Dim $CrystalExportOptions
Dim $ExportFileName
Dim $ExportType

$sReportName = FileOpenDialog("C:\Test\zNC\engine\Vinhos", "", "RPT (*.rpt)", 3);Filter "." means all
$objCRApp = ObjCreate("CrystalRuntime.Application.11")
If $objCRApp = 0 Then
    MsgBox(0, "Error", "Could not create CrystalRuntime Application Object")
    Exit
EndIf
$objCRReport = $objCRApp.OpenReport($sReportName)
If $objCRReport = 0 Then
    MsgBox(0, "Error", "Could not open report: " & $sReportName)
    Exit
EndIf

$objCRViewer = ObjCreate("CrystalReports11.ActiveXReportViewer.1")

; Create a simple GUI for our output
$hndReportViewer = GUICreate ( "Embedded Crystal Reports Export test", 640, 580,(@DesktopWidth-640)/2, (@DesktopHeight-580)/2 , $WS_OVERLAPPEDWINDOW + $WS_VISIBLE + $WS_CLIPSIBLINGS)
If $hndReportViewer = 0 Then
    MsgBox(0, "Error", "Could not create Window to display Crystal Reports control")
    Exit
EndIf
;Creates an ActiveX control in the GUI.
$GUIActiveX = GUICtrlCreateObj ( $objCRViewer, -1, -1, 640, 580)
If $GUIActiveX = 0 Then
    MsgBox(0, "Error", "Could not create ActiveX Control in GUI")
    Exit
EndIf
GUICtrlSetResizing ( $GUIActiveX, $GUI_DOCKAUTO)

; Show GUI
GUISetState ()

$objCRViewer.ReportSource = $objCRReport

; Display the Report to watch automation
$objCRViewer.ViewReport
; The report displays a "0" in control 20005 while the report is loading
While ControlGetText("Embedded Crystal Reports printing test", "", 20005) = "0"
    Sleep(250)
WEnd

$CrystalExportOptions = $objCRReport.ExportOptions
$ExportFileName = "C:\Test\zNC\engine\Vinhos\ExportedReport.PDF"
$ExportType = 31

$CrystalExportOptions.DiskFileName = $ExportFileName
$CrystalExportOptions.FormatType = $ExportType
$CrystalExportOptions.DestinationType = 1
$objCRReport.Export ( False )
Sleep(500)
WinWaitClose("Export", "", 30)
GUIDelete()

I can't pass this connection error. I am using Microsoft SQL Server 2008 R2.

Report I created doesn't need a date range, already did that in SQL.

A: I created a DSN file with the "ODBC Data Source" and configured into crystal reports, i just add the DSN file as the database connection of the report. Now it work.


text:
Q: How to find a pareto optimal solution in a smart way (3 variables) $\max\left( { 3x }_{ 1 }+4{ x }_{ 2 }+2{ x }_{ 3 } \right)  $
${ x }^2_{ 1 }+{ x }^2_{ 2 }+{ x }^2_{ 3 }\le 1 $
${ x }_{ i }\ge 0 $
I have to find a Pareto Optimal solution, but I can't solve this by making calculus (Lagrangian function).
So Is there a smart way to do this?
I know the objective function is a plane, and the constraint is a sphere. But is very difficult to find where the plane intersect the sphere

A: You can easily solve this using the Lagrange multiplier method but a smarter way to do this would be as follows.
The question seems to me like an optimisation problem regarding utilisation maximisation of a consumer with finite income. Consider a consumer which is faced to buy three different products with amounts ($x_1$, $x_2$, $x_3$) and prices (1, 1, 1). If the utility function is described as
f($x_1$, $x_2$, $x_3$)= 3$x_1$+4$x_2$+2$x_3$
and the income of the consumer is 1 unit, then the problem is identical to the one stated above.
The optimal solution is reached for
($x_1$, $x_2$, $x_3$)= (0, 1, 0)
since the marginal utility is constant for all variables and largest for $x_2$.
The way described here is only another way to say that the problem is convex ( even linear ) and the optimum is reached on the boundary.
I hope I' m not wrong and it has helped. For further research on this type of specific problem in economics you can start by this link and continue with any undergraduate microeconomics book, the whole theory is related to such problems.

A: since we have maximization problem and the objective is linear, the second condition is idle:
The refined version of the problem :
$
\min-(3x_1 + 4x_2 +2x_3)
$
$
S.j\ \ ||x_i ||_2 <=1
$
Answer:
Lagrange :
$
-(3x_1 + 4x_2 +2x_3)-\lambda (x_1^2+x_2^2+x_3^2)
$
take derivatives and ...
But if you want a shortcut in $4$ options-based tests, check the the options one-by-one what option has norm $\leq 1$ and biggest value of objective function, simultaneously.

A: Using the Cauchy-Schwarz inequality, we have
$$\begin{align}(3x_1+4x_2+2x_3)^2&\leq (3^2+4^2+2^2)(x_1^2+x_2^2+x_3^2)=29(1) \\\Rightarrow 3x_1+4x_2+2x_3&\leq\sqrt{29}\end{align}$$


text: Q: If f, g : X $\rightarrow$ [0,1] are continuous and surjective where X is a connected topological space, there exists x$\in$X such that f(x)=g(x). Let f and g be continuous, surjective functions from X to [0,1] where X is a connected topological space, prove that there exists x$\in$X such that f(x)=g(x). Not sure where to start.


text:
Q: Could not load the 'pgcrypto' Active Record adapter I need to store some confidential data in postgresql database. In order to do that, I used pgcrypto gem. I added this gem to Gemfile and I have changed adapter name in database.yml as pgcrypto. and executed the following command after bundle install. rails generate pgcrypto:install. But I got the following error Could not load the 'pgcrypto' Active Record adapter. Ensure that the adapter is spelled correctly in config/database.yml and that you've added the necessary adapter gem to your Gemfile. (LoadError)  Help me to fix this issue. Ruby-2.6.0 and rails 5.2.4.2

A: I looked at the gem "pgcrypto," and I'm not sure it executes the "create extension" line that's needed to install the extension in your Postgres database.  Can you try running this in your database(s)?  Development and Test?
CREATE EXTENSION IF NOT EXISTS pgcrypto;


text:
Q: Does moving a file/folder makes disk fragmented? Does moving a file/folder causes fragmentation in Disk on Ubuntu 20.04?

A: In this article on Quora 'Does disk fragmentation occur in Linux? If not, why?' it explains that Linux (EXT4) does not fragment any disk. Windows however will (FAT 32/NTFS).
Fragmentation only happens on HDDs (the ones with platters and readheads in them).So you can defrag them once in a while for better performance.
Fragmentation does not  happen on SSDs. Don't perform a defragmentation on these kind of disks. It is useless and the read/writes shorten its lifespan.
So it really depends on what kind of disk(s) you have in your system and what filesystem you use.

A: moving a file with the mv command on the same disk does not move data. It changes only the directory entries relating to this data. Hence, it cannot fragment a disk.


text:
Q: Symfony2 FormBuilder with Entity type with no values I am using an entity type of form element in Symfony2's formbuilder.
 ->add('categories', 'entity', array('required' => false,
            'multiple' => true,
            'expanded' => true,
            'label'=>'Categories (select all that apply)',
            'class' => 'AcmeBundle:Category',
            'query_builder' => function(EntityRepository $er) use ($profile) {
                return $er->createQueryBuilder('u')
                    ->where('u.profile = :profile')
                    ->setParameter('profile', $profile)
                    ->orderBy('u.name', 'ASC');
            }));

There is a case where the database query does not return any values, but Symfony2 still displays the label for the element.
How do I suppress the label altogether for cases where there are no entity results to display? Thanks!

A: In your associated .twig file add this:
{% if not empty(entity.categories) %}
    {{ form_label(form.categories) }}
    {{ form_errors(form.categories) }}
    {{ form_widget(form.categories) }}
{% endif %}

That will display it only if it is not empty

A: Improving the answer of @alainivars since my edit was rejected.
In your associated .twig file add this:
{% if not empty(entity.categories) %}
    {{ form_label(form.categories) }}
    {{ form_errors(form.categories) }}
    {{ form_widget(form.categories) }}
{% else %}
    {% do form.categories.setRendered %}
{% endif %}

That will display it only if it is not empty and marked the setRendered on the field so it doesn't show on the form_rest, thus bypassing your problem.


text:
Q: Getting result from query made by PHP I'm trying to write a PHP function that checks if a given value is in a column of a database. The function takes the argument $userName and $link where $userName will be checked in the userid column of the database $link is for. Here is what I've got so far:
<?php
/*This function checks to see if the username is already in use
INPUT: the userName to check for and a link to the database
OUTPUT: true if there are no other users registered with userName
*/
function isUnique($userName, $link)
{
    $result = !!mysqli_fetch_row(mysqli_query($link, 'SELECT `userid`
    FROM `login`
    WHERE `userid` = \''.$userName.'\''));
    return $result;
}

echo '<title>testing</title>';
$uName = $_POST['us'];
$pass = $_POST['pa'];

//database work
$link = mysqli_connect("localhost:3306", "root", "");
if(!$link)
    die('Could not connect to MySQL: '.mysql_error());
$db_selected = mysqli_select_db($link, 'Accounts');
if(!$db_selected)
    die('Can\'t use Accounts: '.mysql_error());
echo '
Using Accounts database
';
if(isUnique($uName, $link))
{
    echo 'username is unique!
';
}
else
{
    echo 'username is not unique!
';
}
mysqli_close($link);

echo '';
?>

The page always says that the given username is not unique.

A: Try this:
function isUnique($userName, $link) {
    return !!mysqli_fetch_row(mysqli_query($link, "select `userid` from `login` where `userid`='".$userName."'"));
}

Since mysqli_fetch_row returns null if there is no row, and an array if there is one, casting to boolean will tell you if there was a row or not.

A: $userName = mysqli_escape_string($userName); // Or such

"SELECT COUNT(*) FROM login WHERE userid='$userName'"

BTW IMO it's better to INSERT and then check for number of inserted rows and error code / msg.
If that's 0 and "...duplicate...", then you know it's in use, and can treat properly.

A: function isUnique($userName, $link)
{
                $result = mysqli_query($link, 'SELECT `userid`
                        FROM `login`
                        WHERE `userid` = \''.$userName.'\''));
                return mysqli_num_rows($result) == 0;
}

copied from phpfreaks


text:
Q: Checking equality of elements in 2 dataframes in R column by column I'm trying to check the equality of the elements of two dataframes in R column by column using the all.equal function, and I want to do this using a for loop. I'm new to R so I'm not sure how to write a for loop including two dataframes.
Any help is appreciated.

A: I noticed that this question hasn't been answered so I figured I'd put down an answer for future reference.
To provide a working example I'll be using the mtcars dataset that comes with R as part of the datasets package.
So to start off, let's create a dummy dataset to compare with mtcars. Let's call this dataset mtcars2 and let's make columns 5 and 11, drat and carb respectively, differ to some extent from their original mtcars counterparts, while keeping columns 1 to 4 and columns 6 to 10 intact. To "mess" up columns 5 and 11, we'll use jitter() in combination with simple multiplication.
mtcars2 <- as.data.frame(cbind(mtcars[, 1:4], "drat" = jitter(mtcars[,5]) * 4,
                               mtcars[,6:10], "carb" = jitter(mtcars[,11])* 0.5))

So now we have a dummy dataset to compare to mtcars in our for-loop. Next we prepare a data.frame to write in the results of our for-loop. We'll need a data.frame that has a number of rows equal to the number of columns we're going to compare, and we need two columns, one col_number to show which column the corresponding all.equal() result refers to. And then, of course, we need another column, AE_result to store the result of the all_equal() function we'll be calling. We'll call this data.frame df_AE and we'll declare col_number to be a numeric vector, and AE_result to be a character vector.
width <- ncol(mtcars)
df_AE <- as.data.frame(matrix(0L, nrow = width, ncol = 2))

names(df_AE) <- c("col_number", "AE_result")
class(df_AE$col_number) <- "numeric"
class(df_AE$AE_result) <- "character"

So now we're ready for the actual for-loop, where we'll count our way through the columns, calling all.equal on each pair of columns, and writing the counter (i) and the result (x) to our df_AE data.frame.
for (i in 1:width) {
    x <- all.equal(mtcars[, i], mtcars2[, i])
    df_AE[i,1] <- i
    df_AE[i,2] <- x
}

So now when we call df_AE we'll get something like this:
df_AE

> df_AE
       col_number                           AE_result
1           1                                TRUE
2           2                                TRUE
3           3                                TRUE
4           4                                TRUE
5           5  Mean relative difference: 3.000102
6           6                                TRUE
7           7                                TRUE
8           8                                TRUE
9           9                                TRUE
10         10                                TRUE
11         11 Mean relative difference: 0.4982218


text:
Q: Google Chrome completely unresponsive Pages load indefinitely and most of the time I get this error:

Pressing 'wait' or 'kill pages' does nothing, I have to close the error window from the upper right button.
What I mean by 'completely unresponsive':

*

*I have multiple accounts: none works.

*Things like Settings (chrome://settings/) or About (chrome://chrome/) sections are also inaccessible

*Incognito window is also unresponsive

*Creating a new profile starts a new page (chrome://settings/createProfile) that also keeps loading indefinitely
This is not a duplicate of Page(s) Unresponsive in Google Chrome, the pages do not load slowly, they do not load at all, not even the settings, I have no overload, I have enough ram, the other browsers, including a portable Chromium and the Chromium-based Comodo Dragon are not affected by this. I can start 4 or 5 browsers at the same time and only Google Chrome is unresponsive.
As far as I can tell I was using the present latest version of the browser (or at least a very recent one): as I said, About (chrome://chrome/) is not accessible! :) After downloading and installing the latest version, no change. After uninstalling completely and installing last version, no change.
I cannot access the addons and the plugins.

EDIT:

*

*Disabling addons and plugins as specified in this answer didn't help. Deleting the folder %LOCALAPPDATA%\Google\Chrome\User Data\ (removing all profiles) didn't help. The fresh profile is still affected.

*It seems in fact that Chromium portable is somewhat affected by a problem that may or may not be related to this one: when windows/tabs are loading for the first time they are slow to respond, but once loaded they work fine, opening links and other pages as normal. This slowness of windows when first opening the browser is also present in SRIron and Google Chrome Canary (but not in the other Chromium-based browsers that I tested, Opera and Comodo Dragon).

A: There is a software named as CCleaner. I think you should run that software and make clean and registry clean after uninstalling chrome. And then Re-Install.. And Make sure you have antivirus software.

A: Just got this problem on the last update to Chrome 47, on both Win 7 Home and Win 7 Professional machines.  An interim step to restore some functionality is to change the filename of chrome (e.g. to chrome..exe) and have your shortcut target the newly named file. This enables you to open chrome and edit settings. Then (on both my systems) going into settings and disabling hardware acceleration, then changing the filename back to chrome.exe gives a functional chrome installation. At this point my systems still worked after re enabling hardware acceleration.


text:
Q: Updating QC ALM defect Comments Section using REST API Using REST API in Java I am trying to update QC ALM. I am getting value in html format when I am trying to extract comment section for any Defect. So, if I want to add any comment, do I need to pass as HTML content with the previous comment or is there any other way?
I have tried by Just passing the comment but it removes all the previous comment and it does not show the person name who is updating the comment as it happens through GUI.

A: This would help someone who is new to HP REST API.
 1. To find available API end-points,
GET /qcbin/rest/resouce-list

*To get Users' full name
GET /qcbin/rest/domains/<domain_name>/projects/<project>/customization/users/<user_name>

*To get defect comment, the below request fetches only Defect ID = 1  and outputs dev-comments field.
GET /qcbin/rest/domains/<domain_name>/projects/<project_name>/defects?query={id[1]}&fields=dev-comments

*Sample JSON payload,
PUT /qcbin/rest/domains/<domain_name>/projects/<project>/defects/1
{
"Fields": [{
    "Name": "dev-comments",
    "values": [{
        "value": "USER FULL NAME <USER_ID>, 2016-06-29:\n Comment 1 \n
 \n"
    },
    {
        "value": "USER FULL NAME <USER_ID>, 2016-06-29:\n Comment 2 \n
 \n"
    }]
}]

}


text:
Q: Below code are written in mvc controller, can anyone explain this? Can Anyone explain the use of the below lines in .net MVC
string apiResponse = await response.Content.ReadAsStringAsync();
_hdfcData = JsonConvert.DeserializeObject<HDFCData>(apiResponse);

A: string apiResponse = await response.Content.ReadAsStringAsync();

get http response message and serialize it to string
_hdfcData = JsonConvert.DeserializeObject<HDFCData>(apiResponse);

deserialize the string to HDFCData type


text:
Q: Is it the right way to process a PIL image in pytorch? I want to train a deep model from .png images by using Pytorch. I'm using a pre-trained model on ImageNet so I need to normalize images before feeding them to the network, but when I look at the result of the transform I see there are some values more than 1 and some less than -1. I'm wondering shouldn't they all be in [-1, 1] range? Am I doing it in the right way?
There is my code:
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
preprocess = transforms.Compose([
transforms.ToTensor(),
normalize])

x = Image.open("path/to/the/file").convert('RGB')
x = self.transform(x) # I feed the network by x

A: What you are doing is correct but mean and std are not calculated based on your data, rather you've taken those values from ImageNet dataset.
There will be some images which are out of [-1, 1] range as they weren't part of the mean and std calculations in the first place and it's expected during test. Also there are images outside this range as it changes mean and standard deviation to 0 and 1 respectively, hence there are samples which are outside this range.
If you wish to fine-tune your neural network you should calculate per-channel mean and std and input those values instead (though it might not make a large difference, depending on dataset and how many images you have).


text:
Q: how to ignore all files with same extension in directory I need to fix this part of my .hgignore
win/*.opensdf
win/*.sdf
win/*.suo
win/*.filters
win/*.user
win/*.db3

seems like it doesn't work as it wrote here.
win is at root. And even *.db3 doesn't work for me, only (?i).db3

A: Is win at your root? Otherwise you will need */win/*.ext


text:
Q: How can I create a valid object in a recursively generic class? Question:
I'm implementing a recursive add() method on a tree type datastructure, implemented with a generic class representing tree nodes.
How can I create a sub-tree in that recursion, if the sub-tree is a generic type - thus has no constructor I can call?
Details of Situation:
I have a generic class set (which underneath is a map) that is designed to implement maps of maps of maps of ... of objects (basically, N level tree).
public interface NodeInterface<KeyType, ValueType> {
    public void add(List<KeyType>, ValueType);
    public ValueType getSubTree(KeyType); // Get subtree map
}

// Generic map class.
// Leaf level nodes are maps too, just not maps containing other maps
public abstract class NodeMap <KeyType, ValueType> implements NodeInterface<> {
    protected Map<KeyType, ValueType> map; // actual map
    ...

}

// Leaf level objects - map NOT containing other maps
public class LeafNode extends NodeMap <String, MyDataType> {
    public void add(List<KeyType>, ValueType) {} // implementation for leaf add
    ...
}

// Tree nodes (non-leaf)
public class ParentNodeMap <ValueType extends NodeMap <?,?>>
    extends NodeMap <String, ValueType> {
     // This class is needed because there are methods that must be
     // implemented on a map that can't be implemented on leaf level nodes.
     ...
}

// Actual tree node classes (needed as syntactic sugar, to avoid end users
// having to deal with HashMap<String, Hashmap<String, HashMap<String, ...MyDataType>>>>>
public class Level2Node extends ParentNodeMap <LeafNode> {
}
public class Level1Node extends ParentNodeMap <Level2Node > {
}

What needs to be done:
I'm trying to implement a method which will recursively insert the leaf level object into this map of map of maps (described in the interface).
E.g., the desired behavior is:
tree = new Level1Node();
List<String> keys = Arrays.asList("key1", "key2"); // I think I need 3 here? irrelevant.
MyDataType data = new MyDataType();
tree.add(keys, data);

Problem:
I can't seem to implement creation and insertion of the subtree map in the add() method for ParentNode
This is what I tried in ParentNodeMap class:
public void add(List<KeyType> keys, ValueType value);
    KeyType key = getFirstKey(keys);
    createMapIfNull(); // creates "map" as new HashMap<KeyType, ValueType>()
    ValueType subTree = getSubTree(key); // Gets me child subtree from map
    // PROBLEM! that subtree is now "null" since we just created an new Map
    // which has no key "hey"

    // Now here's where we should create a new subtree and add it:
    if (subTree == null) {
        subTree = new ValueType<>(); // THIS IS WHAT FAILS!!!!
        map.put(key, subTree);
        subTree.add(keys.removeFirstKey(), value); // recursively add to subtree
    }

Now, what I'm specifically stuck on is: How can I create an subTree object (of NodeMap type); where its type is generic ValueType extends NodeMap <?,?> and that's all I know of it?
Calling new ValueType() gives "Cannot instantiate the type ValueType" error.


text:
Q: sort a mongodb query based on a field in a subdocument in Go suppose I have the following struct
type Test struct {
  Title  string `bson:"title" json:"title"`
  Update Update `bson:"update" json:"update"`
}

type Update struct {
  Changes    []string  `bson:"change" json:"change"`
  UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
}

And suppose I want to sort my results in the Query by "update.updatedAt"
cs.Find(bson.M{title: "some title"}).Sort("-update.updatedAt").Limit(10).All(&results)

This query does not work as expected. I can't seem to find any documentation about how to sort a Query by a subdocument field. Intuitively, I was certain that my example would work. For reference, "-updatedAt" works just fine, but for reasons that aren't necessary to explain, I have to keep Update as a subdocument of Test.
Every example and Stack Overflow question I have seen so far involves the sorting and reordering of subdocuments, or arrays. In this case I don't care about the order of my subdocuments, and I'm not sorting by anything inside of an array. I merely want to sort my the documents by the date of a subdocument.
Is there a way to do this with the Go Mgo Query library?

A: I'm pretty sure it is something with your data structures because next code works as expected (you can test it on your PC)
package main

import (
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "log"
    "time"
)

type Test struct {
    Title  string `bson:"title" json:"title"`
    Update Update `bson:"update" json:"update"`
}

type Update struct {
    Changes   []string  `bson:"change" json:"change"`
    UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
}

func main() {
    session, err := mgo.Dial("mongodb://souser:123456@ds055855.mlab.com:55855/catalog")

    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("catalog").C("sortable")

    /*
        // Fill collection with test data (test collection aready has 15 elements)
        for i := 0; i < 15; i++ {
            c.Insert(&Test{
                Title: "Title",
                Update: Update{
                    Changes:   []string{fmt.Sprintf("Changes #%d", i)},
                    UpdatedAt: time.Now(),
                },
            })
        }
    */

    var results []Test

    err = c.Find(bson.M{"title": "Title"}).Sort("-update.updatedAt").Limit(10).All(&results)
    if err != nil {
        log.Fatal(err)
    }

    for _, e := range results {
        fmt.Println(e.Update.UpdatedAt)
    }
}

A: You need to pass subdocument fields comma(,) seperated like:
cs.Find(bson.M{title: "some title"}).Sort("update","-updatedAt").Limit(10).All(&results)


text:
Q: UIAlertViewController adding textfield delegate
I have implemented textfield in UIAlertViewController but I want implement delegate methods to that textfields.

`UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Total Value"  message:@""  preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
     [alert dismissViewControllerAnimated:YES completion:nil];
}];
[ok setEnabled:NO];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField)
 {
     textField.placeholder = @"TotalValue";
     textField.enabled = YES;
     [[alert textFields][0] delegate];
     [NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidChangeNotification object:textField queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note)
      {
          textField.text.length >0 ? [ok setEnabled:YES]: [ok setEnabled:NO];
      }];
     [NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidEndEditingNotification object:textField queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note)
      {
          [self updateTotalValue:textField.text];
      }];
 }];
[alert addAction:ok];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                         {
                             [alert dismissViewControllerAnimated:YES completion:nil];
                         }];
[alert addAction:cancel];
[self.navigationController presentViewController:alert animated:YES completion:nil];`UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Total Value"  message:@""  preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
{
     [alert dismissViewControllerAnimated:YES completion:nil];
}];
[ok setEnabled:NO];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField)
 {
     textField.placeholder = @"TotalValue";
     textField.enabled = YES;
     [[alert textFields][0] delegate];
     [NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidChangeNotification object:textField queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note)
      {
          textField.text.length >0 ? [ok setEnabled:YES]: [ok setEnabled:NO];
      }];
     [NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidEndEditingNotification object:textField queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note)
      {
          [self updateTotalValue:textField.text];
      }];
 }];
[alert addAction:ok];
UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                         {
                             [alert dismissViewControllerAnimated:YES completion:nil];
                         }];
[alert addAction:cancel];
[self.navigationController presentViewController:alert animated:YES completion:nil];

ERoor : Assigning to 'id _Nullable' from incompatible type 'ApprovalDetailsViewController *const __strong'

In addtextfieldconfiguration I want to do my delegate method but it will some errors
     Please can any one give example.

A: You can implement like below -
-(void)showAlert {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Total Value"  message:@""  preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                         {
                             [alert dismissViewControllerAnimated:YES completion:nil];
                         }];
    [ok setEnabled:NO];

    __weak typeof(self) weakSelf = self;

    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField)
     {
         __strong typeof(self) strongSelf = weakSelf;

         textField.placeholder = @"TotalValue";
         textField.enabled = YES;
         textField.delegate = strongSelf;
         [NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidChangeNotification object:textField queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note)
          {
              textField.text.length >0 ? [ok setEnabled:YES]: [ok setEnabled:NO];
          }];
         [NSNotificationCenter.defaultCenter addObserverForName:UITextFieldTextDidEndEditingNotification object:textField queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note)
          {
              [strongSelf upadteTotalValue:textField.text];
          }];
     }];
    [alert addAction:ok];

    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                             }];
    [alert addAction:cancel];

    [self.navigationController presentViewController:alert animated:YES completion:nil];
}
-(void)upadteTotalValue:(NSString *)text {
    NSLog(@"%s",__FUNCTION__);
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%s",__FUNCTION__);
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"%s",__FUNCTION__);

}


text:
Q: Realizar SELECT randômico Tenho uma tabela onde desejo sempre mostrar um único registro de forma randômica.
Estou fazendo assim:
SELECT `id` FROM `tabela` ORDER BY RAND() LIMIT 1

Vejo que dessa forma os mesmos registros repetem muito, existe uma melhor forma de se fazer?

A: Com MySQL 4.1 ou mais recente, podes fazer o seguinte:
SELECT id FROM tabela WHERE id >= (SELECT FLOOR(MAX(id) * RAND()) FROM tabela) ORDER BY id LIMIT 1;

Nota que este método só funciona em tabelas com IDs únicos.


text:
Q: how to construct a class that requires a non-constant amount of heaps the program input in String[] args will look like this 123 0 0 where each rod of the hanoi tower is seperated by a space and each 1-digit integer represents a disk of that size.
How do I make a class of HanoiState that allows me to save the current state that is given as input, and make it so that moving any disk at the top of a rod, in this case it's "1", from one rod to the one adjacent to it is simple.
The command line prompt examples: $java hanoi 123 0 0 or $java hanoi 12 0 4 0
I was thinking of constructing n amount of priority queues for n amount of rods after parsing the input. However, the number of rods is not constant and I'm not sure how to code this.
Is it also possible to construct an array of priority queues? or a list of priority queues?
public static class HanoiState {
    public HanoiState(int rods){

    }
}

 public static void main(String[] args) {
    if (args.length < 3) {
        return;
    }
    HanoiState a = new HanoiState(args.length - 1);

A: Each rod is a stack of discs, so use the Stack class (java.util.Stack). Then, you can use the push(item) and pop() methods to put and take integers off of the top of each rod.
So each rod is a Stack of Integers. To take a disc off of rod n, call rods[n].pop() and to put a disc of size i onto rod n, call rods[n].push(i).
import java.util.Stack;

public class HanoiState {
    Stack<Integer>[] rods;

    public HanoiState(int numOfRods){
        this.rods = (Stack<Integer>[]) new Stack[numOfRods];
    }
}


text:
Q: Swift playground with SceneKit has really low fps I'm working on some SceneKit project for WWDC, but I came across the issue where the fps in the playground live view is extremely low. Please see picture below.
This is the stats on a real device:

This is the stats in the playground

As you can see, the difference is quite significant. Also, does the live view even support Metal??? I know it's kinda like a simulator, so probably it only supports OpenGL? ("GL flush" instead of "Metal flush?")
Another issue is that if I try to pan-gesture the entire scene(it rotates), the fps drops to almost 0...It gets stuck....whereas in the iOS simulator which also uses OpenGL rendering, at least it will rotate without any problems.
The code is exactly the same in my playground file as in my xcproject.
Any help will be great!
Many thanks.


text:
Q: Vue SSR Attribute Remove I am build some app using Vue JS, and I'm implement with SSR, when open the source code vue render some attribute

how to remove attribute data-server-rendered="true" , i want my final code like
 is there a way to remove the code ?
Thank you for the help