问:
Rails: Inspect an array in template engine
I am maintaining a 5.2 rails app and I came across the two lines below in the template:

```<code><%
clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })
all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }
%>
</code>```

I have like to somehow inspect all_students to see what is in the array.  Something like console log.  Any suggestions on how I can do that?

答:
You could use the debug view helper. Note that you have to change to output mode by changing <% to <%=.

```<code><%=
clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })
all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }
debug(all_students)
%>
</code>```

Sidenote: Loading and transforming data is usually done in the controller or even in the model when possible. And I would argue that those lines in a view are a code smell and make the view much harder to maintain and potentially to reuse. I suggest moving those lines into the controller method and just calling the instance variables in the view like this:

```<code># in the controller method:
@clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })
@all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }

# in the view
<%= debug(@all_students) %>
</code>```

Body:
I am maintaining a 5.2 rails app and I came across the two lines below in the template:

<%
clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })
all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }
%>

I have like to somehow inspect all_students to see what is in the array.  Something like console log.  Any suggestions on how I can do that?

Body:
You could use the debug view helper. Note that you have to change to output mode by changing <% to <%=.

<%=
clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })
all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }
debug(all_students)
%>

Sidenote: Loading and transforming data is usually done in the controller or even in the model when possible. And I would argue that those lines in a view are a code smell and make the view much harder to maintain and potentially to reuse. I suggest moving those lines into the controller method and just calling the instance variables in the view like this:

# in the controller method:
@clazzes = Clazz.joins(:staffs).includes(clazz_students: :student).where(staffs: { id: @staff.id })
@all_students = clazzes.flat_map { |clazz| clazz.clazz_students.map(&:student) }

# in the view
<%= debug(@all_students) %>


来源: stackexchange

问:
How to ignore Login for another Route using react-router-dom v5
Here I have a already built vuexy template where it has a setup like if user gets logout it routed to the /login , but I'm setting up Forgot Password / Functionality where user will only have email to make post request and in this case I want to route to another route like /password-reset-request , Now this setup is preventing me to achieve it, anybody knows how to do that .

They setup is like that using "react-router-dom": "^5.2.0",
this link is in login page

```<code><Link className='brand-logo mb-0' to='/password-reset-request' onClick={e => e.preventDefault()}>
        <span className='brand-logo mb-0'>
          Forgot Password ?
        </span>
        </Link>
</code>```

EDIT :

```<code>export const authSlice = createSlice({
  name: 'authentication',
  initialState: {
    userData: initialUser()
  },
  reducers: {
    handleLogin: (state, action) => {
      state.userData = action.payload
      state[config.storageTokenKeyName] = action.payload[config.storageTokenKeyName]
      state[config.storageRefreshTokenKeyName] = action.payload[config.storageRefreshTokenKeyName]
      localStorage.setItem('userData', JSON.stringify(action.payload))
      localStorage.setItem(config.storageTokenKeyName, JSON.stringify(action.payload.accessToken))
      localStorage.setItem(config.storageRefreshTokenKeyName, JSON.stringify(action.payload.refreshToken))
    },
    handleLogout: state => {
      state.userData = {}
      state[config.storageTokenKeyName] = null
      state[config.storageRefreshTokenKeyName] = null
      // ** Remove user, accessToken & refreshToken from localStorage
      localStorage.removeItem('userData')
      localStorage.removeItem(config.storageTokenKeyName)
      localStorage.removeItem(config.storageRefreshTokenKeyName)
    }
  }
})

export const { handleLogin, handleLogout } = authSlice.actions

export default authSlice.reducer
</code>```

If handleLogout called then it redirects to /login

```<code>{
    path: '/login',
    component: lazy(() => import('../../views/Login')),
    layout: 'BlankLayout', //
    meta: {
      authRoute: true
    }
  },
{
    path: '/password-reset-request',
    component: lazy(() => import('../../views/AuthComponents/ForgotPassword'))
  },
</code>```

My main point is if userData is not in local storage then user can also go to /loing and /password-reset-request if he wants to.

答:
I think the problem is that, in your reducer you've only 2 options login and logout and in case user is not logged in, will not be able to access other pages, there are 3 ways to solve it:

Before redirecting the user to log in check the route he/she is trying to access

you can use a private route for authentication

you can create middleware with high order function to check authentication instead of reducer

ContentLicense: CC BY-SA 4.0

Body:
Here I have a already built vuexy template where it has a setup like if user gets logout it routed to the /login , but I'm setting up Forgot Password / Functionality where user will only have email to make post request and in this case I want to route to another route like /password-reset-request , Now this setup is preventing me to achieve it, anybody knows how to do that .

They setup is like that using "react-router-dom": "^5.2.0",
this link is in login page

<Link className='brand-logo mb-0' to='/password-reset-request' onClick={e => e.preventDefault()}>

          Forgot Password ?

        </Link>

EDIT :

export const authSlice = createSlice({
  name: 'authentication',
  initialState: {
    userData: initialUser()
  },
  reducers: {
    handleLogin: (state, action) => {
      state.userData = action.payload
      state[config.storageTokenKeyName] = action.payload[config.storageTokenKeyName]
      state[config.storageRefreshTokenKeyName] = action.payload[config.storageRefreshTokenKeyName]
      localStorage.setItem('userData', JSON.stringify(action.payload))
      localStorage.setItem(config.storageTokenKeyName, JSON.stringify(action.payload.accessToken))
      localStorage.setItem(config.storageRefreshTokenKeyName, JSON.stringify(action.payload.refreshToken))
    },
    handleLogout: state => {
      state.userData = {}
      state[config.storageTokenKeyName] = null
      state[config.storageRefreshTokenKeyName] = null
      // ** Remove user, accessToken & refreshToken from localStorage
      localStorage.removeItem('userData')
      localStorage.removeItem(config.storageTokenKeyName)
      localStorage.removeItem(config.storageRefreshTokenKeyName)
    }
  }
})

export const { handleLogin, handleLogout } = authSlice.actions

export default authSlice.reducer

If handleLogout called then it redirects to /login

{
    path: '/login',
    component: lazy(() => import('../../views/Login')),
    layout: 'BlankLayout', //
    meta: {
      authRoute: true
    }
  },
{
    path: '/password-reset-request',
    component: lazy(() => import('../../views/AuthComponents/ForgotPassword'))
  },

My main point is if userData is not in local storage then user can also go to /loing and /password-reset-request if he wants to.


问:
Unable to connect to AWS RDS server: could not connect to server: Connection timed out (0x0000274C/10060)
I am trying to connect to AWS RDS database using pgAdmin4, I encounter and error:

```<code>Unable to connect to server:
could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "database-1.xxxx.eu-west-2.rds.amazonaws.com" (xx.xxx.xxx.xx) and accepting TCP/IP connections on port 5432?
</code>```

I have tried to Allow Public Accessibility and InBound Rules from my IP. But I am still getting the error? What seems to be the issue?

答:
I was facing the same error but for the MySQL database in rds. What I did was, I
went to http://checkip.amazonaws.com/ and checked the IP shown. I copied that IP and created a new security group by adding two rules, one is your standard all traffic rule, and the second is the one with custom IP which you just copied. Then went to rds and changed VPC security grp to both default and the one I just created. Do this and try to connect again. It worked for me</p>

Body:
I am trying to connect to AWS RDS database using pgAdmin4, I encounter and error:

Unable to connect to server:
could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "database-1.xxxx.eu-west-2.rds.amazonaws.com" (xx.xxx.xxx.xx) and accepting TCP/IP connections on port 5432?

I have tried to Allow Public Accessibility and InBound Rules from my IP. But I am still getting the error? What seems to be the issue?


问:
How can I update remote data list when data updated?

Select in A Screen

navigate to B Screen

edit the product info in B Screen

push Save Button, when update success, navigate up to A Screen

A Screen show update list

Screen

```<code>sealed class Screen (
    val route: String
) {
    object List: Screen("product_list") //-->A Screen
    object EditProduct: Screen("edit_product") //-->B Screen
}
</code>```

NavHost in MainActivity onCreate

```<code>        NavHost(navController = navController, startDestination = Screen.Splash.route) {

            composable(route = Screen.List.route) {
                ListScreen()
            }
            composable(route = Screen.EditProduct.route) {
                EditProductScreen()
            }
</code>```

A is a screen that brings up remote data and represents the list, and B contains detailed information about the product selected from A.

After entering the information about the product in B, I would like to update the list of A to show the revised information when I return to A by navigate up.

In this case, how should I deal with it?

```<code>LaunchedEffect(true) {
    viewModel.eventFlow.collectLatest { event ->
        when(event) {
            is UiEvent.SaveTask -> {
                //previousBackStackEntry?.savedStateHandle?.set<Boolean>("save_result", true)
                onSave()
            }
        }
    }
}
</code>```

when I called onSave() --navcontroller::popBackStack,
navigate to A Screen, but list isn't update

答:
You cal pass a callback to your EditProductScreen and call navController.popBackStack() along with your list update code in this callback.

```<code>@Composable
fun EditProductScreen(onSave: () -> Unit) {
    Button(onClick = onSave) {
    }
}
</code>```
```<code>composable(route = Screen.EditProduct.route) {
    EditProductScreen(
        onSave = {
            navController.popBackStack()
            // update your list
        }
    )
}
</code>```

Body:
Select in A Screen

navigate to B Screen

edit the product info in B Screen

push Save Button, when update success, navigate up to A Screen

A Screen show update list

Screen

sealed class Screen (
    val route: String
) {
    object List: Screen("product_list") //-->A Screen
    object EditProduct: Screen("edit_product") //-->B Screen
}

NavHost in MainActivity onCreate

        NavHost(navController = navController, startDestination = Screen.Splash.route) {

            composable(route = Screen.List.route) {
                ListScreen()
            }
            composable(route = Screen.EditProduct.route) {
                EditProductScreen()
            }

A is a screen that brings up remote data and represents the list, and B contains detailed information about the product selected from A.

After entering the information about the product in B, I would like to update the list of A to show the revised information when I return to A by navigate up.

In this case, how should I deal with it?

LaunchedEffect(true) {
    viewModel.eventFlow.collectLatest { event ->
        when(event) {
            is UiEvent.SaveTask -> {
                //previousBackStackEntry?.savedStateHandle?.set<Boolean>("save_result", true)
                onSave()
            }
        }
    }
}

when I called onSave() --navcontroller::popBackStack,
navigate to A Screen, but list isn't update

Body:
You cal pass a callback to your EditProductScreen and call navController.popBackStack() along with your list update code in this callback.

@Composable
fun EditProductScreen(onSave: () -> Unit) {
    Button(onClick = onSave) {
    }
}

composable(route = Screen.EditProduct.route) {
    EditProductScreen(
        onSave = {
            navController.popBackStack()
            // update your list
        }
    )
}


问:
plutter problem: My app name is not showing same in mobile deivce overview

My mobile app name is CWC(Khushi) but in my mobile device overview section is showing flutter demo. I dont know why?

My mobile app name is CWC(Khushi) but in my mobile device overview section is showing flutter demo. I dont know why?
My mobile app name is CWC(Khushi) but in my mobile device overview section is showing flutter demo. I dont know why?

this is my pubspec.yaml file

```<code>name: cwc
description: We are a Community Owned & Community Driven Movement. Our Innovative Wellness Ecosystem is led by Doctors, Health Heroes, Support Groups, Health Entrepreneurs and Pros, Wellness Product cum Service Providers – powered by Tech Platform and App to Scale, Access Content and Engage.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  google_fonts: ^2.1.0
  http: ^0.13.4
  shared_preferences: ^2.0.8
  fluttertoast: ^8.0.8
  image_picker: ^0.8.3+2
  url_launcher: ^6.0.18
  google_sign_in: ^5.2.2
  firebase_auth: ^3.3.5
  flutter_facebook_auth: ^4.0.0
  sign_in_with_apple: ^3.3.0
  skeletons: ^0.0.3
  flutter_login_facebook: ^1.2.0
  intl: ^0.17.0
  country_calling_code_picker: ^2.0.0
  share: ^2.0.4
  flutter_inappwebview: ^5.3.2
  photo_view: ^0.13.0
  syncfusion_flutter_pdfviewer: ^19.4.48-beta
  better_player: ^0.0.81
  audioplayers: ^0.18.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons: ^0.9.2
flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/app_icon.png"
  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

</code>```

this is my menifest file

```<code>  <application
        android:label="Khushi (CWC)"
        android:icon="@mipmap/launcher_icon"
       android:usesCleartextTraffic="true">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />

       <meta-data android:name="com.facebook.sdk.ApplicationId"
           android:value="@string/facebook_app_id"/>

       <activity android:name="com.facebook.FacebookActivity"
           android:configChanges=
               "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
           android:label="@string/app_name" />
       <activity
           android:name="com.facebook.CustomTabActivity"
           android:exported="true">
           <intent-filter>
               <action android:name="android.intent.action.VIEW" />
               <category android:name="android.intent.category.DEFAULT" />
               <category android:name="android.intent.category.BROWSABLE" />
               <data android:scheme="@string/fb_login_protocol_scheme" />
           </intent-filter>
       </activity>
    </application>
</manifest>

</code>```

in my devide app name is showing cwc(khusi).

but here in my device overview is showing flutter demo name

答:
The title attribute in MaterialApp used as title of app in Recent apps section , so you should assign the specific name that you want.

Please check below sample :

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'CWC(Khushi)',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hello App Home Page'),
        ),
        body: Hello(),
      ),
    );
  }
}
```

Body:
My mobile app name is CWC(Khushi) but in my mobile device overview section is showing flutter demo. I dont know why?

My mobile app name is CWC(Khushi) but in my mobile device overview section is showing flutter demo. I dont know why?
My mobile app name is CWC(Khushi) but in my mobile device overview section is showing flutter demo. I dont know why?

this is my pubspec.yaml file

name: cwc
description: We are a Community Owned & Community Driven Movement. Our Innovative Wellness Ecosystem is led by Doctors, Health Heroes, Support Groups, Health Entrepreneurs and Pros, Wellness Product cum Service Providers – powered by Tech Platform and App to Scale, Access Content and Engage.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  google_fonts: ^2.1.0
  http: ^0.13.4
  shared_preferences: ^2.0.8
  fluttertoast: ^8.0.8
  image_picker: ^0.8.3+2
  url_launcher: ^6.0.18
  google_sign_in: ^5.2.2
  firebase_auth: ^3.3.5
  flutter_facebook_auth: ^4.0.0
  sign_in_with_apple: ^3.3.0
  skeletons: ^0.0.3
  flutter_login_facebook: ^1.2.0
  intl: ^0.17.0
  country_calling_code_picker: ^2.0.0
  share: ^2.0.4
  flutter_inappwebview: ^5.3.2
  photo_view: ^0.13.0
  syncfusion_flutter_pdfviewer: ^19.4.48-beta
  better_player: ^0.0.81
  audioplayers: ^0.18.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons: ^0.9.2
flutter_icons:
  android: "launcher_icon"
  ios: true
  image_path: "assets/app_icon.png"
  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

this is my menifest file

  <application
        android:label="Khushi (CWC)"
        android:icon="@mipmap/launcher_icon"
       android:usesCleartextTraffic="true">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />

       <meta-data android:name="com.facebook.sdk.ApplicationId"
           android:value="@string/facebook_app_id"/>

       <activity android:name="com.facebook.FacebookActivity"
           android:configChanges=
               "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
           android:label="@string/app_name" />
       <activity
           android:name="com.facebook.CustomTabActivity"
           android:exported="true">
           <intent-filter>
               <action android:name="android.intent.action.VIEW" />
               <category android:name="android.intent.category.DEFAULT" />
               <category android:name="android.intent.category.BROWSABLE" />
               <data android:scheme="@string/fb_login_protocol_scheme" />
           </intent-filter>
       </activity>
    </application>
</manifest>

in my devide app name is showing cwc(khusi).

but here in my device overview is showing flutter demo name


问:
Changing channel from unbuffered to buffered prevents goroutine from running
Here is an exercise using channels and select in a goroutine.  If the disconnect channel is changed to a buffered channel the goroutine doesn't run at all.

Why does changing from an unbuffered to a buffered channel prevent running the goroutine?

```<code>func SelectDemo(wg *sync.WaitGroup) {

    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{})
    //  go routine won't run if channel is buffered
    //disconnectCh := make(chan struct{}, 1)

    defer close(messageCh)
    defer close(disconnectCh)
    go func() {
        fmt.Println("  goroutine")
        wg.Add(1)
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("  disconnectCh")
                //  empty the buffered channel before exiting
                for {
                    select {
                    case v := <-messageCh:
                        fmt.Println(v)
                    default:
                        fmt.Println("  disconnection, return")
                        wg.Done()
                        return
                    }
                }
            }
        }
    }()

    fmt.Println("Sending ints")
    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    fmt.Println("Sending done")
    disconnectCh <- struct{}{}
}
</code>```

Here's the code to call the function from main.  I use the wait group to assure that the goroutine completes before the program exits:

```<code>wg := sync.WaitGroup{}
ch09.SelectDemo(&wg)
wg.Wait()
</code>```

答:
That code logic has many flaws - some of them are:

1- Since the messageCh is buffered, this code is not blocking:

```<code>    for i := 0; i < 10; i++ {
        messageCh <- i
    }
</code>```

so the next code is in the fast path to run:

```<code>disconnectCh <- struct{}{}
</code>```

if you make the disconnectCh buffered, this line runs without blocking too, and the SelectDemo function may exit befor running the wg.Add(1).

So: You must put:

```<code>wg.Add(1)
</code>```

before

```<code>go func() {
</code>```

2- Even with wg.Add(1) before go func() {   code -

you have:

```<code>    defer close(messageCh)
    defer close(disconnectCh)
</code>```

which will close both channels at SelectDemo function return
And this select is a random selection since both channels are ready:

```<code>fmt.Println("  goroutine")
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
</code>```

and it is highly likely that the second select:

```<code>                for {
                    select {
                    case v := <-messageCh:
                        fmt.Println(v)
                    default:
                        fmt.Println("  disconnection, return")
                        wg.Done()
                        return
                    }
                }
</code>```

will run forever since the messageCh is closed, returning 0 forever after channel data read:

```<code>case v := <-messageCh:
    fmt.Println(v)
</code>```

Body:
Here is an exercise using channels and select in a goroutine.  If the disconnect channel is changed to a buffered channel the goroutine doesn't run at all.

Why does changing from an unbuffered to a buffered channel prevent running the goroutine?

func SelectDemo(wg *sync.WaitGroup) {

    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{})
    //  go routine won't run if channel is buffered
    //disconnectCh := make(chan struct{}, 1)

    defer close(messageCh)
    defer close(disconnectCh)
    go func() {
        fmt.Println("  goroutine")
        wg.Add(1)
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("  disconnectCh")
                //  empty the buffered channel before exiting
                for {
                    select {
                    case v := <-messageCh:
                        fmt.Println(v)
                    default:
                        fmt.Println("  disconnection, return")
                        wg.Done()
                        return
                    }
                }
            }
        }
    }()

    fmt.Println("Sending ints")
    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    fmt.Println("Sending done")
    disconnectCh <- struct{}{}
}

Here's the code to call the function from main.  I use the wait group to assure that the goroutine completes before the program exits:

wg := sync.WaitGroup{}
ch09.SelectDemo(&wg)
wg.Wait()

Body:
That code logic has many flaws - some of them are:

1- Since the messageCh is buffered, this code is not blocking:

    for i := 0; i < 10; i++ {
        messageCh <- i
    }

so the next code is in the fast path to run:

disconnectCh <- struct{}{}

if you make the disconnectCh buffered, this line runs without blocking too, and the SelectDemo function may exit befor running the wg.Add(1).

So: You must put:

wg.Add(1)

before

go func() {

2- Even with wg.Add(1) before go func() {   code -

you have:

    defer close(messageCh)
    defer close(disconnectCh)

which will close both channels at SelectDemo function return
And this select is a random selection since both channels are ready:

fmt.Println("  goroutine")
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:

and it is highly likely that the second select:

                for {
                    select {
                    case v := <-messageCh:
                        fmt.Println(v)
                    default:
                        fmt.Println("  disconnection, return")
                        wg.Done()
                        return
                    }
                }

will run forever since the messageCh is closed, returning 0 forever after channel data read:

case v := <-messageCh:
    fmt.Println(v)


问:
Increase opacity of child elements when it reaches the top edge of the parent container on scroll
Initially, the child element opacity is set to 0 except for the first child that is already on top, and when the scroll happens the next child to reach the top of the parent container, opacity will be set to 1 and the same thing happens for the rest of the child.

```<code><div class="parent"> // scrollable parent container
  <div class="child">I am child 1</div>  // currently visible child with opacity 1
  <div class="child">I am child 2</div>  // next child element with opacity 0.5
  <div class="child">I am child 3</div>  // next child element with opacity 0.5
  .....
</div>
</code>```

I've seen this post Increase element opacity when user scrolls down the page , but this one is jquery. Can't find something similar for pure javascript and also this only contain one child element.

Don't know where to start. Any help is very much appreciated.

答:
Okay, after several hours of trying / researching. I finally able to solve it. I will post my solution so that it may help others who will have the same use case with me.

```<code>const parentContainer = document.getElementById('parent');
parentContainer.addEventListener(
    'scroll',
   event => {
      [].slice.call(event.target.children).map(el => {
          if (el.offsetTop - 100 < event.target.scrollTop) {
            el.style.opacity =
              1 -
              ((el.clientHeight - event.target.scrollTop) /
                el.clientHeight) *
                0.7 +
              0.3;
          } else {
            el.style.opacity = 0.3;
          }
      });
    }
  )
</code>```

What I did above is get the parent element and added scroll event listener. Map through its child elements and then get the child offsetTop value and compared it to parent scrollTop value, if it's less than apply the logic I found from the reference link above to increase the opacity else (when scroll up) return to default opacity.

I hope this is clear for anyone looking for the same solution.

Body:
Initially, the child element opacity is set to 0 except for the first child that is already on top, and when the scroll happens the next child to reach the top of the parent container, opacity will be set to 1 and the same thing happens for the rest of the child.

 // scrollable parent container

I am child 1
  // currently visible child with opacity 1

I am child 2
  // next child element with opacity 0.5

I am child 3
  // next child element with opacity 0.5
  .....

I've seen this post Increase element opacity when user scrolls down the page , but this one is jquery. Can't find something similar for pure javascript and also this only contain one child element.

Don't know where to start. Any help is very much appreciated.

Body:
Okay, after several hours of trying / researching. I finally able to solve it. I will post my solution so that it may help others who will have the same use case with me.

const parentContainer = document.getElementById('parent');
parentContainer.addEventListener(
    'scroll',
   event => {
      [].slice.call(event.target.children).map(el => {
          if (el.offsetTop - 100 < event.target.scrollTop) {
            el.style.opacity =
              1 -
              ((el.clientHeight - event.target.scrollTop) /
                el.clientHeight) *
                0.7 +
              0.3;
          } else {
            el.style.opacity = 0.3;
          }
      });
    }
  )

What I did above is get the parent element and added scroll event listener. Map through its child elements and then get the child offsetTop value and compared it to parent scrollTop value, if it's less than apply the logic I found from the reference link above to increase the opacity else (when scroll up) return to default opacity.

I hope this is clear for anyone looking for the same solution.


问:
Error logging in to Google Cloud Registry from Gitlab CI: Cannot perform interactive login from a non TTY device
Life is great as I have 2 Gitlab CI projects that should both push docker images to the same directory and both have the some configuration but one is working, one is not...

Working:

```<code>push_gcp:
  only:
    - master
  image: docker:dind
  before_script:
    - docker login registry.gitlab.com -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD}
    - echo $GCLOUD_SERVICE_ACCOUNT_BASE64 > gcloud-service-key.txt
    - cat gcloud-service-key.txt | docker login -u _json_key_base64 --password-stdin https://europe-west4-docker.pkg.dev
  script:
    - ...
  after_script:
    - docker logout ${CI_REGISTRY}
    - docker logout https://europe-west4-docker.pkg.dev
  stage: push
  allow_failure: false
  tags:
    - docker
</code>```

Failing:

```<code>push_gcp:
  only:
    - master
  image: docker:dind
  before_script:
    - docker login registry.gitlab.com -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD}
    - echo $GCLOUD_SERVICE_ACCOUNT_BASE64 > gcloud-service-key.txt
    - cat gcloud-service-key.txt | docker login -u _json_key_base64 --password-stdin https://europe-west4-docker.pkg.dev
  script:
    - ...
  after_script:
    - docker logout ${CI_REGISTRY}
    - docker logout https://europe-west4-docker.pkg.dev
  stage: push_image
  allow_failure: false
  tags:
    - docker
</code>```

Any ideas? I'm going mental here..

答:
Try this:

```<code> - echo $GCP_SA_KEY > ${HOME}/gcloud-service-key.json
 - docker login -u _json_key --password-stdin https://gcr.io < ${HOME}/gcloud-service-key.json
</code>```

basically after --password-stdin, use < .

Body:
Life is great as I have 2 Gitlab CI projects that should both push docker images to the same directory and both have the some configuration but one is working, one is not...

Working:

push_gcp:
  only:
    - master
  image: docker:dind
  before_script:
    - docker login registry.gitlab.com -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD}
    - echo $GCLOUD_SERVICE_ACCOUNT_BASE64 > gcloud-service-key.txt
    - cat gcloud-service-key.txt | docker login -u _json_key_base64 --password-stdin https://europe-west4-docker.pkg.dev
  script:
    - ...
  after_script:
    - docker logout ${CI_REGISTRY}
    - docker logout https://europe-west4-docker.pkg.dev
  stage: push
  allow_failure: false
  tags:
    - docker

Failing:

push_gcp:
  only:
    - master
  image: docker:dind
  before_script:
    - docker login registry.gitlab.com -u ${CI_REGISTRY_USER} -p ${CI_REGISTRY_PASSWORD}
    - echo $GCLOUD_SERVICE_ACCOUNT_BASE64 > gcloud-service-key.txt
    - cat gcloud-service-key.txt | docker login -u _json_key_base64 --password-stdin https://europe-west4-docker.pkg.dev
  script:
    - ...
  after_script:
    - docker logout ${CI_REGISTRY}
    - docker logout https://europe-west4-docker.pkg.dev
  stage: push_image
  allow_failure: false
  tags:
    - docker

Any ideas? I'm going mental here..

Body:
Try this:

 - echo $GCP_SA_KEY > ${HOME}/gcloud-service-key.json
 - docker login -u _json_key --password-stdin https://gcr.io < ${HOME}/gcloud-service-key.json

basically after --password-stdin, use < .


问:
Is it possible to convert OutStream to a string?
I have a method that uses DOM parsing to build an XML file and it takes an OutputStream as an argument. I'm trying to run the program from the command line, but the command line option only accepts strings.

I can run it by inputting System.out as an argument and running the the program, but that's it.

Here's a snippet of code:

```<code>public class WriteSourceTranslatedToTXML extends GetSourceSentences {

    public static String makeTranslated(OutputStream output, String out) throws ParserConfigurationException, IOException, SAXException, URISyntaxException {

        System.out.println("---creating XML file---");
        Document doc = new Document();
        doc.setRootElement(new Element("txml"));

        // Built XML here and inserted sentences
        xmlOutputter.setFormat(Format.getPrettyFormat());
        xmlOutputter.output(doc, output);

        // Write to file
        XMLOutputter xout = new XMLOutputter();
        String xml = xout.outputString(doc.getRootElement().getContent());

        try(FileOutputStream fileOutputStream =
               new FileOutputStream(out)) {
                   xmlOutputter.output(doc, fileOutputStream);
</code>```

And here is the code for the command line:

```<code>@Command(name = "fileCli", description = "Performs file manipulation operations", mixinStandardHelpOptions = true, version = "File Client 1.0")

public class TranslateTXML implements Callable<String> {

    @Option(names = "-o", description = "output path")
    private String output;
    if (output != null) {
        WriteSourceTranslatedToTXML.makeTranslated(output); // Red line under output
        System.out.println("translated made");
        System.out.println("------");
        System.out.println("File \"translated.txml\" has been outputted to designated path");
</code>```

How can I do it?

答:
I used a different method by which Java builds the XML file.

The new method call does not require an OutputStream argument, but simply a string, which I set as the filepath.

```<code>public static void createXml(String directory) throws IOException, TransformerException, ParserConfigurationException {

    BufferedReader sourceReader = new BufferedReader(new FileReader(db));

    .
    .

    // Use DocumentBuilder and construct the XML file using NodeList Collection
    .
    .

    DOMSource source = new DOMSource(doc);

    // Write to console or file
    StreamResult console = new StreamResult(System.out);
    StreamResult file = new StreamResult(new File(directory));
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    // For pretty print
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Write data
    transformer.transform(source, console);
    transformer.transform(source, file);
    sourceReader.close();
</code>```

So by using DOM parser, Transformer, and StreamResult, I can build the .xml file and store it in a Stream with StreamResult (which requires a String parameter for output).
Voilà!

Body:
I have a method that uses DOM parsing to build an XML file and it takes an OutputStream as an argument. I'm trying to run the program from the command line, but the command line option only accepts strings.

I can run it by inputting System.out as an argument and running the the program, but that's it.

Here's a snippet of code:

public class WriteSourceTranslatedToTXML extends GetSourceSentences {

    public static String makeTranslated(OutputStream output, String out) throws ParserConfigurationException, IOException, SAXException, URISyntaxException {

        System.out.println("---creating XML file---");
        Document doc = new Document();
        doc.setRootElement(new Element("txml"));

        // Built XML here and inserted sentences
        xmlOutputter.setFormat(Format.getPrettyFormat());
        xmlOutputter.output(doc, output);

        // Write to file
        XMLOutputter xout = new XMLOutputter();
        String xml = xout.outputString(doc.getRootElement().getContent());

        try(FileOutputStream fileOutputStream =
               new FileOutputStream(out)) {
                   xmlOutputter.output(doc, fileOutputStream);

And here is the code for the command line:

@Command(name = "fileCli", description = "Performs file manipulation operations", mixinStandardHelpOptions = true, version = "File Client 1.0")

public class TranslateTXML implements Callable<String> {

    @Option(names = "-o", description = "output path")
    private String output;
    if (output != null) {
        WriteSourceTranslatedToTXML.makeTranslated(output); // Red line under output
        System.out.println("translated made");
        System.out.println("------");
        System.out.println("File \"translated.txml\" has been outputted to designated path");

How can I do it?

Body:
I used a different method by which Java builds the XML file.

The new method call does not require an OutputStream argument, but simply a string, which I set as the filepath.

public static void createXml(String directory) throws IOException, TransformerException, ParserConfigurationException {

    BufferedReader sourceReader = new BufferedReader(new FileReader(db));

    .
    .

    // Use DocumentBuilder and construct the XML file using NodeList Collection
    .
    .

    DOMSource source = new DOMSource(doc);

    // Write to console or file
    StreamResult console = new StreamResult(System.out);
    StreamResult file = new StreamResult(new File(directory));
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    // For pretty print
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Write data
    transformer.transform(source, console);
    transformer.transform(source, file);
    sourceReader.close();

So by using DOM parser, Transformer, and StreamResult, I can build the .xml file and store it in a Stream with StreamResult (which requires a String parameter for output).
Voilà!


问:
Incorrect syntax near '*=' SQL Server
While moving from SQL Server 2016 to 2019 on DbaaS, I am getting this error:

Msg 102, Level 15, State 1, Server p2fm1sql414\SQL01, Procedure usp_sales_record_1020, Line 75

Incorrect syntax near '*='

See query:

```<code>  select @sql_1 = "
  --BEGIN TRANSACTION
     insert into SalesFactor.dbo.tbl_cmfsales
     select a.asof_yyyymm ,
            a.bllg_doc_id ,
            a.bllg_doc_ref_id ,
            a.bllg_yyyymm ,
            a.cfm_opr_cd  ,
            a.cfm_opr_dsc ,
            a.dlv_doc_id    ,
            a.dstrb_chnl_cd ,
            a.dstrb_chnl_dsc ,
            a.indus_ky_cd ,
            a.indus_ky_dsc ,
            mtd_bllg_amt    = (1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt,
            mtd_bllg_qty    = (1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_qty,
            a.ord_rsn_cd  ,
            a.pay_cst_id ,
            a.plt_cd  ,
            a.sld_cst_id ,
            a.shp_cst_id ,
            a.sll_co_cd ,
            a.sls_org_cd ,
            a.sls_ord_doc_ty_cd ,
            a.sls_ord_doc_ty_dsc ,
            a.sls_ord_id ,
            a.sls_org_dsc,
            a.shp_cst_ctry_dsc,
              returns = case when a.sls_ord_doc_ty_cd not in('or','zdpa') then ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt)
                             else 0 end,
            a.shp_cst_ctry_cd ,
            b.cst_nm ,
            b.addr_2_nm ,
            b.addr_3_nm ,
            b.addr_4_nm ,
            b.addr_cty ,
            rgn_cd = isnull(b.rgn_cd,' '),
            b.post_cd ,
            b.cst_srch_nm ,
            b.cst_acct_grp_cd ,
            b.cst_acct_grp_dsc ,
            UsAmt =    ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * charindex('US',a.shp_cst_ctry_cd),
            OtherAmt = ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * (1-abs(sign((charindex('US',a.shp_cst_ctry_cd)))-0)),
            RnaDpa =   ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * charindex('zdpa',a.sls_ord_doc_ty_cd) ,
            DpaSales = ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * charindex('or',a.sls_ord_doc_ty_cd) ,
            quarter = 'Q' + '" + @pass + "',
            year    = '" + @yyyy + "',
            status =    case when shp_cst_ctry_cd = 'US' then 'U.S.'
                               else'Foreign' end,
            warehouse = case  when substring(a.plt_cd,2,2) = 'ch' Then 'AZ'
                              when substring(a.plt_cd,2,2) = 'wa' Then 'WA'
                              when substring(a.plt_cd,2,2) = 'or' Then 'OR'
                              when substring(a.plt_cd,2,2) = 'sc' Then 'CA'
                              when substring(a.plt_cd,2,2) = 'fm' Then 'CA'
                              when substring(a.plt_cd,2,2) = 'ca' Then 'CA'
                              else 'Foreign' end,
            type =      case when a.shp_cst_ctry_cd = 'US' then '1'
                              else '2' end,
            pay_cst_nm = ' ',
            pay_state = ' '
       from data_store.dbo.tbl_billed_orders_" + @yyyy + @mm + " a, tpdb.dbo.tbl_cst_mstr b
       " + @str_where + " and  a.shp_cst_id *= b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')

--COMMIT TRANSACTION
"
</code>```

I am able to execute this query when I am running on SQL Server 2016 but during migration it fails with above error?

Any suggestions on any changes in this query?

答:
Try changing this line:</p>
```<code>" + @str_where + " and  a.shp_cst_id *= b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')` to `" + @str_where + " and  a.shp_cst_id = b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')
</code>```

Title: Incorrect syntax near '*=' SQL Server

Body:
While moving from SQL Server 2016 to 2019 on DbaaS, I am getting this error:

Msg 102, Level 15, State 1, Server p2fm1sql414\SQL01, Procedure usp_sales_record_1020, Line 75

Incorrect syntax near '*='

See query:

  select @sql_1 = "
  --BEGIN TRANSACTION
     insert into SalesFactor.dbo.tbl_cmfsales
     select a.asof_yyyymm ,
            a.bllg_doc_id ,
            a.bllg_doc_ref_id ,
            a.bllg_yyyymm ,
            a.cfm_opr_cd  ,
            a.cfm_opr_dsc ,
            a.dlv_doc_id    ,
            a.dstrb_chnl_cd ,
            a.dstrb_chnl_dsc ,
            a.indus_ky_cd ,
            a.indus_ky_dsc ,
            mtd_bllg_amt    = (1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt,
            mtd_bllg_qty    = (1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_qty,
            a.ord_rsn_cd  ,
            a.pay_cst_id ,
            a.plt_cd  ,
            a.sld_cst_id ,
            a.shp_cst_id ,
            a.sll_co_cd ,
            a.sls_org_cd ,
            a.sls_ord_doc_ty_cd ,
            a.sls_ord_doc_ty_dsc ,
            a.sls_ord_id ,
            a.sls_org_dsc,
            a.shp_cst_ctry_dsc,
              returns = case when a.sls_ord_doc_ty_cd not in('or','zdpa') then ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt)
                             else 0 end,
            a.shp_cst_ctry_cd ,
            b.cst_nm ,
            b.addr_2_nm ,
            b.addr_3_nm ,
            b.addr_4_nm ,
            b.addr_cty ,
            rgn_cd = isnull(b.rgn_cd,' '),
            b.post_cd ,
            b.cst_srch_nm ,
            b.cst_acct_grp_cd ,
            b.cst_acct_grp_dsc ,
            UsAmt =    ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * charindex('US',a.shp_cst_ctry_cd),
            OtherAmt = ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * (1-abs(sign((charindex('US',a.shp_cst_ctry_cd)))-0)),
            RnaDpa =   ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * charindex('zdpa',a.sls_ord_doc_ty_cd) ,
            DpaSales = ((1 - abs(sign(a.bllg_yyyymm - a.asof_yyyymm))) * a.mtd_bllg_amt) * charindex('or',a.sls_ord_doc_ty_cd) ,
            quarter = 'Q' + '" + @pass + "',
            year    = '" + @yyyy + "',
            status =    case when shp_cst_ctry_cd = 'US' then 'U.S.'
                               else'Foreign' end,
            warehouse = case  when substring(a.plt_cd,2,2) = 'ch' Then 'AZ'
                              when substring(a.plt_cd,2,2) = 'wa' Then 'WA'
                              when substring(a.plt_cd,2,2) = 'or' Then 'OR'
                              when substring(a.plt_cd,2,2) = 'sc' Then 'CA'
                              when substring(a.plt_cd,2,2) = 'fm' Then 'CA'
                              when substring(a.plt_cd,2,2) = 'ca' Then 'CA'
                              else 'Foreign' end,
            type =      case when a.shp_cst_ctry_cd = 'US' then '1'
                              else '2' end,
            pay_cst_nm = ' ',
            pay_state = ' '
       from data_store.dbo.tbl_billed_orders_" + @yyyy + @mm + " a, tpdb.dbo.tbl_cst_mstr b
       " + @str_where + " and  a.shp_cst_id *= b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')

--COMMIT TRANSACTION
"

I am able to execute this query when I am running on SQL Server 2016 but during migration it fails with above error?

Any suggestions on any changes in this query?

Body:
Try changing this line:

" + @str_where + " and  a.shp_cst_id *= b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')` to `" + @str_where + " and  a.shp_cst_id = b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')


问:
Vue - prevent item dragging in a grid
I created a grid of items using this library and it works flawlessly. In my items, i have a very simple bootstrap grid with some forms, inputs and other content, the problem is that a lot of times while using the content inside of the bootstrap grid, i move the entire item.

I was wondering if there is a way to disable dragging only inside of the  so that when i use what's inside of the container, the item is not moved, but if i want to move the item i can drag it by grabbing it outside the container.

Here is my code:

```<code><template>
    <grid-layout :layout.sync="layout"
                 :col-num="1"
                 :row-height="30"
                 :is-draggable="draggable"
                 :is-resizable="resizable"
                 :vertical-compact="true"
                 :use-css-transforms="true"
    >
        <grid-item v-for="item in layout"
                   :static="item.static"
                   :x="item.x"
                   :y="item.y"
                   :w="item.w"
                   :h="item.h"
                   :i="item.i"
        >

        <div class="container">
            <div class="row">
                <div class="col-sm-7">Here is some content...</div>
                <div class="col-sm-5">Here is some other content.. </div>
            </div>
        </div>

        </grid-item>
    </grid-layout>
</template>

<script>
import { GridLayout, GridItem } from "vue-grid-layout"
export default {
    components: {
        GridLayout,
        GridItem
    },
    data() {
        return {
            layout: [
                {"x":0,"y":0,"w":6,"h":4,"i":"0", static: false},
            ],
            draggable: true,
            resizable: true,
            index: 0
        }
    },
    methods: {
        itemTitle(item) {
            let result = item.i;
            if (item.static) {
                result += " - Static";
            }
            return result;
        }
    }
}
</script>

<style scoped>
.vue-grid-layout {
    background: #eee;
}
.vue-grid-item:not(.vue-grid-placeholder) {
    background: #ccc;
    border: 1px solid black;
}
.vue-grid-item .resizing {
    opacity: 0.9;
}
.vue-grid-item .static {
    background: #cce;
}
.vue-grid-item .text {
    font-size: 24px;
    text-align: center;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    height: 100%;
    width: 100%;
}
.vue-grid-item .no-drag {
    height: 100%;
    width: 100%;
}
.vue-grid-item .minMax {
    font-size: 12px;
}
.vue-grid-item .add {
    cursor: pointer;
}
.vue-draggable-handle {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>") no-repeat;
    background-position: bottom right;
    padding: 0 8px 8px 0;
    background-repeat: no-repeat;
    background-origin: content-box;
    box-sizing: border-box;
    cursor: pointer;
}
</style>
</code>```

So basically i should not be able to drag or move the item from inside the container. Any kind of advice is appreciated. Thanks in advance!

答:
You can either set static to true which would not allow you to drag/resize the grid or add an element draggable in your layout and set it to false where you will be able to only resize the grid.

```<code>layout: [
            {"x":0,"y":0,"w":6,"h":4,"i":"0", static: true},
        ] // If you want to lock the grid (no resize/no dragging)
</code>```

or

```<code>layout: [
            {"x":0,"y":0,"w":6,"h":4,"i":"0", draggable: false},
        ] // you will be able to resize but drag
<grid-item
     :key="item.i"
      v-for="item in layout"
      :is-draggable="item.draggable"
      :x="item.x"
      :y="item.y"
      :w="item.w"
      :h="item.h"
     :i="item.i"
     >
</code>```

Title: Vue - prevent item dragging in a grid

Body:
I created a grid of items using this library and it works flawlessly. In my items, i have a very simple bootstrap grid with some forms, inputs and other content, the problem is that a lot of times while using the content inside of the bootstrap grid, i move the entire item.

I was wondering if there is a way to disable dragging only inside of the  so that when i use what's inside of the container, the item is not moved, but if i want to move the item i can drag it by grabbing it outside the container.

Here is my code:

<template>
    <grid-layout :layout.sync="layout"
                 :col-num="1"
                 :row-height="30"
                 :is-draggable="draggable"
                 :is-resizable="resizable"
                 :vertical-compact="true"
                 :use-css-transforms="true"
    >
        <grid-item v-for="item in layout"
                   :static="item.static"
                   :x="item.x"
                   :y="item.y"
                   :w="item.w"
                   :h="item.h"
                   :i="item.i"
        >

Here is some content...

Here is some other content..

        </grid-item>
    </grid-layout>
</template>

So basically i should not be able to drag or move the item from inside the container. Any kind of advice is appreciated. Thanks in advance!

Body:
You can either set static to true which would not allow you to drag/resize the grid or add an element draggable in your layout and set it to false where you will be able to only resize the grid.

layout: [
            {"x":0,"y":0,"w":6,"h":4,"i":"0", static: true},
        ] // If you want to lock the grid (no resize/no dragging)

or

layout: [
            {"x":0,"y":0,"w":6,"h":4,"i":"0", draggable: false},
        ] // you will be able to resize but drag
<grid-item
     :key="item.i"
      v-for="item in layout"
      :is-draggable="item.draggable"
      :x="item.x"
      :y="item.y"
      :w="item.w"
      :h="item.h"
     :i="item.i"
     >


问:
$(this).find("a").attr("onclick"); onclick giving invalid character
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

```<code>$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});
</code>```

And the HTML:

```<code><div>
    <div id="tab1" class="tab_content">01</div>
    <div id="tab2" class="tab_content">02</div>
    <div id="tab3" class="tab_content">03</div>
</div>
<ol class="tabs">
    <li><a onclick="#tab1">Unique benefits</a></li>
    <li><a onclick="#tab2">Insurance</a></li>
    <li><a onclick="#tab3">Business Loan</a></li>
</ol>
</code>```

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out

答:
Thats the expected behaviour.

Because, last time I checked, onclick was an event and not an attribute or property.

Also href and onclick are completely different things.

ContentLicense: CC BY-SA 3.0

Body:
I m creating a dynamic tab using Jquery its working fine but giving error for anchor tag onclick error is invalid character.
See the javascript:

$(document).ready(function(){

    //when page loads...
    $(".tab_content").hide(); //hide all content
    $("ol.tabs li:first").addClass("active").show();  //Activate first tab
    $(".tab_content:first").show(); // show first tab content

    //on click event
    $("ol.tabs li").click(function(){
        $("ol.tabs li").removeClass("active"); //remove any "active" class
        $(this).addClass("active"); // add "active" class to selected tabs
        $(".tab_content").hide(); // hide all tab content
        //var activeTab = $(this).find("a").attr("href"); // find href attribute value to identify the active tab + content
        var activeTab = $(this).find("a").attr("onclick"); // find href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); // fadeIn the active ID content
        alert(activeTab);
        return false;
    });

});

And the HTML:

01

02

03

Unique benefits

Insurance

Business Loan

If i use var activeTab = $(this).find("a").attr("href");

Its work fine.
Help out


问:
Format tree to print
I am trying to visually format a tree (NOT A BST) so that it prints out appealing. I have written code to do so, and it compiles successfully as my tree has a maximum depth of 4. (I will work on making the dashes more attractive later). Here is what I have.

```<code>        String formatted = "";
    formatted += current.getName() +"\n";
    for (Node child: current.getChildren()) {  //figure out how to do this recursively
        formatted += "---"+child.getName() + "\n";
        if (child.getChildren() != null) {
            for (Node child2: child.getChildren()) {
                formatted += "------"+child2.getName() + "\n";
                if (child2.getChildren() != null) {
                    for (Node child3: child2.getChildren()){
                        formatted += "---------"+ child3.getName()+ "\n";
                        if (child3.getChildren() != null) {
                            for (Node child4: child3.getChildren()) {
                                formatted += "------------" + child4.getName()+ "\n";
                            }
                        }
                    }

                }
            }
        }
    }
</code>```

Obviously I want to find a way to do this recursively with any depth of tree but I am lost as how to do so. Any help is appreciated!

答:
You would indeed need recursion. The trick is that you provide the indenting information to the recursive call, like a number of dashes to print before each line.

I will just use the same output format you were using:

```<code>String formatTree(Node root) {
    return formatTree(root, "");
}

String formatTree(Node current, String prefix) {
    String formatted = prefix + current.getName() + "\n";
    if (current.getChildren() != null) {
        // Any deeper node will have more dashes in front of it
        prefix += "---";
        for (Node child: current.getChildren()) {
            formatted += formatTree(child, prefix);
        }
    }
    return formatted;
}
</code>```

Title: Format tree to print

Body:
I am trying to visually format a tree (NOT A BST) so that it prints out appealing. I have written code to do so, and it compiles successfully as my tree has a maximum depth of 4. (I will work on making the dashes more attractive later). Here is what I have.

        String formatted = "";
    formatted += current.getName() +"\n";
    for (Node child: current.getChildren()) {  //figure out how to do this recursively
        formatted += "---"+child.getName() + "\n";
        if (child.getChildren() != null) {
            for (Node child2: child.getChildren()) {
                formatted += "------"+child2.getName() + "\n";
                if (child2.getChildren() != null) {
                    for (Node child3: child2.getChildren()){
                        formatted += "---------"+ child3.getName()+ "\n";
                        if (child3.getChildren() != null) {
                            for (Node child4: child3.getChildren()) {
                                formatted += "------------" + child4.getName()+ "\n";
                            }
                        }
                    }

                }
            }
        }
    }

Obviously I want to find a way to do this recursively with any depth of tree but I am lost as how to do so. Any help is appreciated!

Body:
You would indeed need recursion. The trick is that you provide the indenting information to the recursive call, like a number of dashes to print before each line.

I will just use the same output format you were using:

String formatTree(Node root) {
    return formatTree(root, "");
}

String formatTree(Node current, String prefix) {
    String formatted = prefix + current.getName() + "\n";
    if (current.getChildren() != null) {
        // Any deeper node will have more dashes in front of it
        prefix += "---";
        for (Node child: current.getChildren()) {
            formatted += formatTree(child, prefix);
        }
    }
    return formatted;
}


问:
SQL CASE WHEN a is NULL
I have 3 columns all contain email addresses

```<code>email
alt_email
main_email
</code>```

I wanted to do case when email is null then alt_email
when alt_email is null then email and when both are null then main_email end as all_emails.

I am not getting the correct answer as the total count for all_emails is way 90% less than the total all customers.

TIA

答:
```<code>SELECT
CASE
    WHEN email IS NULL AND alt_email IS NULL THEN main_email
    WHEN email IS NULL AND alt_email IS NOT NULL THEN alt_email
    WHEN alt_email IS NULL AND email IS NOT NULL THEN email
    ELSE email
END AS all_emails
FROM some_table;
</code>```

Title: SQL CASE WHEN a is NULL

Body:
I have 3 columns all contain email addresses

email
alt_email
main_email

I wanted to do case when email is null then alt_email
when alt_email is null then email and when both are null then main_email end as all_emails.

I am not getting the correct answer as the total count for all_emails is way 90% less than the total all customers.

TIA


问:
ie8 var w= window.open() - "Message: Invalid argument."
I have a site that has an IE8-only problem:

The code is:

```<code>var w = window.open(urlstring, wname, wfeatures, 'false');
</code>```

The error is:

Message: Invalid argument.

  Line: 419
  Char: 5

  Code: 0

  URI: http://HOSTNAME/js_context.js

I have confirmed the line number of the code (the "Line" and "URI" are correct), and I understand in later versions of IE8, this is considered accurate.

I have checked all the incoming parameters in the call by dumping alerts, and they all look valid.

This problem does not happen on FF (probably 3).

UPDATE:

The problem appears to be in using assigning the result of window.open() when doing "var w". When I split the line into two statements it works in IE8.

UPDATE2:

Based on:

http://javascript.crockford.com/code.html

When a function is to be invoked
  immediately, the entire invocation
  expression should be wrapped in parens
  so that it is clear that the value
  being produced is the result of the
  function and not the function itself.

This is not exactly what is going on here, but I found that applying the principle solved the problem, in IE8's compatability mode.

```<code>var w = (window.open(urlstring, wname, wfeatures, false));
</code>```

答: Try remove the last argument. Other than that, make sure urlstring, wname, and wfeatures exist.</p>

OwnerDisplayName: benc

Body:
I have a site that has an IE8-only problem:

The code is:

var w = window.open(urlstring, wname, wfeatures, 'false');

The error is:

Message: Invalid argument.

  Line: 419
  Char: 5

  Code: 0

  URI: http://HOSTNAME/js_context.js

I have confirmed the line number of the code (the "Line" and "URI" are correct), and I understand in later versions of IE8, this is considered accurate.

I have checked all the incoming parameters in the call by dumping alerts, and they all look valid.

This problem does not happen on FF (probably 3).

UPDATE:

The problem appears to be in using assigning the result of window.open() when doing "var w". When I split the line into two statements it works in IE8.

UPDATE2:

Based on:

http://javascript.crockford.com/code.html

When a function is to be invoked
  immediately, the entire invocation
  expression should be wrapped in parens
  so that it is clear that the value
  being produced is the result of the
  function and not the function itself.

This is not exactly what is going on here, but I found that applying the principle solved the problem, in IE8's compatability mode.

var w = (window.open(urlstring, wname, wfeatures, false));

LastEditorDisplayName: benc

OwnerDisplayName: TonyF

ContentLicense: CC BY-SA 2.5


问:
Message queue in android
can anybody tell me,
how can get data(message) from message queue ?
or how can send message from main thread to other thread ?.

Thanks

答:
If you want to receive messages on a thread you should run a Looper and create a message Handler bound to this looper. The UI thread has a looper by default. There's a convenient class for creating threads with loopers called HandlerThread. Here's a good article about Handlers and Loopers: Android Guts: Intro to Loopers and Handlers.

EDIT:

```<code>HandlerThread thread = new HandlerThread("Thread name");
thread.start();

Looper looper = thread.getLooper();
Handler handler = new Handler(looper) {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case SOME_MESSAGE_ID:
                // SOME_MESSAGE_ID is any int value
                // do something
                break;
            // other cases
        }
    }
};

handler.post(new Runnable() {
    @Override
    public void run() {
        // this code will be executed on the created thread
    }
});

// Handler.handleMessage() will be executed on the created thread
// after the previous Runnable is finished
handler.sendEmptyMessage(SOME_MESSAGE_ID);
</code>```

Title: Message queue in android

Body:
If you want to receive messages on a thread you should run a Looper and create a message Handler bound to this looper. The UI thread has a looper by default. There's a convenient class for creating threads with loopers called HandlerThread. Here's a good article about Handlers and Loopers: Android Guts: Intro to Loopers and Handlers.

EDIT:

HandlerThread thread = new HandlerThread("Thread name");
thread.start();

Looper looper = thread.getLooper();
Handler handler = new Handler(looper) {
    @Override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case SOME_MESSAGE_ID:
                // SOME_MESSAGE_ID is any int value
                // do something
                break;
            // other cases
        }
    }
};

handler.post(new Runnable() {
    @Override
    public void run() {
        // this code will be executed on the created thread
    }
});

// Handler.handleMessage() will be executed on the created thread
// after the previous Runnable is finished
handler.sendEmptyMessage(SOME_MESSAGE_ID);


问:
What happens at server/endpoint level when client internet connection is lost while the HTTP POST request is executing?
I have a POST endpoint that uploads file into cloud storage by invoking an api.

The code in the endpoint is:

Get the file from the POST request

Save it in a local folder

Invoke cloud storage POST api to send the file into the cloud storage (example: aws s3)

Delete the file from local storage

Return success/failure response

I understand there is a 3-way TCP handshake (and TLS upgrade if using the secure https protocol) for http connection establishment.

Suppose the client has invoked the POST endpoint and the client looses connection when the process has reached step 3 (assume it takes 20 seconds for step 3 to complete and the client looses connection at the 5th second), then:

Will the endpoint execution detect that the client connection has dropped and abort the step 3?

In a second or two, suppose the client gets back the internet, then will the client be able to get the response?

Same as above, but upon internet re-establishment suppose client gets a new IP, then will client be able to get the response?

答:
Will the endpoint execution detect that the client connection has dropped and abort the step 3?

This depends on the server side implementation. Depending on how the connection was dropped and how long step 3 takes the server might not even realize that it has dropped before step 3 is finished.

A properly implemented server will realize though if the request is complete or not and will not even start with step 3 if the request (and therefore the uploaded file) is incomplete.

In a second or two, suppose the client gets back the internet, then will the client be able to get the response?

HTTP is build on top of a reliable transport, either TCP (HTTP/1 and HTTP/2) or QUIC (HTTP/3). Short connection drops which result in small packet loss are dealt at this level and the connection will transparently continue from the perspective of HTTP as if nothing has happened.

Same as above, but upon internet re-establishment suppose client gets a new IP, then will client be able to get the response?

More serious connection drops which lead to the breakage of the underlying TCP/QUIC connection will make it impossible for the current request to transparently continue, i.e. the client will not be able to get the response to the original request. Changing client IP address is one of such cases but not the only one.

If the application needs to deal with such irregularities than it needs a more robust design. This might be done by splitting the file upload into multiple stages and thus multiple requests, like one for starting an upload transaction, others for uploading parts of the file inside this transactions and finally a request to query the status of the transaction, i.e. if the file was successfully uploaded to the cloud storage.


问:
cannot get all elements of array using Axios get in Javascript (Loop through an array in JavaScript)
/*
My task is to get the user's daily work activity information from the API on this localhost page. If the user is involved in several projects, it is necessary to get more than one line of information instead of just one. My current code is code that can only get the information of the first project from the API. In this case, only one line of information can be displayed as shown in the attached photo below. I want to display more than one line of information. Maybe because the list "time_cards" looks like "time_cards [0]", I can only get the first element. I'm guessing, "Loop through an array in JavaScript" I think this method works, but I don't know how to fix the code.
Please help me guys.*/

<template>
  <v-container class="container-padding">
    <v-breadcrumbs class="px-0 pt-0" large>

      <v-breadcrumbs-item class="text-h5 mr-5">Timecard</v-breadcrumbs-item>

      <v-breadcrumbs-item class="text-h6">View</v-breadcrumbs-item>
    </v-breadcrumbs>

    <v-card>
      <v-container fluid>
        <v-row>
          <v-col cols="3">
            <v-subheader>Insert your search date</v-subheader>
          </v-col>
          <v-col cols="3">
            <v-layout row wrap justify-space-around>
            <v-flex xs4 md3>
                <v-text-field v-model="calendarVal" label="Date" type="date" value="2022-02-05"></v-text-field>
            </v-flex>
            <v-flex xs4 md3>
                <v-btn @click="fetchWorkerTimeCard">enter</v-btn>
            </v-flex>
            </v-layout>
          </v-col>
        </v-row>
      </v-container>
      <v-data-table v-if="worker_time_card.length > 0" :headers="headers" :items="worker_time_card"></v-data-table>
    </v-card>
  </v-container>
</template>
```

front end local host page image herecom/YxSjG.png

答:
Ah, you are returning an object. But not an array of objects. So you have to pass in

```<code>Object_values()
</code>```

in the api call. So something like this:

```<code>async fetchWorkerTimeCard() {
  if (this.calendarVal == null) {
    // get today
  } else {
    try {
      await this.$axios.$get('/worker_time_card', { params: { work_date: this.calendarVal } }).then(Object_values(data) => {
        this.worker_time_card.push( {
          start_time: data.start_time,
          end_time: data.end_time,
          rest_time: data.rest_time,
          worked_time: data.worked_time,
          duration: data.time_cards[0].duration,
          work_log: data.time_cards[0].work_log,
          project_id: data.time_cards[0].project_id,

        })
      })
    } catch (error) {
      console.log(error)
      this.worker_time_card = []
    }
  }
},
</code>```

Body:
/*
My task is to get the user's daily work activity information from the API on this localhost page. If the user is involved in several projects, it is necessary to get more than one line of information instead of just one. My current code is code that can only get the information of the first project from the API. In this case, only one line of information can be displayed as shown in the attached photo below. I want to display more than one line of information. Maybe because the list "time_cards" looks like "time_cards [0]", I can only get the first element. I'm guessing, "Loop through an array in JavaScript" I think this method works, but I don't know how to fix the code.
Please help me guys.*/

<template>
  <v-container class="container-padding">
    <v-breadcrumbs class="px-0 pt-0" large>

      <v-breadcrumbs-item class="text-h5 mr-5">Timecard</v-breadcrumbs-item>

      <v-breadcrumbs-item class="text-h6">View</v-breadcrumbs-item>
    </v-breadcrumbs>

    <v-card>
      <v-container fluid>
        <v-row>
          <v-col cols="3">
            <v-subheader>Insert your search date</v-subheader>
          </v-col>
          <v-col cols="3">
            <v-layout row wrap justify-space-around>
            <v-flex xs4 md3>
                <v-text-field v-model="calendarVal" label="Date" type="date" value="2022-02-05"></v-text-field>
            </v-flex>
            <v-flex xs4 md3>
                <v-btn @click="fetchWorkerTimeCard">enter</v-btn>
            </v-flex>
            </v-layout>
          </v-col>
        </v-row>
      </v-container>
      <v-data-table v-if="worker_time_card.length > 0" :headers="headers" :items="worker_time_card"></v-data-table>
    </v-card>
  </v-container>
</template>

front end local host page image herecom/YxSjG.png

Body:
Ah, you are returning an object. But not an array of objects. So you have to pass in

Object_values()

in the api call. So something like this:

async fetchWorkerTimeCard() {
  if (this.calendarVal == null) {
    // get today
  } else {
    try {
      await this.$axios.$get('/worker_time_card', { params: { work_date: this.calendarVal } }).then(Object_values(data) => {
        this.worker_time_card.push( {
          start_time: data.start_time,
          end_time: data.end_time,
          rest_time: data.rest_time,
          worked_time: data.worked_time,
          duration: data.time_cards[0].duration,
          work_log: data.time_cards[0].work_log,
          project_id: data.time_cards[0].project_id,

        })
      })
    } catch (error) {
      console.log(error)
      this.worker_time_card = []
    }
  }
},


答:
You are using an ancient join style *=

Change this to a left join and it will work again.

Please stop using old join styles, this has been deprecated ages ago.

```<code>from data_store.dbo.tbl_billed_orders_" + @yyyy + @mm + " a, tpdb.dbo.tbl_cst_mstr b
       " + @str_where + " and  a.shp_cst_id *= b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')
</code>```

It should be more something like this

```<code>from data_store.dbo.tbl_billed_orders_" + @yyyy + @mm + " a
  left join tpdb.dbo.tbl_cst_mstr b
    ON a.shp_cst_id = b.cst_id
where b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')

</code>```

See also this answer

Title: Incorrect syntax near '*=' SQL Server

Body:
You are using an ancient join style *=

Change this to a left join and it will work again.

Please stop using old join styles, this has been deprecated ages ago.

from data_store.dbo.tbl_billed_orders_" + @yyyy + @mm + " a, tpdb.dbo.tbl_cst_mstr b
       " + @str_where + " and  a.shp_cst_id *= b.cst_id and b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')

It should be more something like this

from data_store.dbo.tbl_billed_orders_" + @yyyy + @mm + " a
  left join tpdb.dbo.tbl_cst_mstr b
    ON a.shp_cst_id = b.cst_id
where b.cst_acct_grp_cd not in('ZISH','ZISP','ZPRC')

See also this answer


问:
Unable to identify Button in hybrid page in android app appium
I have tried to identify 'Send' button but Appium doesn't shown source of that page. This page is a webpage in hybrid android app. Is there any way to get source of this button and verify/inspect it?

I have tried with chrome://inspect/#devices and able to inspect this button in Developer tools but don't know where verify? This is what DOM has inspected.

<button id="btnSaveForm" type="button" ng-click="submitForm(1)" class="btn btn-danger" ng-disabled="isXhrPending() || mainCtrl.isAttachUploading">Send</button>

What could be the Xpath of this and how do I verify it?

答:
For Hybrid apps automation, it's important to define the right context for Appium.

The default context is NATIVE_APP.

So Appium is not able to find any web-view element.

In order to switch context programmatically (with java) you can call

```<code>// the name could be WEBVIEW_... you have to print all the available contexts with driver.getContextHandles(); and find your one
driver.context("WEBVIEW_1");
</code>```

or for appium java-client 8

```<code>import io.appium.java_client.remote.SupportsContextSwitching;

((SupportsContextSwitching) driver).context("WEBVIEW_1");
</code>```

Switch the context in Appium Inspector

I cannot check this, but on your screenshot, there is NATIVE_APP text option in the right-middle part of the screen.

I guess it might be a dropdown with an additional WEBVIEW_... option, so this might be switched.

But when I've tried to find any documentation regarding context switching in Appium Inspector, I've found just this closed feature request (not implemented).

https://github.com/appium/appium-desktop/issues/317

So, this might not be implemented and not supported by Appium Inspector.

In this case, try to follow the suggestion:

You can test webviews by using Chrome or Safari inspector against sims/emus or real devices. Then you get a much more full-featured inspector than we could ever build in Appium Desktop ourselves.

Use autoWebview=true

If your app launched in webview by-default, you might define an additional capability for Appium:

```<code>autoWebview = true
</code>```

which forcefully moves Appium directly into the webview context.

But this also might not work with Appium Desktop (due to https://github.com/appium/appium-desktop/issues/317), and need to be checked.

Body:
For Hybrid apps automation, it's important to define the right context for Appium.

The default context is NATIVE_APP.

So Appium is not able to find any web-view element.

In order to switch context programmatically (with java) you can call

// the name could be WEBVIEW_... you have to print all the available contexts with driver.getContextHandles(); and find your one
driver.context("WEBVIEW_1");

or for appium java-client 8

import io.appium.java_client.remote.SupportsContextSwitching;

((SupportsContextSwitching) driver).context("WEBVIEW_1");

Switch the context in Appium Inspector

I cannot check this, but on your screenshot, there is NATIVE_APP text option in the right-middle part of the screen.

I guess it might be a dropdown with an additional WEBVIEW_... option, so this might be switched.

But when I've tried to find any documentation regarding context switching in Appium Inspector, I've found just this closed feature request (not implemented).

https://github.com/appium/appium-desktop/issues/317

So, this might not be implemented and not supported by Appium Inspector.

In this case, try to follow the suggestion:

You can test webviews by using Chrome or Safari inspector against sims/emus or real devices. Then you get a much more full-featured inspector than we could ever build in Appium Desktop ourselves.

Use autoWebview=true

If your app launched in webview by-default, you might define an additional capability for Appium:

autoWebview = true

which forcefully moves Appium directly into the webview context.

But this also might not work with Appium Desktop (due to https://github.com/appium/appium-desktop/issues/317), and need to be checked.


问:
Bit Hack to get location of bit change
I am needing to figure out a bit-hack to find the first location where the bit-value changes. It could be from 0 to 1 or 1 to 0.

// This would give 0 since no changes happen
let x1 = 0b00000000

// This also gives 0 since there is no change
let x2 = 0b11111111

// This would give 1 since the value changes after the first bit
let x3 = 0b10000000

// This would also give 1 since the value change
// happens at the first bit
let x4 = 0b01111111

// This would return 7 since the change is at the 7th bit
let x5 = 0b00000001

// This would also return 7
let x6 = 0b11111110
```

Any recommendations on an incantation that would give these results?

答:
Like it has been said, you should first NOT it if you have leading ones.  I only knew the cdq method for this.  I learned new commands from that answer. But if you want to implement the bit hacks to do them or you do not have the commands you can try this for the leading zero count:

http://aggregate.org/MAGIC/#Leading%20Zero%20Count

it also uses the ones count:

http://aggregate.org/MAGIC/#Population%20Count%20(Ones%20Count)

there are many hacks for that, you can find also at:

http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

If you have a number that changes multiple times to 0 and 1 and you want to search it starting from least significant bit, get the most significant bit:

http://aggregate.org/MAGIC/#Most%20Significant%201%20Bit

and then do trailing zero count:

http://aggregate.org/MAGIC/#Trailing%20Zero%20Count

another trailing zero count method I learned yesterday is by De Bruijn sequence and table lookup, you can find that here:

https://www.youtube.com/watch?v=ZusiKXcz_ac&t=3619s

at about minute 43.

Title: Bit Hack to get location of bit change

Body:
I am needing to figure out a bit-hack to find the first location where the bit-value changes. It could be from 0 to 1 or 1 to 0.

// This would give 0 since no changes happen
let x1 = 0b00000000

// This also gives 0 since there is no change
let x2 = 0b11111111

// This would give 1 since the value changes after the first bit
let x3 = 0b10000000

// This would also give 1 since the value change
// happens at the first bit
let x4 = 0b01111111

// This would return 7 since the change is at the 7th bit
let x5 = 0b00000001

// This would also return 7
let x6 = 0b11111110

Any recommendations on an incantation that would give these results?


问:
Efficient way of sending a large number of images from client to server
I'm working on a project where one client needs to take several snapshots from a camera (i.e. it's actually taking a short-duration video, hence a stream of frames), then send all images to a server which then performs some processing on these images and returns a result to the client.

Client and server are all running Python3 code.

The critical part is the image sending one.

Some background first, images are *640*480 jpeg* files. JPEG was chosen as a default choice, but lower quality encoding can be selected as well. They are captured in sequence by a camera. We have thus approximately ~600 frames to send. Frame size is around 110KiB.

The client consists of a Raspberry Pi 3 model B+. It sends the frames via wifi to a 5c server. Server and client both reside in the same LAN for the prototype version. But future deployments might be different, both in term of connectivity medium (wired or wireless) and area (LAN or metro).

I've implemented several solutions for this:

Using Python sockets on the server and the client: I'm either sending one frame directly after one frame capture, or I'm sending all images in sequence after the whole stream capture is done.

Using Gstreamer: I'm launching a GStreamer endpoint on my client and directly send the frames to the server as I stream. I'm capturing the stream on the server side with OpenCV compiled with GStreamer support, then save them to the disk.

Now, the issue I'm facing is that even if both solutions work 'well' (they get the 'final' job done, which is to send data to a server and receive a result based on some remote processing), I'm convinced there is a better way to send a large amount of data to a server, using either the Python socket library, or any other available tools.

All personal researches are done on that matter lead me to solutions similar to mine, using Python sockets, or were out of context (relying on other backends than pure Python).

By a better way, I assume:

A solution that saves bandwidth as much as possible.

A solution that sends all data as fast as possible.

For 1. I slightly modified my first solution to archive and compress all captured frames in a .tgz file that I send over to the server. It indeed decreases the bandwidth usage but also increases the time spent on both ends (due to the un/compression processes). It's obviously particularly true when the dataset is large.

For 2. GStreamer allowed me to have a negligible delay between the capture and the reception on my server. I have however no compression at all and for the reasons stated above, I cannot really use this library for further development.

How can I send a large number of images from one client to one server with minimal bandwidth usage and delay in Python?

答: you can restream camera using ffmpeg over network so that client can read it both ways. it will reduce delays.</p>