text:
Q: Getting and sorting from JSON on jqGrid I'm new with jQuery and jqGrid and I'm getting two types of JSON content from another system with the following formats:
Option #1
{
    "@timestamp": "2012-03-27T16:19:26Z",
    "@toplevelentries": 40000,
    "items": [
        {
            "@entryid": "1-B933790B1DC265ED8025725800728CC5",
            "@unid": "B933790B1DC265ED8025725800728CC5",
            "@noteid": "1E76E",
            "@position": "1",
            "@read": true,
            "@siblings": 40000,
            "$17": "Aaron, Adam",
            "InternetAddress": "consurgo@compleo.net",
            "OfficeCountry": "Namibia"
        },
        {
            "@entryid": "2-9D93E80306A7AA88802572580072717A",
            "@unid": "9D93E80306A7AA88802572580072717A",
            "@noteid": "19376",
            "@position": "2",
            "@read": true,
            "@siblings": 40000,
            "$17": "Aaron, Dave",
            "InternetAddress": "gratia@incito.co.uk",
            "OfficeCountry": "Brazil"
        },
        {
            "@entryid": "3-FAFA753960DB587A80257258007287CF",
            "@unid": "FAFA753960DB587A80257258007287CF",
            "@noteid": "1D842",
            "@position": "3",
            "@read": true,
            "@siblings": 40000,
            "$17": "Aaron, Donnie",
            "InternetAddress": "vociferor@nequities.net",
            "OfficeCountry": "Algeria"
        }
    ]
}

Here the jqgrid I have is defined like this:
$().ready(function(){
    jQuery("#list2").jqGrid({
        url:'./xGrid2.xsp/peoplejson',
        datatype: "json",
        colNames:['#','InternetAddress','Name','OfficeCountry'],
        colModel:[
            {name:'@position',index:'@position', width:50, sortable:true},
            {name:'InternetAddress',index:'InternetAddress', width:200, sortable:true},
            {name:'$17',index:'$17', width:200, sortable:true},
            {name:'OfficeCountry',index:'OfficeCountry', width:200, sortable:true}
        ],
        jsonReader: {
            repeatitems: false,
            root: "items",
            id: "@position",
            records: "@toplevelentries",
            page:2,
            total:5
        },
        sortname: '@position',
        sortorder: "desc",
        height:500,
        rowNum:50,
        rowList:[50,100,150],
        caption:"JSON Example",
        pager: '#pager2'
    });
});

I get the data but sorting and paging is not working.
Option 2
[
    {
        "@entryid": "1-B933790B1DC265ED8025725800728CC5",
        "@unid": "B933790B1DC265ED8025725800728CC5",
        "@noteid": "1E76E",
        "@position": "1",
        "@read": true,
        "@siblings": 40000,
        "@form": "Person",
        "$17": "Aaron, Adam",
        "InternetAddress": "consurgo@compleo.net",
        "OfficeCountry": "Namibia"
    },
    {
        "@entryid": "2-9D93E80306A7AA88802572580072717A",
        "@unid": "9D93E80306A7AA88802572580072717A",
        "@noteid": "19376",
        "@position": "2",
        "@read": true,
        "@siblings": 40000,
        "@form": "Person",
        "$17": "Aaron, Dave",
        "InternetAddress": "gratia@incito.co.uk",
        "OfficeCountry": "Brazil"
    },
    {
        "@entryid": "3-FAFA753960DB587A80257258007287CF",
        "@unid": "FAFA753960DB587A80257258007287CF",
        "@noteid": "1D842",
        "@position": "3",
        "@read": true,
        "@siblings": 40000,
        "@form": "Person",
        "$17": "Aaron, Donnie",
        "InternetAddress": "vociferor@nequities.net",
        "OfficeCountry": "Algeria"
    }
]

here the jqgrid I have is defined like this:
$().ready(function(){
    jQuery("#list2").jqGrid({
        url:'./xGrid4.xsp/peoplejson',
        datatype: "json",
        colNames:['InternetAddress','Name', 'OfficeCountry'],
        colModel:[
            {name:'InternetAddress',index:'InternetAddress', width:200},
            {name:'$17',index:'$17', width:200},
            {name:'OfficeCountry',index:'OfficeCountry', width:200}
        ],
        jsonReader: {
            repeatitems: false,
            id: "InternetAddress",
            root: function (obj) { return obj; },
            page: function (obj) { return 1; },
            total: function (obj) { return 1; },
            records: function (obj) { return obj.length; }
        },
        caption:"JSON Example",
        height:500,
        sortable:true,
        rowNum:250,
        rowList:[250,500,750,1000],
        pager: '#pager2'
    });
});

Again not sure if I'm defining correctly my jqrig object since here I don't have a root element on JSON.
In both options sorting is not working and I cannot get populated correctly the total of records and pages on Pager element.
Any help will be appreciated.

A: You have two main problems. The first one: the sorting. It's very easy to solve. jqGrid with datatype: 'json' ask the get only one page of sorted data. If the user change the sorting order or go to the next page for example the new request with another parameters will be send to the server.
If you want that the data will be loaded only once from the server and then will be locally sorted or paged you need just add loadonce: true option to the grid. You have to returns still correctly sorted data to have correct sort order initially.
For performance reason you should always include gridview: true to the list of used options.
The next your problem with two formats of JSON data returned from the server you can solve in the simple way. You can modify the jsonReader to the following:
jsonReader: {
    repeatitems: false,
    id: "InternetAddress",
    root: function (obj) {
        if ($.isArray(obj)) {
            return obj;
        }
        if ($.isArray(obj.items)) {
            return obj.items;
        }
        return [];
    },
    page: function () { return 1; },
    total: function () { return 1; },
    records: function (obj) {
        if ($.isArray(obj)) {
            return obj.length;
        }
        if ($.isArray(obj.items)) {
            return obj.items.length;
        }
        return 0;
    }
}

The corresponding demos: the first one and the second one use the same code, but read different formatted JSON data (the data which you posted). Both produce the same results. I changed rowNum to rowNum: 2 to demonstrate that local paging work. Additionally you can consider to use height: 'auto' instead of fixed value height: 500. The rowNum which you use will define the height of the grid.
Additionally I included in the second demo the line
$("#list2").jqGrid('filterToolbar',
    {stringResult: true, defaultSearch: 'cn', searchOnEnter: false});

to demonstrate the power of local data filtering. I added one more option ignoreCase: true to have case insensitive filtering/searching of data.


text:
Q: Json Objects to Valid Json Array Conversion I've series of Json Objects that look like below

{      "Title":"The Avengers",    "Year":"2012",    "Genre":"Action,
  Sci-Fi, Thriller",    "Director":"Joss Whedon",    "imdbRating":"8.1",
  } {      "Title":"Batman Begins",    "Year":"2005",
  "Genre":"Action, Adventure",    "Director":"Christopher Nolan",
  "imdbRating":"8.3", } {      "Title":"The Dark Knight",
  "Year":"2008",    "Genre":"Action, Crime, Drama",
  "Director":"Christopher Nolan",    "imdbRating":"9.0", }

Can any one help to convert the above in to valid Json Array using JAVA like below?
[
   {
      "Title":"The Avengers",
      "Year":"2012",
      "Genre":"Action, Sci-Fi, Thriller",
      "Director":"Joss Whedon",
      "imdbRating":"8.1"
   },
   {
      "Title":"Batman Begins",
      "Year":"2005",
      "Genre":"Action, Adventure",
      "Director":"Christopher Nolan",
      "imdbRating":"8.3"
   },
   {
      "Title":"The Dark Knight",
      "Year":"2008",
      "Genre":"Action, Crime, Drama",
      "Director":"Christopher Nolan",
      "imdbRating":"9.0"
   }
]

A: your question its self has the answer. Make sure that your json is wrapped with array brackets "[]" then you can convert the same at the java end using some json library like Gson (https://github.com/google/gson)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the index of an Object without writing a loop javascript Have an Object, which has success and error objects in it. Expected answer is, I have an ajax call wrapper, so this wrapper stops the normal behaviour of ajax. once the api gets the response, the response will bypass to my wrapper and there i will take that object and search for the "key", this key will be same to the below object "key"
for example response.key = "01", I need to match this key with my below object. I can do it by using a loop. but i don't want to write a loop, because the response might have thousand of values which will impact the performance. Is there any such a way that I can achieve this without using loops.
help me out with a basic demo example. thanks.
Object:
var getValue = {
    success: {
        "01":"success 1",
        "02":"success 2"
    },
    failure: {
        "03":"failure 1",
        "04":"failure 2"
    },
};

A: Try
return getValue.success[response.key]||getValue.failure[response.key];

A: If you only have "success" and "failure", you could try:
    if (getValue.success[response.key]) {
        console.log(getValue.success[response.key]);
    } else {
        console.warn(getValue.failure[response.key]);
    }


text:
Q: Duplicated classes - Unity - Android The point is that Im doing a Project in Unity that combines VR and AR in the same mobile application.
When I try to compile the program I get the next error:
CommandInvokationFailure: Unable to convert classes into dex format.
C:/Program Files/Java/jdk1.8.0_131\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/al315149/AppData/Local/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Application;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$AudioStats;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$Capture;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$Share;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$ShareStart;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$View;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/google/common/logging/nano/Vr$VREvent$DoublePrecisionTransform;

UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Translation has been interrupted
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:615)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:313)
    at com.android.dx.command.dexer.Main.runDx(Main.java:291)
    at com.android.dx.command.dexer.Main.main(Main.java:247)
    at com.android.dx.command.Main.main(Main.java:94)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at SDKMain.main(SDKMain.java:130)
Caused by: java.lang.InterruptedException: Too many errors
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:607)
    ... 9 more
]
stdout[
ignored resource C:\Users\al315149\Desktop\CarConfigurator\CarConfigurator\CarConfigurator\Temp\StagingArea\android-libraries\gvr-keyboard\libs\.\armeabi-v7a\libgvr_keyboard_shim_unity.so
processing archive C:\Users\al315149\Desktop\CarConfigurator\CarConfigurator\CarConfigurator\Temp\StagingArea\android-libraries\gvr-keyboard\libs\.\classes.jar...
ignored resource com/google/vr/keyboard/
processing com/google/vr/keyboard/BuildConstants.class...
processing com/google/vr/keyboard/GvrKeyboardLoaderClient.class...
processing com/google/vr/keyboard/GvrKeyboardLoaderClient$1.class...
processing com/google/vr/keyboard/GvrKeyboardLoaderClient$KeyboardContextWrapper.class...
processing com/google/vr/keyboard/GvrKeyboardUnity.class...
processing com/google/vr/keyboard/IGvrKeyboardLoader.class...
processing com/google/vr/keyboard/IGvrKeyboardLoader$Stub.class...
processing com/google/vr/keyboard/IGvrKeyboardLoader$Stub$Proxy.class...
processing archive C:\Users\al315149\Desktop\CarConfigurator\CarConfigurator\CarConfigurator\Temp\StagingArea\android-libraries\gvr-keyboardsupport-release\libs\.\classes.jar...
processing com/google/gvr/keyboardsupport/BuildConfig.class...
processing com/google/gvr/keyboardsupport/KeyboardFragment.class...
processing com/google/gvr/keyboardsupport/KeyboardFragment$1.class...
processing com/google/gvr/keyboardsupport/KeyboardFragment$KeyboardCallback.class...
processing com/google/gvr/keyboardsupport/TransitionVRActivity.class...
processing archive C:\Users\al315149\Desktop\CarConfigurator\CarConfigurator\CarConfigurator\Temp\StagingArea\android-libraries\gvr-permissionsupport-release\libs\.\classes.jar...
processing com/google/gvr/permissionsupport/BuildConfig.class...
processing com/google/gvr/permissionsupport/PermissionsFragment.class...
processing com/google/gvr/permissionsupport/PermissionsFragment$1.class...
processing com/google/gvr/permissionsupport/PermissionsFragment$PermissionsCallback.class...
processing com/google/gvr/permissionsupport/TransitionVRActivity.class...
processing com/google/gvr/permissionsupport/TransitionVRActivity$1.class...
ignored resource C:\Users\al315149\Desktop\CarConfigurator\CarConfigurator\CarConfigurator\Temp\StagingArea\android-libraries\gvr\libs\.\armeabi-v7a\libgvr.so
processing archive C:\Users\al315149\Desktop\CarConfigurator\CarConfigurator\CarConfigurator\Temp\StagingArea\android-libraries\gvr\libs\.\classes.jar...
processing com/google/common/logging/nano/Vr$VREvent.class...
processing com/google/common/logging/nano/Vr$VREvent$Application.class...
processing com/google/common/logging/nano/Vr$VREvent$AudioStats.class...
processing com/google/common/logging/nano/Vr$VREvent$Cyclops.class...
processing com/google/common/logging/nano/Vr$VREvent$Cyclops$Capture.class...
processing com/google/common/logging/nano/Vr$VREvent$Cyclops$Share.class...
processing com/google/common/logging/nano/Vr$VREvent$Cyclops$ShareStart.class...
processing com/google/common/logging/nano/Vr$VREvent$Cyclops$View.class...
processing com/google/common/logging/nano/Vr$VREvent$DoublePrecisionTransform.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Actor.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Actor$ControllerState.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$AppState.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$ControllerState.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Environment.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Menu.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Preferences.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$SplashScreen.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Tour.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$Tutorial.class...
processing com/google/common/logging/nano/Vr$VREvent$EarthVr$View.class...
processing com/google/common/logging/nano/Vr$VREvent$EmbedVrWidget.class...
processing com/google/common/logging/nano/Vr$VREvent$EmbedVrWidget$Pano.class...
processing com/google/common/logging/nano/Vr$VREvent$EmbedVrWidget$Video.class...
processing com/google/common/logging/nano/Vr$VREvent$GConfigUpdate.class...
processing com/google/common/logging/nano/Vr$VREvent$GConfigUpdate$GConfigValue.class...
processing com/google/common/logging/nano/Vr$VREvent$HeadMount.class...
processing com/google/common/logging/nano/Vr$VREvent$HistogramBucket.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$AudioDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$ImageDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$ImagePlaybackDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$MediaDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$PickerDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$PlaybackDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$Resolution.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$SphericalMetadata.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$VideoDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$JumpInspector$VideoPlaybackDetails.class...
processing com/google/common/logging/nano/Vr$VREvent$Keyboard.class...
processing com/google/common/logging/nano/Vr$VREvent$Keyboard$KeyboardEvent.class...
processing com/google/common/logging/nano/Vr$VREvent$Keyboard$KeyboardTextEntry.class...
processing com/google/common/logging/nano/Vr$VREvent$Launcher.class...
processing com/google/common/logging/nano/Vr$VREvent$Lullaby.class...
processing com/google/common/logging/nano/Vr$VREvent$Lullaby$LoadTime.class...
processing com/google/common/logging/nano/Vr$VREvent$PerformanceStats.class...
processing com/google/common/logging/nano/Vr$VREvent$Photos.class...
processing com/google/common/logging/nano/Vr$VREvent$Photos$OpenMedia.class...
processing com/google/common/logging/nano/Vr$VREvent$Photos$WarmWelcome.class...
processing com/google/common/logging/nano/Vr$VREvent$QrCodeScan.class...
processing com/google/common/logging/nano/Vr$VREvent$Renderer.class...
processing com/google/common/logging/nano/Vr$VREvent$SdkConfigurationParams.class...
processing com/google/common/logging/nano/Vr$VREvent$SdkConfigurationParams$AsyncReprojectionConfig.class...
processing com/google/common/logging/nano/Vr$VREvent$SensorStats.class...
processing com/google/common/logging/nano/Vr$VREvent$SensorStats$GyroscopeStats.class...
processing com/google/common/logging/nano/Vr$VREvent$SensorStats$Vector3.class...
processing com/google/common/logging/nano/Vr$VREvent$StreetView.class...
processing com/google/common/logging/nano/Vr$VREvent$StreetView$PanoSession.class...
processing com/google/common/logging/nano/Vr$VREvent$TimeSeriesData.class...
processing com/google/common/logging/nano/Vr$VREvent$TimeSeriesData$TimeIntervalData.class...
processing com/google/common/logging/nano/Vr$VREvent$Transform.class...
processing com/google/common/logging/nano/Vr$VREvent$VrCore.class...
processing com/google/common/logging/nano/Vr$VREvent$VrCore$Controller.class...
processing com/google/common/logging/nano/Vr$VREvent$VrHome.class...
processing com/google/common/logging/nano/Vr$VREvent$VrHome$DialogAction.class...
processing com/google/common/logging/nano/Vr$VREvent$VrHome$GetViewerClick.class...
processing com/google/common/logging/nano/Vr$VREvent$VrHome$Setup.class...
processing com/google/common/logging/nano/Vr$VREvent$VrHome$Setup$StepStateChange.class...
processing com/google/common/logging/nano/Vr$VREvent$VrHome$Setup$View.class...
processing com/google/vr/audio/DeviceInfo.class...
processing com/google/vr/audio/DeviceInfo$1.class...
processing com/google/vr/audio/DeviceInfo$HeadphoneState.class...
processing com/google/vr/cardboard/AndroidNCompat.class...
processing com/google/vr/cardboard/AndroidNCompat$1.class...
processing com/google/vr/cardboard/AndroidNCompat$2.class...
processing com/google/vr/cardboard/AndroidNCompat$3.class...
processing com/google/vr/cardboard/CardboardGLSurfaceView.class...
processing com/google/vr/cardboard/CardboardGLSurfaceView$DetachListener.class...
processing com/google/vr/cardboard/ConfigUtils.class...
processing com/google/vr/cardboard/ContentProviderVrParamsProvider.class...
processing com/google/vr/cardboard/ContextUtils.class...
processing com/google/vr/cardboard/DisplaySynchronizer.class...
processing com/google/vr/cardboard/DisplayUtils.class...
processing com/google/vr/cardboard/EglFactory.class...
processing com/google/vr/cardboard/EglReadyListener.class...
processing com/google/vr/cardboard/ExternalSurfaceManager.class...
processing com/google/vr/cardboard/ExternalSurfaceManager$ExternalSurface.class...
processing com/google/vr/cardboard/ExternalSurfaceManager$ExternalSurface$1.class...
processing com/google/vr/cardboard/ExternalSurfaceManager$ExternalSurfaceCallback.class...
processing com/google/vr/cardboard/ExternalSurfaceManager$ExternalSurfaceCallback$1.class...
processing com/google/vr/cardboard/ExternalSurfaceManager$ExternalSurfaceCallback$2.class...
processing com/google/vr/cardboard/ExternalSurfaceManager$ExternalSurfaceData.class...
processing com/google/vr/cardboard/FrameMonitor.class...
processing com/google/vr/cardboard/FullscreenMode.class...
processing com/google/vr/cardboard/FullscreenMode$1.class...
processing com/google/vr/cardboard/FullscreenMode$1$1.class...
processing com/google/vr/cardboard/LegacyVrParamsProvider.class...
processing com/google/vr/cardboard/MutableEglConfigChooser.class...
processing com/google/vr/cardboard/NFCUtils.class...
processing com/google/vr/cardboard/NFCUtils$1.class...
processing com/google/vr/cardboard/PackageUtils.class...
processing com/google/vr/cardboard/PhoneParams.class...
processing com/google/vr/cardboard/PhoneParams$PpiOverride.class...
processing com/google/vr/cardboard/ScanlineRacingRenderer.class...
processing com/google/vr/cardboard/ScanlineRacingRenderer$1.class...
processing com/google/vr/cardboard/ScreenOrientationDetector.class...
processing com/google/vr/cardboard/ScreenOrientationDetector$Listener.class...
processing com/google/vr/cardboard/ScreenOrientationDetector$Orientation.class...
processing com/google/vr/cardboard/StoragePermissionUtils.class...
processing com/google/vr/cardboard/ThreadUtils.class...
processing com/google/vr/cardboard/TransitionView.class...
processing com/google/vr/cardboard/TransitionView$1.class...
processing com/google/vr/cardboard/TransitionView$2.class...
processing com/google/vr/cardboard/TransitionView$3.class...
processing com/google/vr/cardboard/TransitionView$4.class...
processing com/google/vr/cardboard/TransitionView$5.class...
processing com/google/vr/cardboard/TransitionView$TransitionListener.class...
processing com/google/vr/cardboard/UiLayer.class...
processing com/google/vr/cardboard/UiLayer$1.class...
processing com/google/vr/cardboard/UiLayer$10.class...
processing com/google/vr/cardboard/UiLayer$11.class...
processing com/google/vr/cardboard/UiLayer$2.class...
processing com/google/vr/cardboard/UiLayer$3.class...
processing com/google/vr/cardboard/UiLayer$4.class...
processing com/google/vr/cardboard/UiLayer$5.class...
processing com/google/vr/cardboard/UiLayer$6.class...
processing com/google/vr/cardboard/UiLayer$7.class...
processing com/google/vr/cardboard/UiLayer$8.class...
processing com/google/vr/cardboard/UiLayer$9.class...
processing com/google/vr/cardboard/UiUtils.class...
processing com/google/vr/cardboard/UiUtils$1.class...
processing com/google/vr/cardboard/UiUtils$2.class...
processing com/google/vr/cardboard/UiUtils$3.class...
processing com/google/vr/cardboard/UiUtils$4.class...
processing com/google/vr/cardboard/UsedByNative.class...
processing com/google/vr/cardboard/VrContextWrapper.class...
processing com/google/vr/cardboard/VrCoreLibraryLoader.class...
processing com/google/vr/cardboard/VrParamsProvider.class...
processing com/google/vr/cardboard/VrParamsProviderFactory.class...
processing com/google/vr/cardboard/VrParamsProviderFactory$ContentProviderClientHandle.class...
processing com/google/vr/cardboard/VrParamsProviderJni.class...
processing com/google/vr/cardboard/VrSettingsProviderContract.class...
processing com/google/vr/cardboard/annotations/UsedByNative.class...
processing com/google/vr/cardboard/annotations/UsedByReflection.class...
processing com/google/vr/internal/controller/NativeCallbacks.class...
processing com/google/vr/internal/controller/ServiceBridge.class...
processing com/google/vr/internal/controller/ServiceBridge$1.class...
processing com/google/vr/internal/controller/ServiceBridge$2.class...
processing com/google/vr/internal/controller/ServiceBridge$3.class...
processing com/google/vr/internal/controller/ServiceBridge$Callbacks.class...
processing com/google/vr/ndk/base/AndroidCompat.class...
processing com/google/vr/ndk/base/BufferSpec.class...
processing com/google/vr/ndk/base/BufferSpec$ColorFormat.class...
processing com/google/vr/ndk/base/BufferSpec$DepthStencilFormat.class...
processing com/google/vr/ndk/base/BufferViewport.class...
processing com/google/vr/ndk/base/BufferViewport$EyeType.class...
processing com/google/vr/ndk/base/BufferViewport$Reprojection.class...
processing com/google/vr/ndk/base/BufferViewportList.class...
processing com/google/vr/ndk/base/BuildConstants.class...
processing com/google/vr/ndk/base/BuildFlags.class...
processing com/google/vr/ndk/base/CardboardEmulator.class...<message truncated>

I have been looking for info and I have found that the problem is that those files are duplicated in some librarys:
Lcom/google/common/logging/nano/Vr$VREvent;
Lcom/google/common/logging/nano/Vr$VREvent$Application;
Lcom/google/common/logging/nano/Vr$VREvent$AudioStats;
Lcom/google/common/logging/nano/Vr$VREvent$Cyclops;
Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$Capture;
Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$Share;
Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$ShareStart;
Lcom/google/common/logging/nano/Vr$VREvent$Cyclops$View;
Lcom/google/common/logging/nano/Vr$VREvent$DoublePrecisionTransform;

I've tried to open the duplicated classes into the .jar files and do a new .jar. The point is that the error continues appearing and when I go to the .jar files that I've created they have the deleted classes. I don't know if they are being overwritten by other program or I'm doing it badly but I'll love if someone could help me because I'm really frustrated at this moment.


text:
Q: Writing middle tier tests for website built using Struts I have never done any middle tier testing before and I am brand new to Struts. I was assigned the task to find out if it is possible to do middle tier testing of a Struts website and how to do it if it is. I wonder if anyone has experience writing middle tier tests for a website built using the Java Struts framework. If you do, 1) do you find it difficult to do so/would you recommend to just test the website in the UI level? 2) do you have recommendation of any websites or books I should go to/read to learn how to do so?
In case it helps, the website is using tiles in the UI and hibernate.

A: First of all, it does not matter what frontend technology you are using, if you want to test your middle tier. It more depends on your system's architecture, e.g. it will be hard to test separately when all your business logic is implemented in Struts Actions.
Please check out Uncle Bob's article "The Test Bus Imperative", where he explains how your applications should be structured to enable middle tier testing.
Furthermore, read Michael Cohn's blog entry about the Testing Pyramid, which should give you a hint of how to structure your automated tests. There you will see to create GUI based tests, but also that those should not be the majority. Additionally, you can get some information about GUI testing here.
So, first locate your actual business logic and than verify how hard it is to test it separately (without clicking around at the GUI). If that is not possible you probably should stick with GUI tests, using e.g. Selenium. Here are some guidelines for doing so without shooting yourself in the foot :)


text:
Q: Absolute positionning: New Flexbox behavior in Chrome 53 I noticed a difference between Firefox and Chrome (from V53) with absolute positioning in a flex container
Chrome 53 act like we are using a left: 0; on the element.
Instead, the element should be positioned after the previous elements.

body { background-color: #252525; color: #eee; }

.container { width: 100%; display: flex; flex-flow: row nowrap; background-color: grey; }

.static-content,
.absolute-content { display: flex; }

.static-content { flex: 0 0 auto; }
.absolute-content { flex: 1; background-color: tomato; position: absolute; }
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

Test

        Hello world!

        Yo!

How can i keep the Firefox behavior in the new version of Chrome?
Thanks!

A: It works with an extra container.

body { background-color: #252525; color: #eee; }

.container { width: 100%; display: flex; flex-flow: row nowrap; background-color: grey; }

.static-content,
.extra-container,
.absolute-content { display: flex; }

.static-content { flex: 0 0 auto; }
.absolute-content { flex: 1; background-color: tomato; position: absolute; }
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

Test

        Hello world!

          Yo!


text:
Q: Bluetooth Low Energy signal processing prioritization in a crowded space How do Androids prioritize incoming Bluetooth 4.0 messages when there are a lot of signals in a specific location? When there are a lot of beacon messages in an area (a crowd wearing Fitbit devices etc.), Android appears to process some incoming ble messages based on a certain criteria, and ignore the rest. This appears to be prioritized at a lower level than the Android development framework gives us access to. Running various tests with amplified beacon signals in a crowded space, iPhones don't appear to act in the same manner.

A: I suspect the differences in behavior are based on the BLE chipset implementation and not necessarily by any conscious design let alone BLE specification.  You will likely find that the behavior differs even between iOS device models (with different chipsets) and most certainly between the much more fragmented  different Android models.
Any practically useful answer to this question is likely to be based on specific test conditions on specific device models rather than a definitive generalized answer.
Admittedly this is all conjecture based on lots of testing I have done.  I offer it only in the absence of  better and more specific answers from others.

A: There is no "prioritization" as far as I can tell. The Bluetooth chips simply forward what they snap up on the air while they scan to the host.
What you need to keep in mind is the advertising interval. A device that sends out an advertisement more often than another is of course more likely to be detected. Also, if two devices send out an advertisement packet at the exact same moment and the signal strengths are equal, I guess the receiver will just get garbage and drop the packet.
Note that Android uses "active scanning", which means it waits for both the advertising packet and the scan response packet before the app gets notified. To get the scan response packet it must send a scan request immediately after it received the advertising packet, and immediately after that the advertiser sends the scan response packet. Now the standard defines a backoff mechanism if this fails which might be implemented differently in different controllers, hence the biggest differences for different controllers are probably due to this.


text:
Q: debugging stl containers using mingw, issue with python script edit:
ok, i wont give up.
i tried to set this up in codeblocks, but that doesnt work well either:
Starting debugger: C:\MinGW\bin\gdb-python27.exe -nx -fullname  -quiet
done
Setting breakpoints
Attaching to program with pid: 7760
Debugger name and version: GNU gdb (GDB) 7.5
Attaching to process 7760
> source C:\MinGW\bin\.gdbinit
Traceback (most recent call last):
  File "<string>", line 5, in <module>
  File "C:\MinGW\share\gcc-4.8.1\python\libstdcxx\v6\printers.py", line 917, in register_libstdcxx_printers
    register_type_printers(obj)
  File "C:\MinGW\share\gcc-4.8.1\python\libstdcxx\v6\printers.py", line 855, in register_type_printers
    add_one_type_printer(obj, 'basic_string', pfx + 'string')
  File "C:\MinGW\share\gcc-4.8.1\python\libstdcxx\v6\printers.py", line 846, in add_one_type_printer
    gdb.types.register_type_printer(obj, printer)
  File "c:\mingw\share\gdb/python\gdb\types.py", line 179, in register_type_printer
    locus.type_printers.insert(0, printer)
AttributeError: 'module' object has no attribute 'type_printers'
C:\MinGW\bin\.gdbinit:7: Error in sourced command file:
Error while executing Python code.
Error while executing Python code.
> python print sys.version
2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)]
> show version
GNU gdb (GDB) 7.5
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-pc-mingw32".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Debugger name and version: GNU gdb (GDB) 7.5

so it looks as if this has nothing to do with eclipse messing things up, but the script misbehaving.

edit:
i just fired up msys, navigated to the same path eclipse suposedly does (2-environment-cd D:/work/ludum-dare/Debug), set the same parameters (except 5-enable-pretty-printing since gdb-python doesnt seem to know that setting) and finally sourced .gdbinit It didnt even wince at doing that. no errors at all.
does anyone know how to find out what eclipse is trying to run when i click on debug?
Also i just tried the "standard create process launcher" which at first went smoothly, but scrolling up in the traces console, i saw it simply skips over the errors encountered in the python file.

edit: i just realized that not setting 5-enable-pretty-printing doesnt set _use_gdb_pp in printers.py, so it wont run the same way as in eclipse anyhow.
I guess pretty printing is broken in mingw+eclipse cdt

after following these steps: https://stackoverflow.com/a/14266862/3239702
i am facing the following output in eclipse:
610,711 2-environment-cd D:/work/ludum-dare/Debug
610,715 2^done
610,715 (gdb)
610,716 3-gdb-set breakpoint pending on
610,725 3^done
610,725 (gdb)
610,726 4-gdb-set detach-on-fork on
610,735 4^done
610,735 (gdb)
610,736 5-enable-pretty-printing
610,745 5^done
610,745 (gdb)
610,746 6-gdb-set python print-stack none
610,755 6^done
610,755 (gdb)
610,756 7-gdb-set print object on
610,765 7^done
610,765 (gdb)
610,766 8-gdb-set print sevenbit-strings on
610,775 8^done
610,775 (gdb)
610,776 9-gdb-set host-charset UTF-8
610,785 9^done
610,785 (gdb)
610,786 10-gdb-set target-charset WINDOWS-1252
610,795 10^done
610,795 (gdb)
610,795 11-gdb-set target-wide-charset UTF-16
610,805 11^done
610,805 (gdb)
610,822 12source D:\work\ludum-dare\.gdbinit
610,825 &"source D:\\work\\ludum-dare\\.gdbinit\n"
610,896 &"Traceback (most recent call last):\n"
610,896 &"  File \"<string>\", line 4, in <module>\n"
610,896 &"  File \"C:/MinGW/share/gcc-4.8.1/python\\libstdcxx\\v6\\printers.py\", line 917, in regis\
ter_libstdcxx_printers\n"
610,915 &"    register_type_printers(obj)\n"
610,915 &"  File \"C:/MinGW/share/gcc-4.8.1/python\\libstdcxx\\v6\\printers.py\", line 855, in regis\
ter_type_printers\n"
610,917 &"    add_one_type_printer(obj, 'basic_string', pfx + 'string')\n"
610,917 &"  File \"C:/MinGW/share/gcc-4.8.1/python\\libstdcxx\\v6\\printers.py\", line 846, in add_o\
ne_type_printer\n"
610,918 &"    gdb.types.register_type_printer(obj, printer)\n"
610,918 &"  File \"c:\\mingw\\share\\gdb/python\\gdb\\types.py\", line 176, in register_type_printer\
\n"
610,928 &"    locus.type_printers.insert(0, printer)\n"
610,928 &"AttributeError: 'module' object has no attribute 'type_printers'\n"
610,928 &"D:\\work\\ludum-dare\\.gdbinit:6: Error in sourced command file:\n"
610,928 &"Error while executing Python code.\n"
610,928 12^error,msg="D:\\work\\ludum-dare\\.gdbinit:6: Error in sourced command file:\nError while \
executing Python code."
610,929 (gdb)

i have searched the web for other people who have this problem but it looks like i got the jackpot. i got:
Eclipse IDE for C/C++ Developers
Version: Kepler Service Release 1
Build id: 20130919-0819

my mingw installer is all updated, and gdb-python27 is installed from:
gdb-python-7.5.1-mingw32-bin.tar.lzma

python 2.7.6 32bit
User Environment Variables:
PYTHONHOME = C:\Python27
PYTHONPATH = C:\Python27\Lib
PATH = c:\mingw\bin

Global Environment Variables:
contains much more, i only post the relevant part:
PATH = C:\Python27\;

edit:
i just tried the python scripts from svn ( svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python ) of course i changed the path in my .gdbinit accordingly.
the output in the "gdb traces" console is mostly the same, except for a couple of line numbers which differ, but the errors in those lines are identical, so i supose there just was some refactoring or something like that going on.
and also my .gdbinit file as it is now. before the svn checkout, the commented line was used instead of line 4:
python
import sys
# sys.path.insert(0, 'C:/MinGW/share/gcc-4.8.1/python')
sys.path.insert(0, 'D:/work/libstdc++-v3/python')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end

edit:
tried to debug that printers.py script:
i added some prints to the register_libstdcxx_printers function:
def register_libstdcxx_printers (obj):
    "Register libstdc++ pretty-printers with objfile Obj."
    global _use_gdb_pp
    global libstdcxx_printer
    print("initialy obj: " + str(obj))
    print("_use_gdb_pp: " + str(_use_gdb_pp))
    if _use_gdb_pp:
        gdb.printing.register_pretty_printer(obj, libstdcxx_printer)
    else:
        if obj is None:
            obj = gdb
        obj.pretty_printers.append(libstdcxx_printer)
    print("after gdb.printing.register_pretty_printer(obj, libstdcxx_printer): obj: " + str(obj))
    register_type_printers(obj)

the output of this is:
559,740 ~"initialy obj: None\n"
559,740 ~"_use_gdb_pp: True\n"
559,740 ~"after gdb.printing.register_pretty_printer(obj, libstdcxx_printer): obj: None\n"

i cant really blame it to not find the attribute 'type_printers' on None, now can i?
i suppose that None comes from line 6 in my .gdbinit :
register_libstdcxx_printers (None)

A: MinGW GDB 7.5.1 uses Python Scripts from normal GDB 7.6. Therefore the Scripts fail.
After i copied the syscalls and python folders out of
http://ftp.gnu.org/gnu/gdb/gdb-7.5.1.tar.gz
and tried everything again, it miraculously worked.
Starting debugger: C:\MinGW\bin\gdb-python27.exe -nx -fullname  -quiet
done
Setting breakpoints
Attaching to program with pid: 7428
Debugger name and version: GNU gdb (GDB) 7.5
Attaching to process 7428
Continuing...
At D:\work\ludum-dare\src\main.cpp:39
Continuing...
At D:\work\ludum-dare\src\main.cpp:41
Continuing...
At D:\work\ludum-dare\src\componentEntitySystem\componentEntitySystem.cpp:393
> print funcText
$1 = {static npos = <optimized out>, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x24504f4 "'ces:getEntitiesWithComponent(\"position\")'"}}
> source C:\MingW\bin\.gdbinit
> print funcText
$2 = "'ces:getEntitiesWithComponent(\"position\")'"

So, "nice job" to the person who put the gdb 7.6 python scripts into the MinGW GDB 7.5.1 package. NOT.


text:
Q: How to change the lower case to upper case with conditional specific string in python I have some text in dataframes, in which I want some specific fruits in upper case. The text is like below
input is
one apple
two oranges
three bananas
an apple

and
the output required is
one Apple
two Oranges
three Bananas
an Apple

The loop I can give condition if array / string / list have any word "one", "two", "three", and "an" (conditional when these ... any words are in string), after this word, change next followed word first letter lower case to upper case.
If any hint or help.
5 lines data
+++++++++++++++++++++++++++++++++++++++++++++++++++
ID Reference_time Comment
0 0059 one apple box
1 0156 five oranges left
2 1859 an engineer handling issue
3 1555 two persons have eaten, three still hungry
4 2109 an apple carton is still in stock

+++++++++++++++++++++++++++++++++++++++++++++++++++

A: Probably better ways to do this with regex, but this should work using .str.extract
only downside will be is that if you have multiple matches in a single string you'll need to handle/edit the regex.
repl = ['one','two','three','five','an']
pat = '|'.join(repl)

s = df["comment"].str.extract(rf"({pat})(.*\w.*$)")

s[1] = s[1].str.strip().str.capitalize()
df['comment_new'] = s.stack().groupby(level=0).agg(' '.join)

print(df[['comment_new','comment']])

                                  comment_new  \
0                               one Apple box
1                           five Oranges left
2                  an Engineer handling issue
3  two Persons have eaten, three still hungry
4           an Apple carton is still in stock

                                      comment
0                               one apple box
1                           five oranges left
2                  an engineer handling issue
3  two persons have eaten, three still hungry
4           an apple carton is still in stock

A: keywords = ['one', 'two', 'three', 'an']

df['Comment'] = df['Comment'].apply(lambda x: toUpper(keywords, x))

def toUpper(keywords, sentence):
  word_list = sentence.split()
  for i in range(len(word_list)-1):
    if word_list[i] in keywords:
        word_list[i+1] = word_list[i+1].capitalize()

  return ' '.join(word_list)


text:
Q: Keep formatting from being stripped from JSON in Angular from Firebase I have an application connected to Firebase and displayed with an ng-repeat, see code below.  The connection works and displays, but the description item has a \n inline to create separate paragraphs, which unfortunately is being stripped out and the paragraphs simple print to page as one big paragraph.  I am currently using Angular 1.3.8.  I've tried ngSanitize and its either not working or I am using it incorrectly.  Any help is greatly appreciated.  Thank you.

        {{ m.company }}

{{ m.address }}

{{ m.address2 }}

{{ m.url }}

{{ m.name }}

{{ m.title }}

{{ m.phone }}

{{ m.email }}

        {{ m.description }}

A: HTML ignores line breaks when it comes to formatting. You would need to either replace the line breaks with
 elements or set white-space to pre, pre-wrap or pre-line in your CSS.
Try editing the description part like this:
HTML:
{{ m.description }}

CSS:
.description {
  white-space: pre-line;
}

This will keep any line breaks in m.description in the HTML formatting.

A: You can simply remove the extra characters using, let's call it trim in your HTML:
{{ trim(m.description) }}

And code:
$scope.trim = function(text) {
  return text.replace(/\n/g, ' ');
};


text:
Q: How to remove rows with certain values I want to remove the rows that contain "New York" in city column. I have written the following:
     mydata=mydata[(mydata['city'] != ' New York')

When I query like below, I do not get any rows back (I checked for different white space variations too)
    mydata[(mydata['city'] == ' New York')

But when I use extra trees, New York is present in the figure...
1- What could be causing this?
2- How can I remove all variations of New York (like ' New York', 'New York ', 'New York')

A: Use Series.str.strip and change tested value with no trailing space:
mydata=mydata[(mydata['city'].str.strip() != 'New York') ]


text:
Q: How do you center image inside square aspect ratio and maintain responsiveness? I'm creating a product grid for a client and was faced with the issue of properly centering a dynamic thumbnail (sometimes square, portrait, or landscape) in a square aspect ratio and maintaining responsiveness.
I am currently doing the following but was wondering if there was a more clean css solution for centering an image (vertically/horizontally) inside of a div much like you would with a background image on a responsive div with background-size: contain.

.thumbnails {
  margin: auto;
  width: 250px;
}

.thumbnail {
  position: relative;
  margin: 1rem;
  padding-bottom: 100% ;
  border: 1px solid gray;
}

.thumbnail__img {
  position: absolute;
  max-width: 100% ;
  max-height: 100% ;
  width: auto;
  height: auto;
  left: 50% ;
  top: 50% ;
  transform: translate(-50% , -50% );
}

Demo JSFiddle

A: Here's an alternative using object-fit: contain;.
This way there is no need to use transform and meddle with left/top.

.thumbnails{
  width: 250px;
}

.thumbnail{
  position: relative;
  margin: 1rem;
  padding-bottom: 100%;
  border: 1px solid gray;
}

.thumbnail__img{
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block; // important since images have default inline-block property
}


text:
Q: How to fix EntityValidationError on new user registration? I created a new project with individual user accounts and added 2 properties (Display Name and Username(in code DisplayName/LoginUsername)), while DisplayName didn't give me any problems, LoginUsername was apparently a problem for the program.
I've tried to add it to migration, I tried to do it without LoginUsername which worked but is not what I intended and I've tried searching online to no avail.
The part with the Error is
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.LoginUsername, Email = model.Email, DisplayName = model.DisplayName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            return View(model);
        }

My RegisterViewModel includes
    public class RegisterViewModel
    {
        [Required]
        [Display(Name = "Display name")]
        public string DisplayName { get; set; }

        [Required]
        [Display(Name = "Username")]
        public string LoginUsername { get; set; }

        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

I don't which information is still missing, please tell me what else is necessary to add here.
What I wanted was for the registration to include an actual username instead of just the Email, which would also be used for login. Instead I got the error message.
Help would be greatly appreciated. :)
SOLVED: I didn't use the standard UserName provided by IdentityFramework and the app couldn't fill both username props with data, but since they were both required it was unable to save the account. So I accidentally made a unnecessary second property.


text:
Q: How to restore accidentally deleted kdesu Trying to create a link to kdesu with:
ln -s /usr/bin/kdesu /usr/lib64/kde4/libexec/kdesu

I ended up without kdesu (I might have interchanged source and destination, not sure). Which is the package to reinstall kdesu? I can't find it. I'm using Mageia, but it should be similar in different distros.

A: Mageia uses rpm for package management, so use the following command to find which package contains the file /usr/bin/kdesu:
rpm -qf /usr/bin/kdesu

And to reinstall the program (use the right package names, I don't have Mageia to check):
urpmi --replacepkgs libkdesu5 kdebase4-runtime

A: In Fedora 20 it's in this package:
$ repoquery -ql kde-runtime-0:4.13.3-3.fc20.x86_64 | grep kdesu
/usr/bin/kdesu
/usr/libexec/kde4/kdesu
/usr/libexec/kde4/kdesud

I found this out by querying the YUM repositories that I have on my system, looking for a package that contained a file */bin/kdesu.
$ repoquery -qf */bin/kdesu
kde-runtime-0:4.13.3-3.fc20.x86_64
kde-runtime-0:4.11.3-2.fc20.i686
kde-runtime-0:4.13.3-3.fc20.i686
kde-runtime-0:4.11.3-2.fc20.x86_64


text:
Q: Difference between int, NSInteger and NSUInteger What is the main difference between int, NSInteger and NSUInteger in Objective-C?
Which one is better to use in an application and why?

A: In such cases you might right click and go to definition:
#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

A: The difference is for abstract types and their associates sized from  hardware. In a manner that now we don't have to worry about what size an int is or how big it's pointer is on any particular hardware.
"C" is bad at this, only stating that a long is at least as big as an int, that an int is the "natural" integer size of the hardware (whatever that means), that an int is at least as long as a short--a (big mess).
This seemed like a good idea at the time coming from Fortran, but did not age well.
One could use the POSIX defines, things like uint32_t, int16_t, etc. But this does not address how big a pointer needs to be on any particular hardware either.
So, if Apple defines the return type to be an NSUInteger you just use that and you don't need to know if it is 16, 32 or 64 bits in size for your particular hardware.  (I picked those values out-of-the-air just for an example).
As you can see in @Bastian the actual size depends on hardware.
The documentation answers the "letter of the question" but does not provide an understanding of "why"?


text:
Q: Creating a new date variable from several existing variables For the following data set (a small portion of a large data set), I want to create a variable called "DATE", which will use the information from the variables "fyr" and "fyearq". Actually, the variable "fyr" indicates the month - e.g., 5 means May and 10 means October. The variable "fyearq" indicates the year corresponding to that month. Now the new variable "DATE" will be like (for the first observation) 1968-5-31, meaning that in addition to using the data from the two variables "fyr" and "fyearq", it will add the LAST DAY of the corresponding month. Basically, I want to create the variable because eventually using the "DATE" variable and "rdq" variable, I will create another variable called "DIFF", which is actually the number of days between these two dates variables (variable "DATE" and variable "rdq"). I know the package lubridate is excellent for dealing with the date problems, but am not sure how to use it.
  fyr  fyearq  tic        rdq
1    5   1968  AIR       <NA>
2    5   1969  AIR       <NA>
3    5   1970  AIR       <NA>
4    5   1971  AIR       <NA>
5    5   1972  AIR 1973-07-23
6    5   1973  AIR 1974-07-06
7    5   1974  AIR 1975-07-18
8    5   1975  AIR 1976-07-15
9    5   1976  AIR 1977-07-20
10   5   1977  AIR 1978-06-29
11   5   1978  AIR 1979-07-16
12   5   1979  AIR 1980-07-14
13   5   1980  AIR 1981-07-20
14   5   1981  AIR 1982-07-22
15   5   1982  AIR 1983-07-28
16   5   1983  AIR 1984-07-26
17   5   1984  AIR 1985-07-24
18   5   1985  AIR 1986-07-08
19   5   1986  AIR 1987-07-14
20   5   1987  AIR 1988-07-20
21   5   1988  AIR 1989-07-18
22   5   1989  AIR 1990-06-20
23   5   1990  AIR 1991-06-20
24   5   1991  AIR 1992-06-19
25   5   1992  AIR 1993-07-14
26   5   1993  AIR 1994-07-06
27   5   1994  AIR 1995-07-06
28   5   1995  AIR 1996-07-01
29   5   1996  AIR 1997-06-25
30   5   1997  AIR 1998-06-25
31   5   1998  AIR 1999-06-24
32   5   1999  AIR 2000-06-28
33   5   2000  AIR 2001-06-28
34   5   2001  AIR 2002-08-26
35   5   2002  AIR 2003-07-03
36   5   2003  AIR 2004-06-29
37   5   2004  AIR 2005-07-13
38   5   2005  AIR 2006-07-12
39   5   2006  AIR 2007-07-11
40   5   2007  AIR 2008-07-09
41   5   2008  AIR 2009-07-14
42   5   2009  AIR 2010-07-13
43   5   2010  AIR 2011-07-06
44   5   2011  AIR 2012-07-17
45   5   2012  AIR 2013-07-25
46   5   2013  AIR 2014-07-15
47   5   2016  AIR 2017-07-11
48   5   2014  AIR 2015-07-13
49   5   2015  AIR 2016-07-12
50   5   2017  AIR 2018-07-10
51  10   1982 ABSI       <NA>
52  10   1983 ABSI       <NA>
53  10   1984 ABSI 1984-12-20
54  10   1985 ABSI       <NA>
55  10   1986 ABSI 1986-11-18
56  10   1987 ABSI       <NA>
57  10   1988 ABSI 1988-11-22
58  10   1989 ABSI 1989-11-22
59  10   1990 ABSI 1990-11-29
60  10   1991 ABSI 1991-11-21
61  10   1992 ABSI 1992-11-30
62  10   1993 ABSI 1993-11-26
63  10   1994 ABSI 1994-11-29

A: Base R should be sufficient in this case. We can increment fyr and then wrap it in as.Date to get first date of next month and subtract - 1 to get last date of current month.
as.Date(paste(df$fyearq, df$fyr + 1, "01"), "%Y %m %d") - 1
#[1] "1968-05-31" "1969-05-31" "1970-05-31" "1971-05-31" "1972-05-31"....

If you have don't want to specify format explicitly you can use lubridate with same logic
lubridate::ymd(paste(df$fyearq, df$fyr  + 1, "01")) - 1

Logic of answer inspired from @thelatemail's comment.

A: We can use base R methods with sprintf
as.Date(do.call(sprintf, c(fmt = "%d-%d-01",
            df[c('fyearq', 'fyr')] + list(0, 1)))) -1
#[1] "1968-05-31" "1969-05-31" "1970-05-31" "1971-05-31" "1972-05-31"  ...

data
df <- structure(list(fyr = c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L), fyearq = c(1968L, 1969L,
1970L, 1971L, 1972L, 1973L, 1974L, 1975L, 1976L, 1977L, 1978L,
1979L, 1980L, 1981L, 1982L, 1983L, 1984L, 1985L, 1986L, 1987L,
1988L, 1989L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L,
1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L,
2006L, 2007L, 2008L, 2009L, 2010L, 2011L, 2012L, 2013L, 2016L,
2014L, 2015L, 2017L, 1982L, 1983L, 1984L, 1985L, 1986L, 1987L,
1988L, 1989L, 1990L, 1991L, 1992L, 1993L, 1994L), tic = c("AIR",
"AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR",
"AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR",
"AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR",
"AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR",
"AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR", "AIR",
"AIR", "AIR", "AIR", "AIR", "ABSI", "ABSI", "ABSI", "ABSI", "ABSI",
"ABSI", "ABSI", "ABSI", "ABSI", "ABSI", "ABSI", "ABSI", "ABSI"
), rdq = c(NA, NA, NA, NA, "1973-07-23", "1974-07-06", "1975-07-18",
"1976-07-15", "1977-07-20", "1978-06-29", "1979-07-16", "1980-07-14",
"1981-07-20", "1982-07-22", "1983-07-28", "1984-07-26", "1985-07-24",
"1986-07-08", "1987-07-14", "1988-07-20", "1989-07-18", "1990-06-20",
"1991-06-20", "1992-06-19", "1993-07-14", "1994-07-06", "1995-07-06",
"1996-07-01", "1997-06-25", "1998-06-25", "1999-06-24", "2000-06-28",
"2001-06-28", "2002-08-26", "2003-07-03", "2004-06-29", "2005-07-13",
"2006-07-12", "2007-07-11", "2008-07-09", "2009-07-14", "2010-07-13",
"2011-07-06", "2012-07-17", "2013-07-25", "2014-07-15", "2017-07-11",
"2015-07-13", "2016-07-12", "2018-07-10", NA, NA, "1984-12-20",
"<NA>", "1986-11-18", NA, "1988-11-22", "1989-11-22", "1990-11-29",
"1991-11-21", "1992-11-30", "1993-11-26", "1994-11-29")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57",
"58", "59", "60", "61", "62", "63"))


text:
Q: Removing plot artifacts (SphericalPlot3D) Using SphericalPlot3D, I find I get two types of artifact:

*

*A discontinuity in the surface reflectance at $\theta=0,2\pi$

*Little edges, or perhaps gaps between faces, showing in some regions — this depends very much on the angle that the object is viewed from. If you run the code below, it might not show it without some rotation.

They can both be seen in this

How do I get rid of them?
Here's the code to reproduce the problem.
GreatCircleDistance[a_, b_] := ArcCos[(a.b)/(Norm[a, 2] Norm[b, 2])]

SphereToCart[{r_, ϕ_, θ_}] = r {Cos[θ] Sin[ϕ], Sin[θ] Sin[ϕ], Cos[ϕ]}

TotalDistance[θ_, ϕ_] :=
  3 +
    Plus @@
      (Exp[-10 GreatCircleDistance[SphereToCart[{1, θ, ϕ}], #]^2] & /@
        (PolyhedronData["Icosahedron", "VertexCoordinates"] // N))

SphericalPlot3D[TotalDistance[θ, ϕ], {θ, 0, π}, {ϕ, 0, 2 π},
  PlotStyle -> Directive[Orange, Opacity[1], Specularity[White, 10]],
  Mesh -> None,
  PlotPoints -> 30]

A: Compute the normal manually (SphericalPlot does it from the polygons:
SphericalPlot3D[
 TotalDistance[θ, ϕ] /. Abs[x_]^2 -> x^2, {θ,
  0, π}, {ϕ, 0, 2 π},
 PlotStyle -> Directive[Orange, Opacity[1], Specularity[White, 10]],
 Mesh -> None, PlotPoints -> 30,
 NormalsFunction -> Function[{x, y, z, θ, ϕ, ρ},
   Evaluate@
    With[{r =
       TotalDistance[θ, ϕ] /. Abs[a_]^2 :> a^2 //
        Simplify},
     Cross @@
      Transpose@
       D[
        r {Sin[θ] Cos[ϕ], Sin[θ] Sin[ϕ],
          Cos[θ]}, {{θ, ϕ}}]
     ]
   ]
 ]


text:
Q: sIFR 3 rev.436 is unable to sucessfully publish movie — the flash file is blank I have been trying to get sIFR 3 rev.436 working on my site but I stuck at publishing the movie.
I did everything the instruction had told me to but when I published the movie and double clicked it to test, it failed. Yhe movie was blank with the following error. Someone said the Action Scripts should be in the same folder as the sifr.fla; it was, but it didn't help at all.
Here's the compiler errors:

Scene=Scene 1, layer=code, frame=1, Line 19
  The class or interface 'sIFR' could not be loaded.

I was puzzled and after hours of looping in the situation I downloaded rev.432 and tested it out. To my delight, everything turned out right and I published the movie successfully!
But sadly I installed re.436 in Wordpress and it wouldn't display.
Is there anyway I can solve this?

A: Problems solved.
Might be useful for this thread too.
sIFR 3 r4.36 has problem with Flash 8

*

*Locate to your sIFR Action Scripts. Edit with a text editor. Change the encoding from UTF-8 to ANSI.

*You are done.
Glad I found the way.


text:
Q: Eliminate horizontal white space between elements I'm new to the html/css world and learning as I go, designing a simple web site for my business (no Flash, no e-commerce, just information -- SIMPLE!).  This may be a pretty basic question -- I rather hope it is -- but I can't find it addressed in any number of forums.  In fact, most people who are asking are trying to do the opposite.
I'm specifying XHTML for the page, and using an HTML table (I know, I know, but I'm still trying to get my hands around CSS divs, and I expect the problem might not go away, anyway).  I have one row with a light gray background.  In the second row, the 1st cell has an orange background.  Between the two are two pixels of white, so the colors don't touch.  I have margins, borders, and padding all set to 0, and nothing I do gets rid of these white rows.  Aside from the settings mentioned, I've also tried setting a solid border, which had no effect.  This is happening in both Firefox 3.6 and IE 8.
To sum up the question:

*

*Is this a function of using tables?

*If so (or even if not), will using DIVs resolve the issue, once I figure them out?

*Am I overlooking some other solution?
I'm looking to do this strictly with html and css, no other languages.  I've been working with computers for over 30 years, but the last programming I did in earnest was in FORTRAN 77 and I haven't worked much with 3GL or 4GL languages (a tiny bit of PERL, some scripting languages in test tools, I'm quite knowledgeable in UNIX scripts, and I can read but not write VB and the C family).

A: Same as cellspacing=0 just css:
table {
    border-collapse: collapse
}

And the cellpadding=0 is:
table td, table th {
    padding: 0;
}

Just for you to see the CSS approach too :)

A: You need to make the html for the table look like this:
<table cellspacing="0" cellpadding="0">

But you REALLY should do divs. They are far superior AND they will solve your problem.

A: Sounds like it might be a cell padding or cell spacing issue.  Try this documentation.  It also provides a quick method for checking html.


text:
Q: Probability: Median of a Difference Let $Y_1, Y_2, ...$ be random variables and $b_n$ be such that $0 < b_n \uparrow \infty$. Suppose that $\frac{Y_n}{b_n} \stackrel{p}{\to} 0$ (where $\stackrel{p}{\to}$ denotes convergence in probability). I am to show
$ \displaystyle
\frac{\max_{1 \le j \le n} |m(Y_j - Y_n)|}{b_n} \to 0 \qquad (n \to \infty)
$
where $m(\cdot)$ denotes a median of its argument.
I am embarrassingly clueless (in general I seem to have problems converting statements involving medians into useful bounds). All I know about the result is that it is used in a proof of Feller's Weak Law of Large Numbers.
Thanks.

A: The missing clue you ask for might be that:

For every random variable $Z$ and positive real number $z$, if $P(|Z|\ge z)\le\frac13$ then $|m(Z)|\le z$.

This follows directly from the definition of the median. In the context of your question, using the inclusion
$$
[\,|Y_j-Y_n|\ge2ub_n\,]\subseteq [\,|Y_j|\ge ub_n\,]\cup[\,|Y_n|\ge ub_n\,],
$$
which implies the inequality
$$
P(|Y_j-Y_n|\ge2ub_n)\le P(|Y_j|\ge ub_n)+P(|Y_n|\ge ub_n),
$$
a consequence of the missing clue is that it is enough to prove that:

(0) For every positive real number $u$, there exists a finite integer $N$ such that for every $n\ge N$ and every $j\le n$, $P(|Y_j|\ge ub_n)\le\frac16$ and $P(|Y_n|\ge ub_n)\le\frac16$.

We now prove (0). Fix a positive real number $u$.
First, when $n\to+\infty$, $P(|Y_n|\ge ub_n)\to0$, hence there exists a finite $K$ such that:
$\qquad$(i) for every $n\ge K$, $P(|Y_n|\ge ub_n)\le\frac16$.
Second, for each $j\le K$, $P(|Y_j|\ge ub_n)\to0$ when $n\to+\infty$ because $b_n\to\infty$, hence there exists a finite $M_j$ such that:
$\qquad$(ii) for every $n\ge M_j$, $P(|Y_j|\ge ub_n)\le\frac16$.
Choose finally $N\ge K$ such that $N\ge M_j$ for every $j\le K$. Assume that $n\ge N$ and that $j\le n$.

*
*Using (i), one sees that $P(|Y_n|\ge ub_n)\le\frac16$ because $n\ge K$.

*
If $j\le K$, using (ii), one sees that $P(|Y_j|\ge ub_n)\le\frac16$ because $n\ge M_j$.

*
If $j\ge K$, using (i) once again, one sees that $P(|Y_j|\ge ub_n)\le P(|Y_j|\ge ub_j)\le\frac16$ because $b_j\le b_n$.

Hence the proof of (0) is complete.

A: How could you compute the median of a number?
The problem is solved by using inequalities: you show that your thesis is greater or equal than zero, and lesser or equal than something that converge in probability to 0.
Anyhow I cant help you since I don't understand what is the median of a number. You need at least 3 numbers to compute a nontrivial median.
Edit, possible solution:
$ \displaystyle
 \max_{1 \le j \le n} |Y_j - Y_n| \le \max_{1 \le j \le n} |Y_j| =  |Y_*|
$
$ \displaystyle
0 \le \frac{ m ( \max_{1 \le j \le n} |Y_j - Y_n|)}{b_n} \le

\frac{ m ( Y_* )}{b_n}

$
Now if $m(Y_*)$ is a real number, then you're set.
This is just a sketch. If you want to make this proof more consistent take the definition of convergence:
definition
And apply it to your problem, which I think is the task your professor wants you to do.


text:
Q: How to bring back "Add to home" banner for progressive web app after removed the icon from home screen? The reason - I made a Progressive web app, opened in the browser - all is fine and browser offered me to add it to home screen.
Now, I want to demonstrate this on a presentation, and so - removed the icon from home screen. But for the last whole day I've been playing with the website in chrome a lot, and the banner never appears back.
Is it really a once-in-a-lifetime thing? Or is there something specific I need to do?

A: I found another solution - when I go to the settings of chrome mobile and choose History -> Clear browsing data (make sure that the option to clear Cookies is ticked) then click the Clear Data button - after that I get again the app install banner to add the app to the home screen.
Apparently - it clears not only the data itself, but also makes the browser forget everything about this website.
(Strangely - the old icon doesn't go away ... so now I have a few icons on the home screen :D ...)

A: The app-install banner prompt is normally presented after you've visited the site at least twice with at least 5 minutes between each visit. Using a Chrome flag, you can bypass these checks so that the banner always appears on every visit:

*

*Open Android Chrome.

*Go to chrome://flags/#bypass-app-banner-engagement-checks

*Click Enable

*Click Relaunch Now
You can also simulate an Add To Homescreen event from Chrome DevTools:

*

*Open Android Chrome on your phone, and navigate to a PWA (e.g., the Paper Planes app from https://paperplanes.world).

*Connect to your Android with a USB cable.

*From desktop Chrome DevTools, select Menu > More Tools > Remote Devices. OR CTRLSHIFTP (or CMDSHIFTP for macOS), and enter "Remote devices".

*Select your phone by name.

*Click the Inspect button next to the list item corresponding to your PWA (e.g., Paper Planes).

*In the new DevTools pop-up for your PWA, go to the Application panel, and click Add to homescreen. This should cause the app-install banner to appear in Android Chrome. Note the banner won't appear in the Chrome DevTools screen mirror.

(steps above verified with Chrome 55 on macOS Sierra, and Android Chrome 57)


text:
Q: remove extra price from dropdown in configurable product please see here
how to remove that from drop-down?
while at the same time if we choose this option the original price will change as well.

A: in order to remove that additional price entirely you have to over write functionality of below script:
/app/code/core/Mage/Catalog/Block/Product/View/Options/Type/Select.php
GO to line number : 70 and change the code with this code snippet :
From :
$select->addOption(
            $_value->getOptionTypeId(),
            $_value->getTitle() . ' ' . $priceStr . '',
            array('price' => $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false))
        );

To :
$select->addOption(
            $_value->getOptionTypeId(),
            $_value->getTitle() /*. ' ' . $priceStr . ''*/,
            array('price' => $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false))
        );

you will find workaround this block, hope it will help

A: I registered just to say thank you to Naveed. I was going to just add a comment on their post, but I can't as a new user. So to anyone wanting the correct answer, his answer is correct except there is a space in his code causing it to not work.
$select->addOption(
        $_value->getOptionTypeId(),
        $_value->getTitle() /*. ' ' . $priceStr . ''*/,
        array('price' => $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false))
    );

Should be
$select->addOption(
        $_value->getOptionTypeId(),
        $_value->getTitle()/*. ' ' . $priceStr . ''*/,
        array('price' => $this->helper('core')->currencyByStore($_value->getPrice(true), $store, false))
    );


text:
Q: Algorithm for generating random numbers from a discrete distribution?
Design a fast algorithm to repeatedly generate numbers from the
  discrete distribution: Given an array a[] of non negative real numbers
  that sum to 1, the goal is to return index i with probability a[i]

I found this question in a an online algorithm book, Introduction to Programming in Java, chapter 4.2: Sorting and Searching (http://introcs.cs.princeton.edu/java/42sort/) .
the hint says:

Form an array s[] of cumulated sums such that s[i] is the sum of the first i elements of a[]. Now, generate a random real number r between 0 and 1, and use binary search to return the index i for which s[i] ≤ s[i+1].

some how I am not able to understand the hint and hence cant find the solution..

A: There are many ways to answer this problem.  This article describes numerous approaches, their strengths, their weaknesses, and their runtimes.  It concludes with an algorithm that takes O(n) preprocessing time, then generates numbers in time O(1) each.
The particular approach you're looking for is described under "roulette wheel selection."
Hope this helps!

A: Here's a Python algorithm which implements the 'Roulette Wheel' Technique. It's tough to explain without a graphic. The article linked to by templatetypedef should do well for that. Also, note that this algorithm doesn't actually require the weights to be normalized (they don't need to sum to 1), but this will work nonetheless.
import random

trials = 50
selected_indices = []

# weights on each index
distrib = [0.1, 0.4, 0.2, 0.3]

index = random.randrange(0, len(distrib) - 1)
max_weight = max(distrib)
B = 0
# generate 'trials' random indices
for i in range (trials):

    # increase B by a factor which is
    # guaranteed to be much larger than our largest weight
    B = B + random.uniform(0, 2 * max_weight)

    # continue stepping through wheel until B lands 'within' a weight
    while(B > distrib[index]):
        B = B - distrib[index]
        index = (index + 1) % len(distrib)
    selected_indices.append(index)

print("Randomly selected indices from {0} trials".format(trials))
print(selected_indices)

A: This is a snippet from wakkerbot/megahal. Here the weights are (unsigned) ints, and their sum is in node->childsum. For maximum speed, the children are sorted (more or less) in descending order. (the weights are expected to have a power-law like distribution, with only a few high weights and many smaller ones)
    /*
     *          Choose a symbol at random from this context.
     *          weighted by ->thevalue
     */
    credit = urnd( node->childsum );
    for(cidx=0; 1; cidx = (cidx+1) % node->branch) {
        symbol = node->children[cidx].ptr->symbol;
        if (credit < node->children[cidx].ptr->thevalue) break;
        /* 20120203 if (node->children[cidx].ptr->thevalue == 0) credit--; */
        credit -= node->children[cidx].ptr->thevalue;
    }
done:
    // fprintf(stderr, "{+%u}", symbol );
    return symbol;

A: Depending on the granularity, you can create an Index with 100, 1000 or 10000 Elements. Assume a distribution (a,b,c,d) with p=(10%, 20%, 30%, 40%), we create a Map:
val prob = Map ('a' -> 10, 'b' -> 20, 'c' -> 30, 'd' -> 40)
val index = (for (e <- prob;
  i <- (1 to e._2)) yield e._1 ).toList

index: List[Char] = List(a, a, a, a, a, a, a, a, a, a,
b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b,
c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c,
d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d, d)

We can now pick an element of desired probability very fast:
val x = index (random.nextInt (100))

x is now by 40% d, by 10% a and so on. Short setup, fast access.
The numbers don't even need to sum up to 100, but you have to calculate the range once, then:
val max = prob.map (_._2).sum
val x = index (random.nextInt (max))


text:
Q: calculate vector between 2 vectors in 3d sphere I have a sphere with known radius $R$ and 2 vectors $\vec a $ and $\vec b$ within this sphere both starting from $(0,0,0)$ and ending on the edges of this sphere so $\left\lVert\vec a \right\rVert = R$ and $\left\lVert\vec b \right\rVert = R$.
The angle between these 2 vectors is $\alpha = 90^o$ but their coordinates are unspecified( known but they can be anywhere in the sphere)
How can I calculate vector $\vec c$ coordinates if this vector also starts at $(0,0,0)$, its length is also equal to spheres radius : $\left\lVert\vec c \right\rVert = R$ , and is somewhere between $\vec a $ and $\vec b$ specified by the known angle of $\beta$ that is an angle between $\vec a$ and $\vec c$ and is $0^o \lt\beta \lt 90^o$

A: If $\vec{c} $ lies between $\vec{a}$ and $\vec{b}$, it lies in the plane spanned by them. So there are $s,t$ so that $\vec{c}=s\vec{a}+t\vec{b}$. If we know the angle between $\vec{c}$ and $\vec{a}$ is $\beta$, we know that
$$ tR^2 = \vec{c} \cdot \vec{a} = R^2\cos{\beta}, $$
so $t=\cos{\beta}$. But then the angle between $\vec{b}$ and $\vec{c}$ is $90^{\circ}-\beta$, so
$$ sR^2 = \vec{c} \cdot \vec{b} = \cos{(90^{\circ}-\beta)} = \sin{\beta}, $$
so
$$ \vec{c} = \vec{a}\cos{\beta}+\vec{b}\sin{\beta}. $$
We can verify that $\vec{c} \cdot \vec{c} = \vec{a} \cdot \vec{a} \cos^2{\beta} + \vec{a} \cdot \vec{b} \sin{\beta}\cos{\beta} + \vec{b} \cdot \vec{b} \sin^2{\beta} = R^2 $ since $\vec{a} \cdot \vec{b} = 0$.


text:
Q: How to remove columns from ListView c# I'm new with ListView and encountered a small problem :
I have a ListViewin WinForm which I fill it line after line with many columns (about 15) , later on I have an option to save ListView to CSV .
what I want is a way to let the user delete unwanted columns from ListView .
My function to create the columns at first
    private void checkAddListBoxColumns(DomainLayer.ScriptLogic.session sessionToAdd)
    {
        if (IsResultLogListViewFirstRun)
        {
            IsResultLogListViewFirstRun = false;
            this.Invoke((MethodInvoker)delegate
            {
                ResultsLogTab_ListView.Columns.Clear();
            });

            foreach (var item in sessionToAdd.comments.Keys)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    ResultsLogTab_ListView.Columns.Add(item);
                });
            }
            McsTableRow mcsTR = new McsTableRow();
            Type t = mcsTR.GetType();
            foreach (/*PropertyInfo*/FieldInfo info in t.GetFields())
            {
                this.Invoke((MethodInvoker)delegate
                {
                    ResultsLogTab_ListView.Columns.Add(info.Name+" 1");
                });
            }
            foreach (FieldInfo info in t.GetFields())
            {
                this.Invoke((MethodInvoker)delegate
                {
                    ResultsLogTab_ListView.Columns.Add(info.Name+" 2");
                });
            }
            this.Invoke((MethodInvoker)delegate
            {
                ResultsLogTab_ListView.Columns.Add("Effective PHY Rate");
            });
            //...more of the same
        }
        else
        {
            //?
        }
    }

later I add line like
            private OnSessionToAdd()
            {
            foreach (string key in sessionToAdd.comments.Keys)
            {
                item.SubItems.Add(sessionToAdd.comments[key]);
            }

            Type t = sessionToAdd.CurrentMCSCheck.firstMcsRow.GetType();

            foreach (FieldInfo info in t.GetFields())
            {
                string x = info.GetValue(sessionToAdd.CurrentMCSCheck.firstMcsRow) as string;
                item.SubItems.Add(x);
            }

            t = sessionToAdd.CurrentMCSCheck.secondMcsRow.GetType();

            foreach (FieldInfo info in t.GetFields())
            {
                string x = info.GetValue(sessionToAdd.CurrentMCSCheck.secondMcsRow) as string;
                item.SubItems.Add(x);
            }

            item.SubItems.Add(sessionToAdd.CurrentMCSCheck.EffectivePHYRate);

            this.Invoke((MethodInvoker)delegate
            {
             ResultsLogTab_ListView.Items.Add(item);
            });
            }

What i need is a way to get all names of columns and than delete columns by name or some kind of IndexOf(name)
please point me to the right direction
EDIT
just to clearfy I dont to hide columns (settings width = 0) I want to delete them
to help you understand my point I've added the way I save the ListView
the way I save to CSV :
public StringBuilder ListViewToCSV(ListView listView, string filePath, bool includeHidden)
{
    //make header string
    StringBuilder result = new StringBuilder();
    WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listView.Columns[i].Text);

    //export data rows
    foreach (ListViewItem listItem in listView.Items)
        WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listItem.SubItems[i].Text);

    return result;

}

private static void WriteCSVRow(StringBuilder result, int itemsCount, Func<int, bool> isColumnNeeded, Func<int, string> columnValue)
{
    bool isFirstTime = true;
    for (int i = 0; i < itemsCount; i++)
    {
        if (!isColumnNeeded(i))
            continue;

        if (!isFirstTime)
            result.Append(",");
        isFirstTime = false;

        result.Append(String.Format("\"{0}\"", columnValue(i)));
    }
    result.AppendLine();
}

than just save StringBuilder

A: You can reference the column by name.
var columnToRemove = ResultsLogTab_ListView.Columns["Name Of Column"];

and then remove it
ResultsLogTab_ListView.Columns.Remove(columnToRemove);

This is all documented on MSDN which is a great resource.
Update
With regards to saving/loading from CSV let's say you have a List<string> of column names (obtained from said CSV file) you want to keep then you can use LINQ to find the columns that do not match, and then iterate over the result to remove them.
using System.Linq;

...

var columnNames = new List<string> { "one", "two", "three" };

var columnsToDelete = ResultsLogTab_ListView.Columns.Where(c => !columnNames.Contains(c.Name));

foreach(var column in columnsToDelete)
{
     ResultsLogTab_ListView.Columns.Remove(column);
}


text:
Q: CPLEX Error 1016: Promotional version I have wrote a code for solving Integer Programming model in CPLEX oplide as follows:
nmbl = 521466;
nbi = 17;

int As[nbi] =...;

int amb[nmbl] = ...;
dvar boolean I[nmbl][nbi];

minimize
sum (a in nmbl, b in nbi, c in nmbl: c>a,d in nbi: d != b) I[a][b]*I[c][d]*10;

subject to
{
cons1:
forall (i in nmbl)
I[i][1] + I[i][2] + I[i][3] + I[i][4]+ I[i][5] + I[i][6] + I[i][7] + I[i][8] + I[i][9] + I[i][10] + I[i][11] + I[i][12] + I[i][13] + I[i][14] + I[i][15] + I[i][16] + I[i][17] == 1;

cons2:
forall (j in nbi)
  sum (i in nmbl) I[i][j]*amb[i] <= As[j];
}

It shows an CPLEX Error  1016: Promotional version. Problem size limits exceeded. I will be thankful to you for providing me idea to locate the problem.

A: The current problem is too large for your version of CPLEX Free. Reduce the size of the problem.
And you can to download this version :
https://www.ibm.com/developerworks/community/blogs/jfp/entry/CPLEX_Is_Free_For_Students?lang=en


text:
Q: Return value of System Function I Experimented the system function call. It is used to execute the command with in the program. The man page contains the following information about the return value of system.
RETURN VALUE
The value returned is -1 on error (e.g.  fork(2) failed), and the return status of the command otherwise.

As per the man page reference, I checked the following program.
Program:
#include<stdio.h>
#include<unistd.h>
int main()
{
    printf("System returns: %d\n",system("ls a"));
}

Output:
$ ./a.out
ls: cannot access a: No such file or directory
System returns: 512
$ ls a
ls: cannot access a: No such file or directory
mohanraj@ltsp63:~/Advanced_Unix/Chapter8/check$ echo $?
2
$

The above output shows that, return value of system function is 512 and the exit status of ls a command is 2. As per the
reference, I expect the return value of system function is equal to exit status of the ls command. But the value becomes different.
Why?

A: You forgot to read the whole section.

[T]he return value is a "wait status" that can  be
         examined  using the macros described in waitpid(2).  (i.e., WIFEXITED()
WEXITSTATUS() and so on).

A: The return value is the exit status of the shell, see sh(1), bash(1) or whatever you have configured in SHELL environment variable.  By the way, the shell usually returns the last command executed exit value, but that can not be the case if you have hit the Ctrl-C key or sent a signal to the process.  Check in the manual page for the exit value of the shell on these cases.


text:
Q: Can continuation in `IAuthorizationFilter.ExecuteAuthorizationFilterAsync` be null? I have a standard ASP.NET auth filter implementation like this.
public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext context, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
       await OnAuthorizeAsync(context);
       return context.Response ?? await continuation();
}

Can continuation be null in IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) and should I add null check?


text:
Q: Can we add private betas in "your communities" drop down? I am actively participating in a few graduated sites and a private beta. What I normally do when I become active somewhere is to add the site into my "your communities" list dropdown.
However, I noticed that it is not possible to add sites in your own "Your communities" if they are -still- in private beta.
Could we have this option?
Note this is pretty related to Have private betas in "Your Communities" list in the Stack Exchange dropdown and what was then mentioned in comments there, but wanted to make sure it is requested in a stand alone post, since in that post they are asking for something more generic.

A: You can add private beta sites in the pinned list in the drop-down list of sites same way you can add any other site. (They don't appear in the ordinary search, but do appear when adding)
All you have to do it is go to the edit button, search for it, select the site you want to add, and then click add; and you can see the site in the drop-down.

The resulting list would look like this.


text:
Q: Brackets convert to %26%2340%3B instead of %28 in PHP I use this line to get a full route name in Codeigniter:
$path = implode("/", func_get_args());
for example if user types https://example.com/test/test5678/test+(123)
I'll get this: test5678/test+(123)
It's kind of weird. Everything goes normal but the brackets:
if I urldecode($path), I'll get test5678/test (123)
Then when I encode it again (urlencode($path)) the brackets convert to %5C%26%5C%2340%5C%3B instead of %28 or ( .(same result for ))
What is wrong? How can I fix this? Thanks.


text:
Q: how to set up a multiple apache virtual host? I have installed the Zend framework. However, when I try to set up the virtual host - apache.
localhost doesn't work.its execute zend folder.its out side of wamp folder.
What have I done:
    <IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

Include "c:/wamp/alias/*"
NameVirtualHost localhost

<VirtualHost *:80>
   DocumentRoot "C:/websites/zendy/public"
   ServerName zendy

   # This should be omitted in the production environment
   SetEnv APPLICATION_ENV development

   <Directory "C:/websites/zendy/public">
       Options Indexes MultiViews FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
   </Directory>

</VirtualHost>

<VirtualHost *:80>
   DocumentRoot "C:/wamp/www"
   ServerName localhost

   # This should be omitted in the production environment
   SetEnv APPLICATION_ENV development

   <Directory "C:/wamp/www">
       Options Indexes MultiViews FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
   </Directory>

</VirtualHost>

how to work this two virtual hosts?


text:
Q: Chunk array by three in PHP (in JS it works out) as title says I wanna chunk an array by three and display results each in a single row.
In JS no problems:
const array = [1,2,3,4,5,6,7];
let i, arr, j;

for (i = 0; i < array.length; i += 3) {

 arr = array.slice(i, i + 3);
 let div = document.createElement("div");
 div.classList.add('row');

 for (j = 0; j < arr.length; j++) {
  let par = document.createElement("p");
  let res = document.createTextNode(arr[j]);
  par.appendChild(res);
  div.appendChild(par);
 }

document.body.appendChild(div);

}

Getting correctly:

1

2

3

4

5

6

7

In PHP, with this:
<?php
  $array = [1,2,3,4,5,6,7];
  for ($i = 0; $i < count($array); $i += 3) :
    $arr = array_slice($array, $i, $i + 3);
?>

    <?= implode(" ", $arr); ?>

<?php endfor; ?>

I get:

1

2

3

4

5

6

7

7

I always get the middle row wrong (even if you increase $array), what am I missing? :/

A: The third parameter of array_slice() is the length and not the end point, so change it to...
$arr = array_slice($array, $i, 3);

A: The arguments to array_slice in PHP and slice in JS aren't quite the same. PHP takes a start and a length, whereas JS takes a start and an end.
PHP:
array_slice(array $array, int $offset, int $length = NULL);

JS:
arr.slice(begin, end)

So you can't quite just copy the implementation over from one to the other. If you change your PHP line to:
$arr = array_slice($array, $i, 3);

(just specifying the length 3 instead of $i + 3), then it should work correctly.
Alternatively in PHP, you could just use array_chunk, and loop over the resulting chunks.

A: You may use array_chunk() in php
<?php
$array = [1,2,3,4,5,6,7];
echo "
";
print_r(array_chunk($array, 3));

?>

A: There's already array_chunk function:
$chunks = array_chunk($array, 3);
foreach ($chunks as $chunk) {?>

        <?= implode(" ", $chunk); ?>

<?php
}

A: Use array_chunk().
$array = [1,2,3,4,5,6,7];
$chunks = array_chunk($array, 3);

foreach ($chunks as $chunk) {
  // Do whatever you want with chunks: e.g.:
  implode(" ", $chunk);
}


text:
Q: What design pattern should I use to avoid dummy code here? I have a base class -
class content
{

private:
  int m_data;

public:

  int getdbhandle() { return m_sql_db; }

  void setData(int data) { m_data = data; }

  virtual int getterrestrialServices { qDebug()"This is a dummy interface"; }

};

class telecontent: public content
{

   virtual int getterrestrialServices { qDebug()" Real implementation here"; }

};

Now, the class content is instantiated as telecontent, when the product type is tele.
However, when the product type is generic - the dummy interface prints keep coming.
How can I avoid so? Is there any design pattern that forces the base class not to implement the dummy function? I want an efficient way so that only derived class has method. I don't want the base class to have that method. But, I can't modify the caller - code- so that the method is not called. I want the best way to strategically design such that the dummy interface can be avoided.

A:
is there any design pattern that forces the base class not to
  implement the dummy function?

Pure virtual allows this:
class content
{

private:
  int m_data;

public:
  virtual ~content() { }
  int getdbhandle() { return m_sql_db; }

  void setData(int data) { m_data = data; }

  virtual int getterrestrialServices() = 0; // pure virtual

};

This means no one can create instances of content (will cause a compiler error), and so when some one inherits from content they must provide an implementation of getterrestrialServices() (else again, they'll get a compiler error).

A: What you need is pure virtual like so:
virtual int getterrestrialServices() = 0;

It will force every class the inherits content to implement it and you wont be able to create a content class, only classes the inherit from it so you wont have the dummy prints.


text:
Q: Optimizing dataset with a composite primary key that includes a status field I might be over thinking things, but I am considering opportunities to optimize a large dataset. I have a table schema whose contents is primarily grabbed with its primary key and a status field. Is there any optimization that can be done if I somehow included the status field as part of a composite primary key to speed up search? So for example my table schema might be something like:
CREATE TABLE object_t (
    object_id SERIAL PRIMARY KEY NOT NULL,
    status VARCHAR CHECK (status ~ '(Astatus|Bstatus|Cstatus|Dstatus)'),
    contents TEXT
);

My queries will almost always be something like
SELECT * FROM object_t WHERE search condition AND status = ...

Is there any advantage here for large datasets to adjust the schema to have:
PRIMARY KEY (object_id, status)

Further, tables that I join with this table also always include that status filter. Should I then adjust foreign key constraints to be something like:
FOREIGN KEY (object_id, status) REFERENCES object_t (object_id, status)

Is there any optimization to be gained here, or is simply operating with the object_id and status filter as good as it gets?

A: The index you suggest will very likely not help.
It only offers a benefit if there is also a condition similar to this in the query:
WHERE object_id = ? AND status = ?

If only status is in the WHERE condition, the index cannot be used at all.
The name status suggests that there are not very many different values. That means that such a condition is often not very selective, which speaks against indexing it.
If you allways query for a certain status, a partial index can be helpful.
But the best thing you can do is experiment.


text: Q: How to stop Sublime Text 3 from Scrolling opened file tabs automatically on startup When I start sublime text 3, it starts jumping from one file tab to another in a cyclic manner and then stops on the same file. The Sublime text build is 3143. This happens once.


text:
Q: JPanel appears in two locations I am designing a grid-based game which uses the Java swing framework.  I have a JFrame with two JPanel within it, but one of them appears in two places.  Here is a screenshot:

The panel that says "Turn 1" and has the buttons is only supposed to appear to the right of the grid, but it strangely also appears in the upper-left hand corner.  Here is my code:
public class ArenaPanel extends JPanel {

    private final GridPanel gp;
    private final InfoPanel ip;
    private GameManager gm;
    private int w, h;
    private int cw, ch;
    private double tw, th;
    private Point p2;
    private Point p1;
    private int shotWidth;
    private Color shotColor;

    public ArenaPanel(int w, int h) {
        Images.load();
        setLayout(new GridBagLayout());
        this.w = w;
        this.h = h;
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.weightx = 0;
        c.weighty = 1;
        gp = new GridPanel();
        gp.setPreferredSize(new Dimension(700, 700));
        this.add(gp, c);
        c.gridx = 1;
        c.weightx = c.weighty = 0;
        ip = new InfoPanel();
        add(ip, c);
    }

    public void setGameManager(GameManager g) {
        gm = g;
    }

    public void start() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                gm.start();
            }
        });
        t.start();
    }

    public void step() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                gm.doTurn();
            }
        });
        t.start();
    }

    public void paint(Graphics g) {
        g.setColor(Color.black);
        int val = Math.min(getWidth() - 200, getHeight());
        gp.setPreferredSize(new Dimension(val, val));
        gp.revalidate();
        g.fillRect(0, 0, getWidth(), getHeight());
        paintComponents(g);
    }

    private class GridPanel extends JPanel {

        public void paint(Graphics g) {
            cw = getWidth();
            ch = getHeight();
            g.setColor(Color.gray);
            g.fillRect(0, 0, cw, ch);
            tw = (double) cw / w;
            th = (double) ch / h;
            g.setColor(Color.black);
            for (int i = 0; i < w; i++) {
                g.drawLine((int) (i * tw), 0, (int) (i * tw), ch);
            }
            for (int i = 0; i < h; i++) {
                g.drawLine(0, (int) (i * th), cw, (int) (i * th));
            }
            for (int i = 0; i < w; i++) {
                for (int j = 0; j < h; j++) {
                    Robot t = gm.getGrid()[i][j];
                    if (t != null) {
                        Point p = expand(i, j);
                        g.drawImage(t.getImage(), p.x + t.getOffsetX(),
                                p.y + t.getOffsetY(), (int) tw, (int) th, null);
                    }
                }
            }
            if (p1 != null) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(shotColor);
                g2.setStroke(new BasicStroke(shotWidth));
                g2.drawLine(p1.x, p1.y, p2.x, p2.y);
                p1 = null;
                p2 = null;
            }
        }
    }

    private class InfoPanel extends JPanel implements ActionListener {

        private JButton start, stop, step;
        private JLabel turns;
        private int numTurns = 0;
        private GridBagConstraints gbc;
        private ArrayList<TeamPanel> tpanels;

        public InfoPanel() {
            JPanel buttons = new JPanel();
            setLayout(new GridBagLayout());
            buttons.setLayout(new GridBagLayout());
            gbc = new GridBagConstraints();
            start = new JButton("Start");
            gbc.gridy = 0;
            gbc.gridx = 1;
            turns = new JLabel("Turn 1");
            buttons.add(turns, gbc);
            start.addActionListener(this);
            gbc.gridy = 1;
            gbc.gridx = 0;
            buttons.add(start, gbc);
            step = new JButton("Step");
            step.addActionListener(this);
            gbc.gridx++;
            buttons.add(step, gbc);
            stop = new JButton("Stop");
            stop.addActionListener(this);
            gbc.gridx++;
            buttons.add(stop, gbc);
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(buttons, gbc);
            tpanels = new ArrayList<TeamPanel>();
        }

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (actionEvent.getSource() == start) {
                start();
            } else if (actionEvent.getSource() == stop) {
                gm.stop();
            } else if (actionEvent.getSource() == step) {
                step();
            }
        }

        public void incrementTurn() {
            numTurns++;
            turns.setText("Turn " + numTurns);
        }

        public void initializeTeams(Map<String, TeamInfo> m) {
            Set<String> k = m.keySet();
            for (TeamPanel tp : tpanels) {
                this.remove(tp);
            }
            tpanels.clear();
            gbc.gridy = 1;
            for (String s : k) {
                TeamPanel tp = new TeamPanel(m.get(s));
                add(tp, gbc);
                gbc.gridy++;
                tpanels.add(tp);
            }
            this.revalidate();
        }
    }

    private class TeamPanel extends JPanel {
        private Color col;
        private int score;
        private JLabel scoreLabel;
        private TeamInfo inf;

        public TeamPanel(TeamInfo inf) {
            this.inf = inf;
            col = getColor(inf.c);
            super.setLayout(new FlowLayout());
            BufferedImage ico = new BufferedImage(20, 20, BufferedImage.TYPE_3BYTE_BGR);
            Graphics g = ico.getGraphics();
            g.setColor(col);
            g.fillRect(0, 0, 20, 20);
            add(new JLabel(new ImageIcon(ico)));
            this.add(new JLabel(inf.team));
            scoreLabel = new JLabel("" + inf.score);
            add(scoreLabel);
        }

        public void paint(Graphics g) {
            //g.setColor(col);
            //g.fillRect(-5, 0, 10, 10);
            scoreLabel.setText("Score: " + inf.score);
            this.paintComponents(g);
        }
    }

    public void initializeTeams(Map<String, TeamInfo> m) {
        ip.initializeTeams(m);
    }
}

I have looked on google and StackOverflow for a similar problem, but I was unable to find one.  Any help would be greatly appreciated.
Thanks!

A: *

*Don't override the paint(...) method

*Override the JPanel's paintComponent(...) method instead.

*Don't forget to call the super paintComponent(...) method within your override.

*And never call the super's paintComponents(...) (note the trailing "s") from within either the paint or paintComponent method. This smells like it could be the cause of your problem.