问:
android studio app just says error in network connection
I have created a login and register system, when ever I try to login, register, change password or reset password the app just says "Error In Network Connection".

I am using strong internet connection, could you please advise as I have tried to on WI-FI and 4G, however it still says the same error.

Please view the logcat errors

```<code>06-25 14:23:44.625  16888-16888/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: samsung sensitivity: NULL, cateogry: NULL
06-25 14:23:44.705  16888-16903/? E/SPPClientService﹕ ============PushLog. commonIsShipBuild. stop!
06-25 14:23:44.705  16888-16903/? E/SPPClientService﹕ [PushClientApplication] Push log off : This is Ship build version
06-25 14:23:44.735  16906-16906/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:44.735  16906-16906/? E/Zygote﹕ v2
06-25 14:23:44.755  16906-16906/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:44.825  16922-16922/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:44.825  16922-16922/? E/Zygote﹕ v2
06-25 14:23:44.845  16922-16922/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:44.995  16949-16949/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:44.995  16949-16949/? E/Zygote﹕ v2
06-25 14:23:45.055  16949-16949/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:45.495  16976-16976/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:45.495  16976-16976/? E/Zygote﹕ v2
06-25 14:23:45.545  16976-16976/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:45.695  16976-16976/? E/PhotosPlugin﹕ Loading PhotosPlugin
06-25 14:23:46.095  17021-17021/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.095  17021-17021/? E/Zygote﹕ v2
06-25 14:23:46.135  17021-17021/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: samsung sensitivity: NULL, cateogry: NULL
06-25 14:23:46.495  17060-17060/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.495  17060-17060/? E/Zygote﹕ v2
06-25 14:23:46.535  17060-17060/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:46.655    3216-3216/? E/PackageReceiver﹕ this package will be replased, skip this package
06-25 14:23:46.655    3216-3216/? E/PackageReceiver﹕ This package will be replaced = com.brad.visor
06-25 14:24:18.665     930-1106/? E/MotionRecognitionService﹕ handler : SCREEN_ON end
06-25 14:23:46.745  17105-17105/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.745  17105-17105/? E/Zygote﹕ v2
06-25 14:23:46.785  17105-17105/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:46.915  17124-17124/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.915  17124-17124/? E/Zygote﹕ v2
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 0 : /system/app/
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 1 : /system/priv-app/
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 2 : /vendor/app/
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 3 : /oem/app/
06-25 14:23:46.955  17124-17124/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:47.115  17148-17148/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.115  17148-17148/? E/Zygote﹕ v2
06-25 14:23:47.155  17148-17148/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:47.385  16669-17170/? E/FilterInstaller﹕ There is no requred permission
06-25 14:23:47.465      281-281/? E/SMD﹕ DCD ON
06-25 14:23:47.515  17183-17183/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.515  17183-17183/? E/Zygote﹕ v2
06-25 14:23:47.535  17183-17183/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:47.545  17199-17199/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.545  17199-17199/? E/Zygote﹕ v2
06-25 14:23:47.565  17199-17199/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:47.815  17223-17223/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.815  17223-17223/? E/Zygote﹕ v2
06-25 14:23:47.855  17223-17223/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: samsung sensitivity: NULL, cateogry: NULL
06-25 14:23:48.065  17249-17249/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:48.065  17249-17249/? E/Zygote﹕ v2
06-25 14:23:48.115  17249-17249/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
06-25 14:23:48.205    3216-3216/? E/PackageReceiver﹕ this package will be replased, skip this package
06-25 14:23:48.205    3216-3216/? E/PackageReceiver﹕ This package will be replaced = com.brad.visor
06-25 14:23:48.475    1700-1700/? E/NetworkScheduler.SchedulerReceiver﹕ Invalid parameter app
06-25 14:23:48.475    1700-1700/? E/NetworkScheduler.SchedulerReceiver﹕ Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
06-25 14:23:48.525  17270-17270/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:48.525  17270-17270/? E/Zygote﹕ v2
06-25 14:23:48.555  17270-17270/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:49.035  17270-17270/? E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
06-25 14:23:49.225  17270-17328/? E/File﹕ fail readDirectory() errno=2
06-25 14:23:49.325    1669-7212/? E/MDM﹕ [181] b.run: Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}
06-25 14:23:50.465      281-281/? E/SMD﹕ DCD ON
06-25 14:23:53.475      281-281/? E/SMD﹕ DCD ON
06-25 14:23:56.475      281-281/? E/SMD﹕ DCD ON
06-25 14:23:57.315  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:57.925  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:58.095  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:58.155  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:59.465      281-281/? E/SMD﹕ DCD ON
06-25 14:24:02.465      281-281/? E/SMD﹕ DCD ON
06-25 14:24:02.605     930-1128/? E/WifiStateMachine﹕ WifiStateMachine CMD_START_SCAN source 10014 txSuccessRate=94.24 rxSuccessRate=74.75 targetRoamBSSID=c4:04:15:c1:13:70 RSSI=-40
06-25 14:24:02.615     930-1128/? E/WifiStateMachine﹕ [1,435,238,642,625 ms] noteScanStartWorkSource{10014} uid 10014
06-25 14:24:05.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:06.525     930-1128/? E/WifiStateMachine﹕ [1,435,238,646,538 ms] noteScanEnd WorkSource{10014}
06-25 14:24:06.545     930-1128/? E/WifiStateMachine﹕ wifi setScanResults statecom.android.server.wifi.WifiStateMachine$ConnectedState@550587e sup_state=COMPLETED debouncing=false
06-25 14:24:06.745      930-930/? E/LocSvc_flp﹕ I/===> int flp_inject_location(FlpLocation*) line 222
06-25 14:24:06.745     930-1419/? E/LocSvc_ApiV02﹕ I/<--- void globalRespCb(locClientHandleType, uint32_t, locClientRespIndUnionType, void*) line 125 QMI_LOC_INJECT_POSITION_REQ_V02
06-25 14:24:08.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:11.465      281-281/? E/SMD﹕ DCD ON
06-25 14:24:14.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:17.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:18.545      251-251/? E/qdexternal﹕ writeHPDOption: file write failed '/sys/devices/virtual/graphics/fb1/hpd'
06-25 14:24:18.675     930-1128/? E/WifiStateMachine﹕ handleScreenStateChanged Exit: true
06-25 14:24:18.695     930-1128/? E/WifiStateMachine﹕ setSuspendOptimizationsNative: 4 false -want true stack:setSuspendOptimizationsNative - access$16800 - processMessage - processMsg
06-25 14:24:18.695     930-1128/? E/native﹕ do suspend false
06-25 14:24:18.885    1315-1315/? E/daemonapp﹕ [MSC_Daemon]>>> WU:1606 [0:0] [NameNotFoundException] !!
06-25 14:24:18.925    4622-4819/? E/BtGatt.ScanManager﹕ default value of curScanSetting 0 is choosen
06-25 14:24:19.905     930-1816/? E/PersonaManagerService﹕ inState():  stateMachine is null !!
06-25 14:24:20.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:21.125     930-1423/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:21.155   2258-17537/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:21.155   2258-17538/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:21.685    2258-2258/? E/SamsungIME﹕ SwiftKey guide popup condition 2 : true false false true true true true true true true
06-25 14:24:22.585     930-1128/? E/WifiStateMachine﹕ [1,435,238,662,601 ms] noteScanEnd no scan source
06-25 14:24:22.595     930-1128/? E/WifiStateMachine﹕ wifi setScanResults statecom.android.server.wifi.WifiStateMachine$ConnectedState@550587e sup_state=COMPLETED debouncing=false
06-25 14:24:23.265   1172-17483/? E/SViewCoverBase﹕ requestDumpUpload : MC is not installed
06-25 14:24:23.295     930-1232/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:23.325   2258-17571/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:23.415   2258-17582/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:23.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:23.925    2258-2258/? E/SamsungIME﹕ SwiftKey guide popup condition 2 : true false false true true true true true true true
06-25 14:24:25.475     930-1423/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:25.485  16752-16752/com.brad.visor E/ViewRootImpl﹕ sendUserActionEvent() mView == null
06-25 14:24:25.775     930-1336/? E/Watchdog﹕ !@Sync 167
06-25 14:24:26.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:27.355     930-1712/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.625  17614-17614/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:27.625  17614-17614/? E/Zygote﹕ v2
06-25 14:24:27.645  17614-17614/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.865  17632-17632/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:27.865  17632-17632/? E/Zygote﹕ v2
06-25 14:24:27.895  17632-17632/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: shared sensitivity: NULL, cateogry: NULL
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.985  17648-17648/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:27.985  17648-17648/? E/Zygote﹕ v2
06-25 14:24:28.005  17648-17648/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.085  17664-17664/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:28.085  17664-17664/? E/Zygote﹕ v2
06-25 14:24:28.115  17664-17664/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:24:28.765     930-1050/? E/PowerManagerService﹕ handleSandman : startDreaming, but isDreaming false
06-25 14:24:28.905     930-1128/? E/WifiStateMachine﹕ WifiStateMachine CMD_START_SCAN source 10014 txSuccessRate=33.91 rxSuccessRate=24.84 targetRoamBSSID=c4:04:15:c1:13:70 RSSI=-41
06-25 14:24:28.905     930-1128/? E/WifiStateMachine﹕ [1,435,238,668,921 ms] noteScanstart no scan source
06-25 14:24:28.905      930-930/? E/LightSensor﹕ Light old sensor_state 0, new sensor_state : 512 en : 1
06-25 14:24:28.965     930-1106/? E/MotionRecognitionService﹕ handler : SCREEN_OFF end
06-25 14:24:28.965     930-1128/? E/WifiStateMachine﹕ handleScreenStateChanged Exit: false
06-25 14:24:28.975    286-17705/? E/AudioPlayer﹕ >>> setAudioEffect Error mAudioFormat : 1, event : 168430090, value : 151652874
06-25 14:24:28.985     930-1128/? E/WifiStateMachine﹕ setSuspendOptimizationsNative: 4 true -want true stack:setSuspendOptimizationsNative - access$16800 - processMessage - processMsg
06-25 14:24:28.985     930-1128/? E/WifiStateMachine﹕ setSuspendOptimizationsNative do it 4 true stack:setSuspendOptimizationsNative - access$16800 - processMessage - processMsg
06-25 14:24:28.985     930-1128/? E/native﹕ do suspend true
06-25 14:24:29.025    286-17709/? E/AudioPlayer﹕ >>> setAudioEffect Error mAudioFormat : 1, event : 4587583, value : 4390976
06-25 14:24:29.075    286-17713/? E/AudioPlayer﹕ >>> setAudioEffect Error mAudioFormat : 1, event : 4587583, value : 4390976
06-25 14:24:29.275     930-1014/? E/LightSensor﹕ RED : 0, GREEN : 0, BLUE : 0, CLEAR : 0, CALCULATED LUX : 0.000000, CCT : 1596.000000, REAL LUX : 0.000000 a_time = 238, gain = 64, ir=0, rp1=1, gp1=0, bp1=0, cp1=0, cpl=3202560
06-25 14:24:29.275     930-1076/? E/LightSensor﹕ Light old sensor_state 512, new sensor_state : 0 en : 0
06-25 14:24:29.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:29.555      930-930/? E/MotionRecognitionService﹕ mReceiver.onReceive : ACTION_USER_PRESENT  :: UNLOCK SCREEN
06-25 14:24:29.555      930-930/? E/LightSensor﹕ Light old sensor_state 0, new sensor_state : 512 en : 1
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.605  17723-17723/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:29.605  17723-17723/? E/Zygote﹕ v2
06-25 14:24:29.655  17723-17723/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
06-25 14:24:29.695    1172-1172/? E/StatusBar﹕ onReceive : Intent.ACTION_SCREEN_OFF
06-25 14:24:29.935     930-1014/? E/LightSensor﹕ RED : 0, GREEN : 0, BLUE : 0, CLEAR : 0, CALCULATED LUX : 0.000000, CCT : 1596.000000, REAL LUX : 0.000000 a_time = 238, gain = 64, ir=0, rp1=1, gp1=0, bp1=0, cp1=0, cpl=3202560
06-25 14:24:29.935     930-1076/? E/LightSensor﹕ Light old sensor_state 512, new sensor_state : 0 en : 0
06-25 14:24:29.995    4622-4819/? E/BtGatt.ScanManager﹕ default value of curScanSetting 0 is choosen
06-25 14:24:30.075  17723-17723/? E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
06-25 14:24:32.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:32.785     930-1128/? E/WifiStateMachine﹕ [1,435,238,672,797 ms] noteScanEnd WorkSource{10014}
06-25 14:24:32.795     930-1128/? E/WifiStateMachine﹕ wifi setScanResults statecom.android.server.wifi.WifiStateMachine$ConnectedState@550587e sup_state=COMPLETED debouncing=false
06-25 14:24:35.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:38.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:41.485      281-281/? E/SMD﹕ DCD ON
</code>```

manifest file

```<code>  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.brad.visor" >

    <application

        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login">
        </activity>
        <activity
            android:name=".Register">
        </activity>
        <activity
            android:name=".Registered">
        </activity>
        <activity
            android:name=".Main">
        </activity>
        <activity
            android:name=".PasswordReset">
        </activity>
        <activity
            android:name=".ChangePassword">
        </activity>

    </application>

    <!-- Allow to connect with internet and to know the current network state-->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>
</code>```

答:
check application on different devices

check for connection with following method

```<code>public static boolean isNetworkConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}
</code>```

Body:
I have created a login and register system, when ever I try to login, register, change password or reset password the app just says "Error In Network Connection".

I am using strong internet connection, could you please advise as I have tried to on WI-FI and 4G, however it still says the same error.

Please view the logcat errors

06-25 14:23:44.625  16888-16888/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: samsung sensitivity: NULL, cateogry: NULL
06-25 14:23:44.705  16888-16903/? E/SPPClientService﹕ ============PushLog. commonIsShipBuild. stop!
06-25 14:23:44.705  16888-16903/? E/SPPClientService﹕ [PushClientApplication] Push log off : This is Ship build version
06-25 14:23:44.735  16906-16906/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:44.735  16906-16906/? E/Zygote﹕ v2
06-25 14:23:44.755  16906-16906/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:44.825  16922-16922/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:44.825  16922-16922/? E/Zygote﹕ v2
06-25 14:23:44.845  16922-16922/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:44.995  16949-16949/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:44.995  16949-16949/? E/Zygote﹕ v2
06-25 14:23:45.055  16949-16949/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:45.495  16976-16976/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:45.495  16976-16976/? E/Zygote﹕ v2
06-25 14:23:45.545  16976-16976/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:45.695  16976-16976/? E/PhotosPlugin﹕ Loading PhotosPlugin
06-25 14:23:46.095  17021-17021/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.095  17021-17021/? E/Zygote﹕ v2
06-25 14:23:46.135  17021-17021/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: samsung sensitivity: NULL, cateogry: NULL
06-25 14:23:46.495  17060-17060/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.495  17060-17060/? E/Zygote﹕ v2
06-25 14:23:46.535  17060-17060/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:46.655    3216-3216/? E/PackageReceiver﹕ this package will be replased, skip this package
06-25 14:23:46.655    3216-3216/? E/PackageReceiver﹕ This package will be replaced = com.brad.visor
06-25 14:24:18.665     930-1106/? E/MotionRecognitionService﹕ handler : SCREEN_ON end
06-25 14:23:46.745  17105-17105/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.745  17105-17105/? E/Zygote﹕ v2
06-25 14:23:46.785  17105-17105/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:46.915  17124-17124/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:46.915  17124-17124/? E/Zygote﹕ v2
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 0 : /system/app/
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 1 : /system/priv-app/
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 2 : /vendor/app/
06-25 14:23:46.925      292-292/? E/installd﹕ system dir 3 : /oem/app/
06-25 14:23:46.955  17124-17124/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:47.115  17148-17148/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.115  17148-17148/? E/Zygote﹕ v2
06-25 14:23:47.155  17148-17148/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:47.385  16669-17170/? E/FilterInstaller﹕ There is no requred permission
06-25 14:23:47.465      281-281/? E/SMD﹕ DCD ON
06-25 14:23:47.515  17183-17183/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.515  17183-17183/? E/Zygote﹕ v2
06-25 14:23:47.535  17183-17183/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:23:47.545  17199-17199/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.545  17199-17199/? E/Zygote﹕ v2
06-25 14:23:47.565  17199-17199/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:47.815  17223-17223/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:47.815  17223-17223/? E/Zygote﹕ v2
06-25 14:23:47.855  17223-17223/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: samsung sensitivity: NULL, cateogry: NULL
06-25 14:23:48.065  17249-17249/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:48.065  17249-17249/? E/Zygote﹕ v2
06-25 14:23:48.115  17249-17249/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
06-25 14:23:48.205    3216-3216/? E/PackageReceiver﹕ this package will be replased, skip this package
06-25 14:23:48.205    3216-3216/? E/PackageReceiver﹕ This package will be replaced = com.brad.visor
06-25 14:23:48.475    1700-1700/? E/NetworkScheduler.SchedulerReceiver﹕ Invalid parameter app
06-25 14:23:48.475    1700-1700/? E/NetworkScheduler.SchedulerReceiver﹕ Invalid package name : Perhaps you didn't include a PendingIntent in the extras?
06-25 14:23:48.525  17270-17270/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:23:48.525  17270-17270/? E/Zygote﹕ v2
06-25 14:23:48.555  17270-17270/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: untrusted sensitivity: NULL, cateogry: NULL
06-25 14:23:49.035  17270-17270/? E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
06-25 14:23:49.225  17270-17328/? E/File﹕ fail readDirectory() errno=2
06-25 14:23:49.325    1669-7212/? E/MDM﹕ [181] b.run: Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}
06-25 14:23:50.465      281-281/? E/SMD﹕ DCD ON
06-25 14:23:53.475      281-281/? E/SMD﹕ DCD ON
06-25 14:23:56.475      281-281/? E/SMD﹕ DCD ON
06-25 14:23:57.315  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:57.925  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:58.095  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:58.155  17021-17102/? E/SQLiteLog﹕ (284) automatic index on LOCAL_DUPS(local_dup_id)
06-25 14:23:59.465      281-281/? E/SMD﹕ DCD ON
06-25 14:24:02.465      281-281/? E/SMD﹕ DCD ON
06-25 14:24:02.605     930-1128/? E/WifiStateMachine﹕ WifiStateMachine CMD_START_SCAN source 10014 txSuccessRate=94.24 rxSuccessRate=74.75 targetRoamBSSID=c4:04:15:c1:13:70 RSSI=-40
06-25 14:24:02.615     930-1128/? E/WifiStateMachine﹕ [1,435,238,642,625 ms] noteScanStartWorkSource{10014} uid 10014
06-25 14:24:05.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:06.525     930-1128/? E/WifiStateMachine﹕ [1,435,238,646,538 ms] noteScanEnd WorkSource{10014}
06-25 14:24:06.545     930-1128/? E/WifiStateMachine﹕ wifi setScanResults statecom.android.server.wifi.WifiStateMachine$ConnectedState@550587e sup_state=COMPLETED debouncing=false
06-25 14:24:06.745      930-930/? E/LocSvc_flp﹕ I/===> int flp_inject_location(FlpLocation*) line 222
06-25 14:24:06.745     930-1419/? E/LocSvc_ApiV02﹕ I/<--- void globalRespCb(locClientHandleType, uint32_t, locClientRespIndUnionType, void*) line 125 QMI_LOC_INJECT_POSITION_REQ_V02
06-25 14:24:08.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:11.465      281-281/? E/SMD﹕ DCD ON
06-25 14:24:14.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:17.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:18.545      251-251/? E/qdexternal﹕ writeHPDOption: file write failed '/sys/devices/virtual/graphics/fb1/hpd'
06-25 14:24:18.675     930-1128/? E/WifiStateMachine﹕ handleScreenStateChanged Exit: true
06-25 14:24:18.695     930-1128/? E/WifiStateMachine﹕ setSuspendOptimizationsNative: 4 false -want true stack:setSuspendOptimizationsNative - access$16800 - processMessage - processMsg
06-25 14:24:18.695     930-1128/? E/native﹕ do suspend false
06-25 14:24:18.885    1315-1315/? E/daemonapp﹕ [MSC_Daemon]>>> WU:1606 [0:0] [NameNotFoundException] !!
06-25 14:24:18.925    4622-4819/? E/BtGatt.ScanManager﹕ default value of curScanSetting 0 is choosen
06-25 14:24:19.905     930-1816/? E/PersonaManagerService﹕ inState():  stateMachine is null !!
06-25 14:24:20.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:21.125     930-1423/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:21.155   2258-17537/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:21.155   2258-17538/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:21.685    2258-2258/? E/SamsungIME﹕ SwiftKey guide popup condition 2 : true false false true true true true true true true
06-25 14:24:22.585     930-1128/? E/WifiStateMachine﹕ [1,435,238,662,601 ms] noteScanEnd no scan source
06-25 14:24:22.595     930-1128/? E/WifiStateMachine﹕ wifi setScanResults statecom.android.server.wifi.WifiStateMachine$ConnectedState@550587e sup_state=COMPLETED debouncing=false
06-25 14:24:23.265   1172-17483/? E/SViewCoverBase﹕ requestDumpUpload : MC is not installed
06-25 14:24:23.295     930-1232/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:23.325   2258-17571/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:23.415   2258-17582/? E/SamsungIME﹕ lang.getLanguageCode():en, lang.getCountryCode():GB
06-25 14:24:23.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:23.925    2258-2258/? E/SamsungIME﹕ SwiftKey guide popup condition 2 : true false false true true true true true true true
06-25 14:24:25.475     930-1423/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:25.485  16752-16752/com.brad.visor E/ViewRootImpl﹕ sendUserActionEvent() mView == null
06-25 14:24:25.775     930-1336/? E/Watchdog﹕ !@Sync 167
06-25 14:24:26.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:27.355     930-1712/? E/ClipboardUIManager﹕ Failed to get ClipboardService
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.615      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.625  17614-17614/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:27.625  17614-17614/? E/Zygote﹕ v2
06-25 14:24:27.645  17614-17614/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.855     930-1077/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.865  17632-17632/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:27.865  17632-17632/? E/Zygote﹕ v2
06-25 14:24:27.895  17632-17632/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: shared sensitivity: NULL, cateogry: NULL
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.975      930-947/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:27.985  17648-17648/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:27.985  17648-17648/? E/Zygote﹕ v2
06-25 14:24:28.005  17648-17648/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.075     930-1423/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:28.085  17664-17664/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:28.085  17664-17664/? E/Zygote﹕ v2
06-25 14:24:28.115  17664-17664/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: platform sensitivity: NULL, cateogry: NULL
06-25 14:24:28.765     930-1050/? E/PowerManagerService﹕ handleSandman : startDreaming, but isDreaming false
06-25 14:24:28.905     930-1128/? E/WifiStateMachine﹕ WifiStateMachine CMD_START_SCAN source 10014 txSuccessRate=33.91 rxSuccessRate=24.84 targetRoamBSSID=c4:04:15:c1:13:70 RSSI=-41
06-25 14:24:28.905     930-1128/? E/WifiStateMachine﹕ [1,435,238,668,921 ms] noteScanstart no scan source
06-25 14:24:28.905      930-930/? E/LightSensor﹕ Light old sensor_state 0, new sensor_state : 512 en : 1
06-25 14:24:28.965     930-1106/? E/MotionRecognitionService﹕ handler : SCREEN_OFF end
06-25 14:24:28.965     930-1128/? E/WifiStateMachine﹕ handleScreenStateChanged Exit: false
06-25 14:24:28.975    286-17705/? E/AudioPlayer﹕ >>> setAudioEffect Error mAudioFormat : 1, event : 168430090, value : 151652874
06-25 14:24:28.985     930-1128/? E/WifiStateMachine﹕ setSuspendOptimizationsNative: 4 true -want true stack:setSuspendOptimizationsNative - access$16800 - processMessage - processMsg
06-25 14:24:28.985     930-1128/? E/WifiStateMachine﹕ setSuspendOptimizationsNative do it 4 true stack:setSuspendOptimizationsNative - access$16800 - processMessage - processMsg
06-25 14:24:28.985     930-1128/? E/native﹕ do suspend true
06-25 14:24:29.025    286-17709/? E/AudioPlayer﹕ >>> setAudioEffect Error mAudioFormat : 1, event : 4587583, value : 4390976
06-25 14:24:29.075    286-17713/? E/AudioPlayer﹕ >>> setAudioEffect Error mAudioFormat : 1, event : 4587583, value : 4390976
06-25 14:24:29.275     930-1014/? E/LightSensor﹕ RED : 0, GREEN : 0, BLUE : 0, CLEAR : 0, CALCULATED LUX : 0.000000, CCT : 1596.000000, REAL LUX : 0.000000 a_time = 238, gain = 64, ir=0, rp1=1, gp1=0, bp1=0, cp1=0, cpl=3202560
06-25 14:24:29.275     930-1076/? E/LightSensor﹕ Light old sensor_state 512, new sensor_state : 0 en : 0
06-25 14:24:29.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:29.555      930-930/? E/MotionRecognitionService﹕ mReceiver.onReceive : ACTION_USER_PRESENT  :: UNLOCK SCREEN
06-25 14:24:29.555      930-930/? E/LightSensor﹕ Light old sensor_state 0, new sensor_state : 512 en : 1
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.595     930-1581/? E/ActivityManager﹕ checkUser: useridlist=null, currentuser=0
06-25 14:24:29.605  17723-17723/? E/Zygote﹕ MountEmulatedStorage()
06-25 14:24:29.605  17723-17723/? E/Zygote﹕ v2
06-25 14:24:29.655  17723-17723/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
06-25 14:24:29.695    1172-1172/? E/StatusBar﹕ onReceive : Intent.ACTION_SCREEN_OFF
06-25 14:24:29.935     930-1014/? E/LightSensor﹕ RED : 0, GREEN : 0, BLUE : 0, CLEAR : 0, CALCULATED LUX : 0.000000, CCT : 1596.000000, REAL LUX : 0.000000 a_time = 238, gain = 64, ir=0, rp1=1, gp1=0, bp1=0, cp1=0, cpl=3202560
06-25 14:24:29.935     930-1076/? E/LightSensor﹕ Light old sensor_state 512, new sensor_state : 0 en : 0
06-25 14:24:29.995    4622-4819/? E/BtGatt.ScanManager﹕ default value of curScanSetting 0 is choosen
06-25 14:24:30.075  17723-17723/? E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
06-25 14:24:32.475      281-281/? E/SMD﹕ DCD ON
06-25 14:24:32.785     930-1128/? E/WifiStateMachine﹕ [1,435,238,672,797 ms] noteScanEnd WorkSource{10014}
06-25 14:24:32.795     930-1128/? E/WifiStateMachine﹕ wifi setScanResults statecom.android.server.wifi.WifiStateMachine$ConnectedState@550587e sup_state=COMPLETED debouncing=false
06-25 14:24:35.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:38.485      281-281/? E/SMD﹕ DCD ON
06-25 14:24:41.485      281-281/? E/SMD﹕ DCD ON

manifest file

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.brad.visor" >

    <application

        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login">
        </activity>
        <activity
            android:name=".Register">
        </activity>
        <activity
            android:name=".Registered">
        </activity>
        <activity
            android:name=".Main">
        </activity>
        <activity
            android:name=".PasswordReset">
        </activity>
        <activity
            android:name=".ChangePassword">
        </activity>

    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

</manifest>

Body:
check application on different devices

check for connection with following method

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnected();
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Sort by Frequency of Values in a Column - Pandas
I have a column in a dataframe

Fruits

Apple

                                                                Mango

Banana

Apple

                                                                Mango

Banana

Apple

                                                                Mango

Grapes

I want to sort this column by Frequency of the values occurring in it, So the dataframe now should be:

Fruits

Apple

                                                                Apple

Apple

Banana

                                                               Banana

Banana

Mango

                                                                Mango

Grapes

Thanks!

答:
Create a freq column and then sort by freq and fruit name.

```<code>df.assign(freq=df.apply(lambda x: df.Fruits.value_counts()\
  .to_dict()[x.Fruits], axis=1))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]
Out[593]:
   Fruits
0   Apple
3   Apple
6   Apple
1   Mango
4   Mango
7   Mango
2  Banana
5  Banana
8  Grapes
</code>```

A similar approach by using groupby and count:

```<code>df.assign(freq=df.groupby('Fruits')['Fruits'].transform('count'))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]
</code>```

To view all columns:

```<code>df.assign(freq=df.groupby('Fruits')['Fruits'].transform('count'))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Create a freq column and then sort by freq and fruit name.

df.assign(freq=df.apply(lambda x: df.Fruits.value_counts()\
  .to_dict()[x.Fruits], axis=1))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]
Out[593]:
   Fruits
0   Apple
3   Apple
6   Apple
1   Mango
4   Mango
7   Mango
2  Banana
5  Banana
8  Grapes

A similar approach by using groupby and count:

df.assign(freq=df.groupby('Fruits')['Fruits'].transform('count'))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True]).loc[:,['Fruits']]

To view all columns:

df.assign(freq=df.groupby('Fruits')['Fruits'].transform('count'))\
  .sort_values(by=['freq','Fruits'],ascending=[False,True])


问:
Finding orders made within any ISO week of a specific year using T-SQL
As part of a reporting setup, I have a SQL query fetching the number of orders placed each week:

```<code>select datepart(isowk, order_date), count(*)
from orders where year(order_date) = @Year
group by datepart(isowk, order_date), year(order_date)
order by 1
</code>```

Note that I am using the new isowk format in the datepart function call, as business in Denmark typically use ISO week numbers.

Running this query with @Year = 2010 yields a result set simialar to this:

```<code>1           5
2           7
3           10
...
53          3
</code>```

You and I both know that 2010 isn't over yet, and certainly there has been no week 53 yet. Actually, there has - the first three days of the year belonged to ISO week 53 of 2009. While it might be possible to explain this to other programmers, the people who are going to read my reports are never going to understand this. Hence, I want to get rid of this week 53, by "moving" the data over to 2009.

How can I rewrite my WHERE clause to filter the data set to orders made between monday of week 1 and friday of the last week (52 or 53) in the year defined as @Year?

答:
In fact I do not know any programming language which delivers a isoyear ...

```<code>create function isoyear(@date datetime) returns smallint as begin
declare @isoyear smallint =
    case
    when datepart(isowk, @date) = 1 and month(@date) = 12
    then year(@date)+1
    when datepart(isowk, @date) = 53 and month(@date) = 1
    then year(@date)-1
    else year(@date)
    end;
return @isoyear;
end;
</code>```

Hope we'll get a datepart(isoyear, ...) next time ...

ContentLicense: CC BY-SA 2.5

Body:
As part of a reporting setup, I have a SQL query fetching the number of orders placed each week:

select datepart(isowk, order_date), count(*)
from orders where year(order_date) = @Year
group by datepart(isowk, order_date), year(order_date)
order by 1

Note that I am using the new isowk format in the datepart function call, as business in Denmark typically use ISO week numbers.

Running this query with @Year = 2010 yields a result set simialar to this:

1           5
2           7
3           10
...
53          3

You and I both know that 2010 isn't over yet, and certainly there has been no week 53 yet. Actually, there has - the first three days of the year belonged to ISO week 53 of 2009. While it might be possible to explain this to other programmers, the people who are going to read my reports are never going to understand this. Hence, I want to get rid of this week 53, by "moving" the data over to 2009.

How can I rewrite my WHERE clause to filter the data set to orders made between monday of week 1 and friday of the last week (52 or 53) in the year defined as @Year?

Body:
In fact I do not know any programming language which delivers a isoyear ...

create function isoyear(@date datetime) returns smallint as begin
declare @isoyear smallint =
    case
    when datepart(isowk, @date) = 1 and month(@date) = 12
    then year(@date)+1
    when datepart(isowk, @date) = 53 and month(@date) = 1
    then year(@date)-1
    else year(@date)
    end;
return @isoyear;
end;

Hope we'll get a datepart(isoyear, ...) next time ...


问:
Handle next events after seeing a specific number of them
What I'm attempting to do is subscribe to an observable that emits a sequence of Enums. The goal being that every time I've seen 3 Enums of a specific kind that my onNext is called. Below is what I've attempted However, it only works once. It doesn't continue on. I'm wondering what is the best way to handle this.

```<code>enum Baseball {
 case strike, ball, hit
}

let bag = DisposeBag()
let subject = PublishSubject<Baseball>()

subject.filter { $0 == .strike }
  .elementAt(2)
  .subscribe(onNext: { _ in print("3 Strikes you're out")
}).addDisposableTo(bag)

// First batter
subject.onNext(.strike)
subject.onNext(.ball)
subject.onNext(.ball)
subject.onNext(.ball)
subject.onNext(.strike)
subject.onNext(.strike) // 3 Strikes you're out is printed

// Second batter
subject.onNext(.ball)
subject.onNext(.ball)
subject.onNext(.hit)

// Third batter
subject.onNext(.strike)
subject.onNext(.strike)
subject.onNext(.strike) // Would like this to fire as well
</code>```

答:
This is a fun exercise.

Buffer

As shown by @daniel-t, this approach takes a .buffer of capacity 3 and when it is full, you know there were 3 strikes.

Counter

In addition to the buffer approach, you can also use a counter:

```<code>let subject = PublishSubject<Baseball>()

let strikes = subject.asObservable()
    .filter { $0 == .strike }
let ticker = strikes.map { _ in () }
let counter = ticker.scan(0) { (memo, _) -> Int in memo + 1 }

strikes.withLatestFrom(counter) { strike, count in (strike, count) }
    .filter { _, count in count % 3 == 0 }
    .subscribe(onNext: { _ in print("3 Strikes you're out")
    }).addDisposableTo(bag)
</code>```

With another operator or two, one could also make the increasing strike counter reset to 0 after 3.

Index as Counter

```<code>let subject = PublishSubject<Baseball>()

let strikes = subject.asObservable()
    .filter { $0 == .strike }
// Unlike the counter, this starts at 0 and reports "% 3 == 0" too early.
strikes.mapWithIndex { _, index in index + 1 }
    .filter { $0 % 3 == 0 }
    .subscribe(onNext: { _ in print("3 Strikes you're out")
    }).addDisposableTo(bag)
</code>```

Body:
What I'm attempting to do is subscribe to an observable that emits a sequence of Enums. The goal being that every time I've seen 3 Enums of a specific kind that my onNext is called. Below is what I've attempted However, it only works once. It doesn't continue on. I'm wondering what is the best way to handle this.

enum Baseball {
 case strike, ball, hit
}

let bag = DisposeBag()
let subject = PublishSubject<Baseball>()

subject.filter { $0 == .strike }
  .elementAt(2)
  .subscribe(onNext: { _ in print("3 Strikes you're out")
}).addDisposableTo(bag)

// First batter
subject.onNext(.strike)
subject.onNext(.ball)
subject.onNext(.ball)
subject.onNext(.ball)
subject.onNext(.strike)
subject.onNext(.strike) // 3 Strikes you're out is printed

// Second batter
subject.onNext(.ball)
subject.onNext(.ball)
subject.onNext(.hit)

// Third batter
subject.onNext(.strike)
subject.onNext(.strike)
subject.onNext(.strike) // Would like this to fire as well

Body:
This is a fun exercise.

Buffer

As shown by @daniel-t, this approach takes a .buffer of capacity 3 and when it is full, you know there were 3 strikes.

Counter

In addition to the buffer approach, you can also use a counter:

let subject = PublishSubject<Baseball>()

let strikes = subject.asObservable()
    .filter { $0 == .strike }
let ticker = strikes.map { _ in () }
let counter = ticker.scan(0) { (memo, _) -> Int in memo + 1 }

strikes.withLatestFrom(counter) { strike, count in (strike, count) }
    .filter { _, count in count % 3 == 0 }
    .subscribe(onNext: { _ in print("3 Strikes you're out")
    }).addDisposableTo(bag)

With another operator or two, one could also make the increasing strike counter reset to 0 after 3.

Index as Counter

let subject = PublishSubject<Baseball>()

let strikes = subject.asObservable()
    .filter { $0 == .strike }
// Unlike the counter, this starts at 0 and reports "% 3 == 0" too early.
strikes.mapWithIndex { _, index in index + 1 }
    .filter { $0 % 3 == 0 }
    .subscribe(onNext: { _ in print("3 Strikes you're out")
    }).addDisposableTo(bag)


问:
Does Postgres guarantee to lock rows in the order of supplied update-statements?
I like to do batch updates to Postgres. Sometimes, the batch may contain update-statements to the same record. (*)

To this end I need to be sure that Postgres locks rows based on the order in which the update-statements are supplied.

Is this guaranteed?

To be clear, I'm sending a sequence of single row update-statements, so not a single multi-row update-statement. E.g.:

```<code>update A set x='abc', dt='<timeN>' where id='123';
update A set x='def', dt='<timeN+1>' where id='123';
update A set x='ghi', dt='<timeN+2>' where id='123';
</code>```

*) This might seem redundant: just only save the last one. However, I have defined an after-trigger on the table so history is created in a different table. Therefore I need the multiple updates.

答:
The rows will definitely be locked in the order of the UPDATE statements.

Moreover, locks only affect concurrent transactions, so if all the UPDATEs take place in one database session, you don't have to be afraid to get blocked by a lock.

Body:
I like to do batch updates to Postgres. Sometimes, the batch may contain update-statements to the same record. (*)

To this end I need to be sure that Postgres locks rows based on the order in which the update-statements are supplied.

Is this guaranteed?

To be clear, I'm sending a sequence of single row update-statements, so not a single multi-row update-statement. E.g.:

update A set x='abc', dt='<timeN>' where id='123';
update A set x='def', dt='<timeN+1>' where id='123';
update A set x='ghi', dt='<timeN+2>' where id='123';

*) This might seem redundant: just only save the last one. However, I have defined an after-trigger on the table so history is created in a different table. Therefore I need the multiple updates.


问:
iOS - Iteration in some folders
I need to get some files in definite folders. For this purpose I use this answer and it works fine. However, my folder structure is like:

```<code>Documents/
  idOfFolder1/
    images/
      image1.jpg
      image2.png
    sounds/
      sound1.mp3
    files/
      file1.pdf
  idOfFolder2/
    images/
      ...
</code>```

I need to iterate through all folders having a specific id and get images. Since the answer written iterates through all folders it takes much more time than normal (we have many files). To optimize process, I want to skip "sounds" and "files" folders. Is there a way to handle this?

Thank you!

答:
If you don't like to use NSPredicate, following code will also do what you want,

(this code will directly access the folders with given ids and pick everything inside the images folders)

```<code>-(void) printImagesOfFolders:(NSArray *) folderIds{

    for(NSString *folderId in folderIds){

        NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
        NSURL *documentsURL = [paths lastObject];
        NSString * imageFolderPath = [NSString stringWithFormat:@"%@/images", folderId];

        NSURL *rootURL = [documentsURL URLByAppendingPathComponent:imageFolderPath];
        NSFileManager *fm = [NSFileManager defaultManager];
        NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:rootURL
                                        includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                           options:NSDirectoryEnumerationSkipsHiddenFiles
                                                      errorHandler:nil];

        for (NSURL *url in dirEnumerator) {

            NSLog(@"url: %@", url);

        }

    }

}
</code>```

How to use it

```<code>[self printImagesOfFolders:@[@"idOfFolder1",@"idOfFolder2",@"idOfFolder3",@"idOfFolder4"]];
</code>```

Title: iOS - Iteration in some folders

Body:
I need to get some files in definite folders. For this purpose I use this answer and it works fine. However, my folder structure is like:

Documents/
  idOfFolder1/
    images/
      image1.jpg
      image2.png
    sounds/
      sound1.mp3
    files/
      file1.pdf
  idOfFolder2/
    images/
      ...

I need to iterate through all folders having a specific id and get images. Since the answer written iterates through all folders it takes much more time than normal (we have many files). To optimize process, I want to skip "sounds" and "files" folders. Is there a way to handle this?

Thank you!

Body:
If you don't like to use NSPredicate, following code will also do what you want,

(this code will directly access the folders with given ids and pick everything inside the images folders)

-(void) printImagesOfFolders:(NSArray *) folderIds{

    for(NSString *folderId in folderIds){

        NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
        NSURL *documentsURL = [paths lastObject];
        NSString * imageFolderPath = [NSString stringWithFormat:@"%@/images", folderId];

        NSURL *rootURL = [documentsURL URLByAppendingPathComponent:imageFolderPath];
        NSFileManager *fm = [NSFileManager defaultManager];
        NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:rootURL
                                        includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                           options:NSDirectoryEnumerationSkipsHiddenFiles
                                                      errorHandler:nil];

        for (NSURL *url in dirEnumerator) {

            NSLog(@"url: %@", url);

        }

    }

}

How to use it

[self printImagesOfFolders:@[@"idOfFolder1",@"idOfFolder2",@"idOfFolder3",@"idOfFolder4"]];


问:
Converting map into tuple
I am loading hbase table using pig.

```<code>product = LOAD 'hbase://product' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('a:*', '-loadKey true') AS (id:bytearray, a:map[])
</code>```

The relation product has a tuple that has map in it. I want to convert the map data into tuple
Here is the sample..

```<code>grunt>dump product;
06:177602927,[cloud_service#true,wvilnk#true,cmpgeo#true,cmplnk#true,webvid_standard#true,criteria_search#true,typeahead_search#true,aasgbr#true,lnkmin#false,aasdel#true,aasmcu#true,aasvia#true,lnkalt#false,aastlp#true,cmpeel#true,aasfsc#true,aasser#true,aasdhq#true,aasgbm#true,gboint#true,lnkupd#true,aasbig#true,webvid_basic#true,cmpelk#true]
06:177927527,[cloud_service#true,wvilnk#true,cmpgeo#true,cmplnk#true,webvid_standard#true,criteria_search#true,typeahead_search#true,aasgbr#false,lnkmin#false,aasdel#false,aasmcu#false,aasvia#false,lnkalt#false,aastlp#true,cmpeel#true,aasfsc#false,aasser#false,aasdhq#true,aasgbm#false,gboint#true,lnkupd#true,aasbig#false,webvid_basic#true,cmpelk#true,blake#true]
</code>```

I want to convert each tuple into individual records like below

```<code>177602927,cloud_service,true
177602927,wvilnk,true
177602927,cmpgeo,true
177602927,cmpgeo,true
</code>```

I am pretty new to pig and perhaps this is my first time to do something with Pig Latin. Any help is much appreciated.

答:
I was able to find a fix for my problem.

I used a UDF called MapEntriesToBag which will convert all the maps into bags.
Here is my code.

```<code>>register /your/path/to/this/Jar/Pigitos-1.0-SNAPSHOT.jar
>DEFINE MapEntriesToBag pl.ceon.research.pigitos.pig.udf.MapEntriesToBag();
>product = LOAD 'hbase://product' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('a:*', '-loadKey true') AS (id:bytearray, a:map[])
>b = foreach product generate flatten(SUBSTRING($0,3,12)), flatten(MapEntriesToBag($1));
</code>```

The UDF is available in the Jar Pigitos-1.0-SNAPSHOT.jar. You can download this jar from here

For more information you can refer to this link. It has more interesting UDF's related to Map datatype.

Title: Converting map into tuple

Body:
I am loading hbase table using pig.

product = LOAD 'hbase://product' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('a:*', '-loadKey true') AS (id:bytearray, a:map[])

The relation product has a tuple that has map in it. I want to convert the map data into tuple
Here is the sample..

grunt>dump product;
06:177602927,[cloud_service#true,wvilnk#true,cmpgeo#true,cmplnk#true,webvid_standard#true,criteria_search#true,typeahead_search#true,aasgbr#true,lnkmin#false,aasdel#true,aasmcu#true,aasvia#true,lnkalt#false,aastlp#true,cmpeel#true,aasfsc#true,aasser#true,aasdhq#true,aasgbm#true,gboint#true,lnkupd#true,aasbig#true,webvid_basic#true,cmpelk#true]
06:177927527,[cloud_service#true,wvilnk#true,cmpgeo#true,cmplnk#true,webvid_standard#true,criteria_search#true,typeahead_search#true,aasgbr#false,lnkmin#false,aasdel#false,aasmcu#false,aasvia#false,lnkalt#false,aastlp#true,cmpeel#true,aasfsc#false,aasser#false,aasdhq#true,aasgbm#false,gboint#true,lnkupd#true,aasbig#false,webvid_basic#true,cmpelk#true,blake#true]

I want to convert each tuple into individual records like below

177602927,cloud_service,true
177602927,wvilnk,true
177602927,cmpgeo,true
177602927,cmpgeo,true

I am pretty new to pig and perhaps this is my first time to do something with Pig Latin. Any help is much appreciated.

Body:
I was able to find a fix for my problem.

I used a UDF called MapEntriesToBag which will convert all the maps into bags.
Here is my code.

>register /your/path/to/this/Jar/Pigitos-1.0-SNAPSHOT.jar
>DEFINE MapEntriesToBag pl.ceon.research.pigitos.pig.udf.MapEntriesToBag();
>product = LOAD 'hbase://product' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('a:*', '-loadKey true') AS (id:bytearray, a:map[])
>b = foreach product generate flatten(SUBSTRING($0,3,12)), flatten(MapEntriesToBag($1));

The UDF is available in the Jar Pigitos-1.0-SNAPSHOT.jar. You can download this jar from here

For more information you can refer to this link. It has more interesting UDF's related to Map datatype.


问:
Can't open library window in interface builder
I am using a MacBook Pro installed with Xcode 3.2.5 and iOS SDK 4.2. When I launch Interface Builder by clicking the nib file, then I do not see any library window. Anyone has idea on why it is behaving so?

Thanks!

答: If you choose Library from the Tools menu, or if you press ⇧⌘L, does it not appear?


问:
If I press one key and then another too fast, my pygame sprite stops moving
I'm new to pygame so my code is a bit messy but I hope you can help me. When I make a sprite move it works fine, but if I switch keys really fast, or if I press the jump button and let go, my sprite stops moving.</p>

```<code>import shelve
import sys, pygame, pygame.mixer
import time
from pygame.locals import *
import random
pygame.init()
shelfFile = shelve.open('save_game')

#screen
sise = width, hight = 700, 600
red = 30,30,30
screen = pygame.display.set_mode(sise)

pygame.display.set_caption('Thing')

#varuables
background = pygame.image.load('background.png')
player = pygame.image.load('you.png')
enemy1 = pygame.image.load('enemy1.png')
clock = pygame.time.Clock()
px = shelfFile['px']
py = shelfFile['py']
health = shelfFile['health']
x2 = 0

x = 0
y = 0
u = 0
d = 0
t = 0
r = 0

ex = 0
ey = 0

cutseane = shelfFile ['cutseane']
black = 255,255,255

Punch = False

color = 255,0,0
radius = 5

room = shelfFile['room']

ehealth = shelfFile['ehealth']

while True:
    pygame.event.get()
    if jump == 1:
        y = -20
    if py <= 200:
        jump = 2
    if jump == 2:
        y = +20
    if py >= 480:
        py = 480

                #The Wall
    if px <= 0:
        px = 0
    if px >= 630:
        px = 630
    pygame.display.flip()
    screen.blit(background,(1,1))
    screen.blit(player,(px,py))
    #if ehealth >= 1:
        #screen.blit(enemy1,(ex,ey))
    #else:
        #ex = 0
        #ey = 0
                px = px + x
    py = py + y
    clock.tick(30)
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()

        if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
            shelfFile['px'] = px
            shelfFile['py'] = py
            shelfFile['health'] = health
            shelfFile['ehealth'] = ehealth
            shelfFile['cutseane'] = cutseane
            shelfFile['room'] = room
            shelfFile.close()
            pygame.quit(); sys.exit();

                    #Player Movement
        elif event.type == pygame.KEYDOWN:
            if keys [pygame.K_0]:
                health -= 1
                text = 1
                shelfFile['text'] = text
            elif event.key == pygame.K_RIGHT:
                x = -15
            elif event.key == pygame.K_LEFT:
                x = +15
            elif event.key == pygame.K_UP:
                y = +15
            elif event.key == pygame.K_DOWN:
                y = -15
        elif event.type == KEYUP:
            if event.key == pygame.K_LEFT and x > 0:
                x = 0
            elif event.key == pygame.K_RIGHT and x < 0:
                x = 0
            elif event.key == pygame.K_UP and x > 0:
                y = 0
            elif event.key == pygame.K_DOWN and x < 0:
                y = 0
</code>```

答:
Your event loop is really messed up and should be restructured. keys = pygame.key.get_pressed() shouldn't be called in the event loop, but in the outer while loop. I've got a minimal example to show you one way to do the movement and event handling (only with the event loop and without key.get_pressed).

```<code>import sys
import pygame

pygame.init()

screen = pygame.display.set_mode((700, 600))
clock = pygame.time.Clock()

player = pygame.Surface((30, 30))
player.fill((120, 240, 90))

px = 100
py = 200
x_speed = 0
y_speed = 0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            # If player is on the ground, jump (in more advanced
            # games you need collision detection instead >= 480).
            if event.key == pygame.K_UP and py >= 480:
                y_speed = -20
            elif event.key == pygame.K_RIGHT:
                x_speed = 10
            elif event.key == pygame.K_LEFT:
                x_speed = -10
        elif event.type == pygame.KEYUP:
            # If player is moving right, stop him.
            if event.key == pygame.K_RIGHT and x_speed > 0:
                x_speed = 0
            # If player is moving left, stop him.
            elif event.key == pygame.K_LEFT and x_speed < 0:
                x_speed = 0

    # Don't jump too high.
    if py <= 200:
        y_speed = 20
    # Don't go below y = 480.
    if py >= 480:
        py = 480

    # Move the player.
    px += x_speed
    py += y_speed
    # The Wall.
    if px <= 0:
        px = 0
    if px >= 630:
        px = 630

    screen.fill((50, 50, 50))
    screen.blit(player, (px, py))

    pygame.display.flip()
    clock.tick(30)
</code>```

Body:
I'm new to pygame so my code is a bit messy but I hope you can help me. When I make a sprite move it works fine, but if I switch keys really fast, or if I press the jump button and let go, my sprite stops moving.

import shelve
import sys, pygame, pygame.mixer
import time
from pygame.locals import *
import random
pygame.init()
shelfFile = shelve.open('save_game')

#screen
sise = width, hight = 700, 600
red = 30,30,30
screen = pygame.display.set_mode(sise)

pygame.display.set_caption('Thing')

#varuables
background = pygame.image.load('background.png')
player = pygame.image.load('you.png')
enemy1 = pygame.image.load('enemy1.png')
clock = pygame.time.Clock()
px = shelfFile['px']
py = shelfFile['py']
health = shelfFile['health']
x2 = 0

x = 0
y = 0
u = 0
d = 0
t = 0
r = 0

ex = 0
ey = 0

cutseane = shelfFile ['cutseane']
black = 255,255,255

Punch = False

color = 255,0,0
radius = 5

room = shelfFile['room']

ehealth = shelfFile['ehealth']

while True:
    pygame.event.get()
    if jump == 1:
        y = -20
    if py <= 200:
        jump = 2
    if jump == 2:
        y = +20
    if py >= 480:
        py = 480

                #The Wall
    if px <= 0:
        px = 0
    if px >= 630:
        px = 630
    pygame.display.flip()
    screen.blit(background,(1,1))
    screen.blit(player,(px,py))
    #if ehealth >= 1:
        #screen.blit(enemy1,(ex,ey))
    #else:
        #ex = 0
        #ey = 0
                px = px + x
    py = py + y
    clock.tick(30)
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()

        if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
            shelfFile['px'] = px
            shelfFile['py'] = py
            shelfFile['health'] = health
            shelfFile['ehealth'] = ehealth
            shelfFile['cutseane'] = cutseane
            shelfFile['room'] = room
            shelfFile.close()
            pygame.quit(); sys.exit();

                    #Player Movement
        elif event.type == pygame.KEYDOWN:
            if keys [pygame.K_0]:
                health -= 1
                text = 1
                shelfFile['text'] = text
            elif event.key == pygame.K_RIGHT:
                x = -15
            elif event.key == pygame.K_LEFT:
                x = +15
            elif event.key == pygame.K_UP:
                y = +15
            elif event.key == pygame.K_DOWN:
                y = -15
        elif event.type == KEYUP:
            if event.key == pygame.K_LEFT and x > 0:
                x = 0
            elif event.key == pygame.K_RIGHT and x < 0:
                x = 0
            elif event.key == pygame.K_UP and x > 0:
                y = 0
            elif event.key == pygame.K_DOWN and x < 0:
                y = 0

Body:
Your event loop is really messed up and should be restructured. keys = pygame.key.get_pressed() shouldn't be called in the event loop, but in the outer while loop. I've got a minimal example to show you one way to do the movement and event handling (only with the event loop and without key.get_pressed).

import sys
import pygame

pygame.init()

screen = pygame.display.set_mode((700, 600))
clock = pygame.time.Clock()

player = pygame.Surface((30, 30))
player.fill((120, 240, 90))

px = 100
py = 200
x_speed = 0
y_speed = 0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            # If player is on the ground, jump (in more advanced
            # games you need collision detection instead >= 480).
            if event.key == pygame.K_UP and py >= 480:
                y_speed = -20
            elif event.key == pygame.K_RIGHT:
                x_speed = 10
            elif event.key == pygame.K_LEFT:
                x_speed = -10
        elif event.type == pygame.KEYUP:
            # If player is moving right, stop him.
            if event.key == pygame.K_RIGHT and x_speed > 0:
                x_speed = 0
            # If player is moving left, stop him.
            elif event.key == pygame.K_LEFT and x_speed < 0:
                x_speed = 0

    # Don't jump too high.
    if py <= 200:
        y_speed = 20
    # Don't go below y = 480.
    if py >= 480:
        py = 480

    # Move the player.
    px += x_speed
    py += y_speed
    # The Wall.
    if px <= 0:
        px = 0
    if px >= 630:
        px = 630

    screen.fill((50, 50, 50))
    screen.blit(player, (px, py))

    pygame.display.flip()
    clock.tick(30)


问:
Serving HTML files from Azure Blob for Express.js server
So, I have an Express.js server and an Angular.js front end (Served through express itself and not deployed externally). We have multiple "themes" for the website which can be switched on the fly. Now the theme count is manageable, but we expect it to go into the thousands (maybe even ten thousands)

In the current implementation, we are storing the static theme files (HTML, CSS) in the deployment package itself. With the ever growing number of themes, the deployment package size is growing very quickly.

Now, I am considering moving the themes to an external storage (Azure Blob) and then stream the static content to Express.js from Azure Blob Storage and serve it accordingly.

Will Azure Blob Storage or any other storage be a bottleneck in this case? Or is there a better solution for this "theme" count problem?

答:
Blob storage is a good solution.
If you make the Bob storage public readable, then you can serve the static files directly from blob storage, they don't even have to come via your Express server, thus offloading all that. I often do this with css and have some apps where I serve the entire front end app, including scripts, from blob storage; I just have a single html page served from my main server with script tags pointing to blob storage.
With Angular 1 I just have a build step that bundles all the html templates inside the script package.

Later you can "upgrade" Bob storage to be a proper CDN, meaning you can have all the static stuff served locally to the user.

FWIW, I believe haveibeenpwned serves it's static content from Azure Blob storage.


问:
React redux - componentDidMount fetching vs action
If I use react with redux - does it always necessary to fetch data from the redux action? Or it depends if I need the data to be stateful?

For example: I have a container which displays a user profile page. Can I fetch its data from the componentDidMount?

Thanks.

答:
Yes - this is how you would fetch it if there wasn't redux being used.

If you want to use redux (to make profiles available in general etc.), you should call the action from componentDidMount to properly handle lifecycle events etc.


问:
Database design, for optimized access
I jump straight into the problem, currently I have a table as such

```<code>id | model | CategoryId | etc...
</code>```

Now my new requirement is to have support for multiple categories. So I have two possible solutions in mind but I would like to know problems that both this designs might create. I also know that at most I can have 6 categories, also I can't create a linker table to link product to category.

On first design I would simply create column  CategoryN

```<code>id | model | CategoryId1 | CategoryId2 | CategoryId3 | CategoryId4 | etc...
</code>```

But this would make queries hideous,

```<code>   id | model | CategoryId | etc...
</code>```

My second approach is simply to add product for N categories

```<code>   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 3           | etc...
</code>```

I think queries would be cleaner but not necessarily simpler.
Another aspect is that I am looking at the performance of the queries and it looks like the first approach would be better.
I hope this is clear enough.

Thanks for any suggestions.

答:
I think you're after a many-to-many relationship here.

Basically, you have a model_to_categories table that matches model ids against category ids.

Title: Database design, for optimized access

Body:
I jump straight into the problem, currently I have a table as such

id | model | CategoryId | etc...

Now my new requirement is to have support for multiple categories. So I have two possible solutions in mind but I would like to know problems that both this designs might create. I also know that at most I can have 6 categories, also I can't create a linker table to link product to category.

On first design I would simply create column  CategoryN

id | model | CategoryId1 | CategoryId2 | CategoryId3 | CategoryId4 | etc...

But this would make queries hideous,

   id | model | CategoryId | etc...

My second approach is simply to add product for N categories

   id | model | CategoryId | etc...
   1 | ABC   | 1           | etc...
   2 | ABC   | 2           | etc...
   3 | ABC   | 3           | etc...

I think queries would be cleaner but not necessarily simpler.
Another aspect is that I am looking at the performance of the queries and it looks like the first approach would be better.
I hope this is clear enough.

Thanks for any suggestions.


问:
Unable to subscribe to router events in Aurelia (TypeScript)
There's no reason this shouldn't be working:)

```<code>import {Router, RouterConfiguration} from 'aurelia-router';
import { EventAggregator } from 'aurelia-event-aggregator';
import {autoinject} from 'aurelia-framework';

@autoinject
export class App {
  router: Router;
  ea: EventAggregator;
  navEvent: any;

  constructor(eventAggregator: EventAggregator) {
    this.ea = eventAggregator;
  }

  configureRouter(config: RouterConfiguration, router: Router) {
    config.title = 'Intterra Management';
    config.map([
      { route: ['', 'home'], name: 'home', moduleId: 'home', nav: false, title: '' },
      { route: 'logs', name: 'logs', moduleId: 'logs', nav: true, title: 'Logs' }
    ]);

    this.router = router;
  }

  attached() {
    this.navEvent = this.ea.subscribe('router:navigation:complete', response => {
      localStorage['state'] = location.hash;
    });
  }

  detached() {
    this.navEvent.dispose();
  }
 ...
</code>```

I verified the event is firing when when I navigate, but the subscribed function isn't being called. Any ideas?

答:
No sure if you have found a solution to your problem yet, but try using this.ea directly.

```<code>this.ea.subscribe("router:navigation:complete", response => {
    localStorage['state'] = location.hash;
});
</code>```

Not sure if subscribing to said event in your constructor might help?

Body:
There's no reason this shouldn't be working:)

import {Router, RouterConfiguration} from 'aurelia-router';
import { EventAggregator } from 'aurelia-event-aggregator';
import {autoinject} from 'aurelia-framework';

@autoinject
export class App {
  router: Router;
  ea: EventAggregator;
  navEvent: any;

  constructor(eventAggregator: EventAggregator) {
    this.ea = eventAggregator;
  }

  configureRouter(config: RouterConfiguration, router: Router) {
    config.title = 'Intterra Management';
    config.map([
      { route: ['', 'home'], name: 'home', moduleId: 'home', nav: false, title: '' },
      { route: 'logs', name: 'logs', moduleId: 'logs', nav: true, title: 'Logs' }
    ]);

    this.router = router;
  }

  attached() {
    this.navEvent = this.ea.subscribe('router:navigation:complete', response => {
      localStorage['state'] = location.hash;
    });
  }

  detached() {
    this.navEvent.dispose();
  }
 ...

I verified the event is firing when when I navigate, but the subscribed function isn't being called. Any ideas?

Body:
No sure if you have found a solution to your problem yet, but try using this.ea directly.

this.ea.subscribe("router:navigation:complete", response => {
    localStorage['state'] = location.hash;
});

Not sure if subscribing to said event in your constructor might help?


问:
.net mvc add viewpage by scaffolding throw error There is no store type corresponding to the conceptual side type 'SByte' of primitive type 'SByte'
When I add a viewpage, use by scaffolding, it's throwing an error that

there is no store type corresponding to the conceptual side type 'SByte' of
    primitive type 'SByte'.

below image:

答: Please verify your connection string target the correct database and that is capable of handling the datatype which is in the error specified.</p>


问:
Scalable, Efficient Hierarchical Softmax in Tensorflow?
I'm interested in implementing a hierarchical softmax model that can handle large vocabularies, say on the order of 10M classes. What is the best way to do this to both be scalable to large class counts and efficient? For instance, at least one paper has shown that HS can achieve a ~25x speedup for large vocabs when using a 2-level tree where each node sqrt(N) classes. I'm interested also in a more general version for an arbitrary depth tree with an arbitrary branching factor.

There are a few options that I see here:

1) Run tf.gather for every batch, where we gather the indices and splits. This creates problems with large batch sizes and fat trees where now the coefficients are being duplicated a lot, leading to OOM errors.

2) Similar to #1, we could use tf.embedding_lookup which would keep help with OOM errors but now keeps everything on the CPU and slows things down quite a bit.

3) Use tf.map_fn with parallel_iterations=1 to process each sample separately and go back to using gather. This is much more scalable but does not really get close to the 25x speedup due to the serialization.

Is there a better way to implement HS? Are there different ways for deep and narrow vs. short and wide trees?

答:
You mention that you want GPU-class performance:

but now keeps everything on the CPU and slows things down quite a bit

and wish to use 300-unit hidden size and 10M-word dictionaries.

This means that (assuming float32), you'll need 4 * 300 * 10M * 2 bytes = 24 GB just to store the parameters and the gradient for the output layer.

Hierarchical Softmax (HSM) doesn't reduce the memory requirements - it just speeds up the training.

Realistically, you'll need a lot more GPU memory, because you'll also need to store:

other parameters and their gradients

optimizer data, e.g. velocities in momentum training

activations and backpropagated temporary data

framework-specific overhead

Therefore, if you want to do all computation on GPUs, you'll have no choice but to distribute this layer across multiple high-memory GPUs.

However, you now have another problem:

To make this concrete, let's suppose you have a 2-level HSM with 3K classes, with 3K words per class (9M words in total). You distribute the 3K classes across 8 GPUs, so that each hosts 384 classes.

What if all target words in a batch are from the same 384 classes, i.e. they belong to the same GPU? One GPU will be doing all the work, while the other 7 wait for it.

The problem is that even if the target words in a batch belong to different GPUs, you'll still have the same performance as in the worst-case scenario, if you want to do this computation in TensorFlow (This is because TensorFlow is a "specify-and-run" framework -- the computational graph is the same for the best case and the worst case)

What is the best way to do this to both be scalable to large class counts and efficient?

The above inefficiency of model parallelism (each GPU must process the whole batch) suggests that one should try to keep everything in one place.

Let us suppose that you are either implementing everything on the host, or on 1 humongous GPU.

If you are not modeling sequences, or if you are, but there is only one output for the whole sequence, then the memory overhead from copying the parameters, to which you referred, is negligible compared to the memory requirements described above:

400 == batch size << number of classes == 3K

In this case, you could simply use gather or embedding_lookup (Although the copying is inefficient)

However, if you do model sequences of length, say, 100, with output at every time step, then the parameter copying becomes a big issue.

In this case, I think you'll need to drop down to C++ / CUDA C and implement this whole layer and its gradient as a custom op.


问:
ZBar code scanner ntdll.dll error in delphi
I am trying to scan a image using ZBar and I am working from this code example : http://blog.freehand.com.ua/2013/03/zbar-reading-bar-codes-in-delphi.html

This is the code I currently have :

```<code>procedure TForm1.Button1Click(Sender: TObject);
var zimage : zbar_image_t;
weirdVarArea : SIZE_T;
weirdVarBlob : PByte;
sym: zbar_symbol_t;
begin
  zimage := zbar_image_create;
  zbar_image_set_format(zimage, 'Y800');
  zbar_image_set_size(zimage, Image1.Picture.Width, Image1.Picture.Height);

  weirdVarArea := Image1.Picture.Width * Image1.Picture.Height;
  weirdVarBlob := GetMemory(weirdVarArea);
  zbar_image_set_data(zimage, weirdVarBlob, weirdVarArea, nil);

  zbar_process_image(processor, zimage);

  //  sym := zbar_image_first_symbol(zimage);
  //  ShowMessage(zbar_symbol_get_data(sym));
end;

end.
</code>```

There is one button named "Button1" on the form as well as a image component named "Image1" with a qr code loaded into it.

When I run that code I get the error : Access violation at address 77E57543 in module 'ntdll.dll'. Write of address 000000A4.

The line causing the trouble is zbar_process_image(processor, zimage);

I am not sure how to proceed.

Thanks for your responce, Kobus

答:
Access violation at address 77E57543 in module 'ntdll.dll'. Write of address 000000A4.

This is actually Windows issue. When you get this error, you must find out the restore point when the application was working properly and close Windows automatic updates to prevent the issue happens again. If you cannot solve the issue with this way, you should reinstall your Windows.

Body:
I am trying to scan a image using ZBar and I am working from this code example : http://blog.freehand.com.ua/2013/03/zbar-reading-bar-codes-in-delphi.html

This is the code I currently have :

procedure TForm1.Button1Click(Sender: TObject);
var zimage : zbar_image_t;
weirdVarArea : SIZE_T;
weirdVarBlob : PByte;
sym: zbar_symbol_t;
begin
  zimage := zbar_image_create;
  zbar_image_set_format(zimage, 'Y800');
  zbar_image_set_size(zimage, Image1.Picture.Width, Image1.Picture.Height);

  weirdVarArea := Image1.Picture.Width * Image1.Picture.Height;
  weirdVarBlob := GetMemory(weirdVarArea);
  zbar_image_set_data(zimage, weirdVarBlob, weirdVarArea, nil);

  zbar_process_image(processor, zimage);

  //  sym := zbar_image_first_symbol(zimage);
  //  ShowMessage(zbar_symbol_get_data(sym));
end;

end.

There is one button named "Button1" on the form as well as a image component named "Image1" with a qr code loaded into it.

When I run that code I get the error : Access violation at address 77E57543 in module 'ntdll.dll'. Write of address 000000A4.

The line causing the trouble is zbar_process_image(processor, zimage);

I am not sure how to proceed.

Thanks for your responce, Kobus


问:
Is there any way in Powershell to find ADF slices that completed in last 1 hour for example?
Given certain dataset, I want to find out how many of its slices actually became Ready in last 1 hour (or say 2 hours, it's just an example). This gives me idea of cluster health. Because out of dozens of datasets, if no Ready slice was produced in last couple of hours, it's surely alarming for me.

I know Powershell has a cmdlet to get slice status which returns actual start and end time of slices -- but the problem is it finds that only on the basis of slice information. I don't care if the slice date is 1 year back -- I want the status on the basis of actual start and end time for that slice -- and I want to do it programmatically.

Worst case is -- one will need to get status for all possible slices and then get actual start and end time, but this is very inefficient -- there is also limit on how many API calls one can in an hour.

答:
I think the cmdlet your looking for here is Get-AzureRmDataFactoryActivityWindow this accepts a run window and will return the result of a time slice either Ready, Waiting, Failed etc.

Example of use:

```<code>Get-AzureRmDataFactoryActivityWindow `
    -DataFactoryName $ADFName.DataFactoryName `
    -ResourceGroupName $ResourceGroup `
    | ? {$_.WindowStart -ge $Now} `
    | SELECT ActivityName, ActivityType, WindowState, RunStart, InputDatasets, OutputDatasets `
    | Sort-Object ActivityName
</code>```

Use this with the required params to return a list of the information you want. I might then stick it into a SQL table for wider monitoring etc. But you could use an array in PowerShell to get the count value and produce the alert. Next wrap it up in something that polls on the hour maybe.

Here's a link to all ADF PowerShell cmdlets available in the Azure module: https://learn.microsoft.com/en-gb/powershell/module/azurerm.datafactories/?view=azurermps-4.0.0

Hope this helps

Body:
I think the cmdlet your looking for here is Get-AzureRmDataFactoryActivityWindow this accepts a run window and will return the result of a time slice either Ready, Waiting, Failed etc.

Example of use:

Get-AzureRmDataFactoryActivityWindow `
    -DataFactoryName $ADFName.DataFactoryName `
    -ResourceGroupName $ResourceGroup `
    | ? {$_.WindowStart -ge $Now} `
    | SELECT ActivityName, ActivityType, WindowState, RunStart, InputDatasets, OutputDatasets `
    | Sort-Object ActivityName

Use this with the required params to return a list of the information you want. I might then stick it into a SQL table for wider monitoring etc. But you could use an array in PowerShell to get the count value and produce the alert. Next wrap it up in something that polls on the hour maybe.

Here's a link to all ADF PowerShell cmdlets available in the Azure module: https://learn.microsoft.com/en-gb/powershell/module/azurerm.datafactories/?view=azurermps-4.0.0

Hope this helps


问:
XSTREAM array converter
I want to convert below XML to objects. I

```<code><authentication>
    <name>Reese Rideout</name>
    <shows type="array">
        <show>stage</show>
        <show>youtube</show>
    </shows>
</authentication>
</code>```

I have Authentication class with List<Show> shows. I believe I will need to use the array converter. However, I do not understand how to use it and am not finding any documents.

Kindly suggest how could I parse this into my object graph.

答:
For

```<code> <authentication>
      <name>Reese Rideout</name>
      <shows type="array">
         <show>stage</show>
         <show>youtube</show>
       </shows>
    </authenticatoin>
</code>```

you can have

```<code>class Authentication{
String name;
List<Show> shows;
}

class Show{
List<String> show;
}
</code>```

You will have to use aliasing

```<code>xstream.alias("authentication", Authentication.class);
xstream.alias("Show", Show.class);
</code>```

Title: XSTREAM array converter

Body:
I want to convert below XML to objects. I

<authentication>
    <name>Reese Rideout</name>
    <shows type="array">
        <show>stage</show>
        <show>youtube</show>
    </shows>
</authentication>

I have Authentication class with List<Show> shows. I believe I will need to use the array converter. However, I do not understand how to use it and am not finding any documents.

Kindly suggest how could I parse this into my object graph.

Body:
For

 <authentication>
      <name>Reese Rideout</name>
      <shows type="array">
         <show>stage</show>
         <show>youtube</show>
       </shows>
    </authenticatoin>

you can have

class Authentication{
String name;
List<Show> shows;
}

class Show{
List<String> show;
}

You will have to use aliasing

xstream.alias("authentication", Authentication.class);
xstream.alias("Show", Show.class);


问:
DYGRAPHS: Show warning when disable small graph in range selector
I disabled the small graph in range selector using:
showInRangeSelector: false,
but I'm getting warning sign like this:
I can't seem to find where is the bug.

Updated with code:

```<code><html>
<head>
<link href="http://dygraphs.com/2.0.0/dygraph.css" rel="stylesheet"/>
<script src="http://dygraphs.com/2.0.0/dygraph.js"></script>
<div id="hello" class="chart"></div>
</head>
<body>
<script type = "text/javascript">

var hello = [
            [new Date("2016-03-06"),[10,20,30],[11,11,11]],
            [new Date("2016-03-07"),[10,20,30],[15,15,15]],
            [new Date("2016-03-08"),[10,20,30],[32,32,32]],
            [new Date("2016-03-09"),[10,20,30],[18,18,18]],
            [new Date("2016-03-10"),[10,20,30],[26,26,26]],
            [new Date("2016-03-11"),[10,20,30],[31,31,31]],
            [new Date("2016-03-12"),[10,20,30],[9,9,9]],
        ],

a = new Dygraph(
    document.getElementById("hello"),hello,
    {
        labels: [ "Date", "Mean" , "Scatter"],
        customBars: true,
        showRangeSelector: true,
        showInRangeSelector : false,
        interactionModel: Dygraph.defaultInteractionModel,
        series: {
            "Mean" : {
                drawPoints: false,
                color: "#585858",
            },
            "Scatter" : {
                drawPoints: true,
                pointSize: 3,
                strokeWidth: 0,
            }
        },
    }
);
</script>
</code>```

Thank you :)

I have to add extra wording because the post is mostly codes and I can't post it :P

答:
I don´t clearly understand why you want to do this, but maybe this is a solution. You have to think in preprocessing the info before creating the dygraph. This way you can show the rangeselector only if any of the series is going to be shown.</p>

```<code>var showMeanInRangeSelector = false; // or true
var showScatterInRangeSelector = false; // or true
var rangeSelectorVisible = showMeanInRangeSelector || showScatterInRangeSelector;

a = new Dygraph(document.getElementById("hello"),hello,
  {
    labels: [ "Date", "Mean" , "Scatter"],
    customBars: true,
    showRangeSelector: rangeSelectorVisible,
    interactionModel: Dygraph.defaultInteractionModel,
    series: {
        "Mean" : {
            drawPoints: false,
            color: "#585858",
            showInRangeSelector : showMeanInRangeSelector
        },
        "Scatter" : {
            drawPoints: true,
            pointSize: 3,
            strokeWidth: 0,
            showInRangeSelector : showScatterInRangeSelector
        }
    },
  }
);
</code>```

Body:
I disabled the small graph in range selector using:
showInRangeSelector: false,
but I'm getting warning sign like this:
I can't seem to find where is the bug.

Updated with code:

<link href="http://dygraphs.com/2.0.0/dygraph.css" rel="stylesheet"/>

Thank you :)

I have to add extra wording because the post is mostly codes and I can't post it :P

Body:
I don´t clearly understand why you want to do this, but maybe this is a solution. You have to think in preprocessing the info before creating the dygraph. This way you can show the rangeselector only if any of the series is going to be shown.

var showMeanInRangeSelector = false; // or true
var showScatterInRangeSelector = false; // or true
var rangeSelectorVisible = showMeanInRangeSelector || showScatterInRangeSelector;

a = new Dygraph(document.getElementById("hello"),hello,
  {
    labels: [ "Date", "Mean" , "Scatter"],
    customBars: true,
    showRangeSelector: rangeSelectorVisible,
    interactionModel: Dygraph.defaultInteractionModel,
    series: {
        "Mean" : {
            drawPoints: false,
            color: "#585858",
            showInRangeSelector : showMeanInRangeSelector
        },
        "Scatter" : {
            drawPoints: true,
            pointSize: 3,
            strokeWidth: 0,
            showInRangeSelector : showScatterInRangeSelector
        }
    },
  }
);


问:
Html/Css dynamic centering
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="center-container">
      <div class="inner-container">
          <div class="group-container">
              <div class="element"></div>
              <div class="element"></div>
              <div class="element"></div>
          </div>
          <div class="group-container">
              <div class="element"></div>
              <div class="element"></div>
              <div class="element"></div>
          </div>
      </div>
  </div>
</div></code>```

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)

答:
You can align them by setting text-align: center; to parent as they are inline-block elements by default they are align to the left.

```<code>.inner-container {
    display: inline-block;
    text-align: center;
}
</code>```

.container {
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container {
  display: inline-block;
  text-align: center;
}

.group-container {
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="center-container">
    <div class="inner-container">
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
    </div>
  </div>
</div></code>```

Title: Html/Css dynamic centering

Body:
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)

Body:
You can align them by setting text-align: center; to parent as they are inline-block elements by default they are align to the left.

.inner-container {
    display: inline-block;
    text-align: center;
}

.container {
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container {
  display: inline-block;
  text-align: center;
}

.group-container {
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}

<div class="container">
  <div class="center-container">
    <div class="inner-container">
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
      <div class="group-container">
        <div class="element"></div>
        <div class="element"></div>
        <div class="element"></div>
      </div>
    </div>
  </div>
</div>


问:
Error using lodash in angular2
I'm trying to use lodash in angular 2.4.0

angular-cli : "@angular/cli": "1.0.0-rc.4",

Tried to import like this
import * as _ from 'lodash';

Also tried

```<code>npm install --save lodash

npm install --save @types/lodash
</code>```

package.json

```<code>{
  "name": "travelz",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.1.3",
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "@types/lodash": "^4.14.37",
    "core-js": "^2.4.1",
    "intl": "^1.2.5",
    "lodash": "^4.16.4",
    "rxjs": "^5.1.0",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "^1.0.0-rc.4",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.0.0"
  }
}
</code>```

getting these errors:

```<code>C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8599,32): ',' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8602,14): ']' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8602,15): ';' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,26): ',' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,42): '(' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,61): ',' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,66): ')' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8607,15): ';' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8607,25): Declaration or statement expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8608,23): ')' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8608,46): '(' expected.)
</code>```

Can anyone please help?

答:
need to install the lodash under @types. </p>

```<code>$ npm install --save lodash

$ npm install --save @types/lodash
</code>```

<p>Then import it like this </p>

```<code>import * as _ from "lodash";
</code>```

Title: Error using lodash in angular2

Body:
I'm trying to use lodash in angular 2.4.0

angular-cli : "@angular/cli": "1.0.0-rc.4",

Tried to import like this
import * as _ from 'lodash';

Also tried

npm install --save lodash

npm install --save @types/lodash

package.json

{
  "name": "travelz",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.1.3",
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "@types/lodash": "^4.14.37",
    "core-js": "^2.4.1",
    "intl": "^1.2.5",
    "lodash": "^4.16.4",
    "rxjs": "^5.1.0",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "^1.0.0-rc.4",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.0.0"
  }
}

getting these errors:

C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8599,32): ',' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8602,14): ']' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8602,15): ';' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,26): ',' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,42): '(' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,61): ',' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8605,66): ')' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8607,15): ';' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8607,25): Declaration or statement expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8608,23): ')' expected.)
C:/xampp/htdocs/travelz/node_modules/@types/lodash/index.d.ts (8608,46): '(' expected.)

Can anyone please help?

Body:
need to install the lodash under @types.

$ npm install --save lodash

$ npm install --save @types/lodash

Then import it like this

import * as _ from "lodash";