问:
Flutter Firebase Messaging is Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
I am trying to use Firebase Messaging in a Flutter app. I follow all the instruction from the package.

In my pubspec.yaml I have these packages:

```<code>dependencies:
  flutter:
    sdk: flutter
  ...
  firebase_messaging: ^5.1.5
  ...
</code>```

My main.app is just it:

```<code>void main() {
  runApp(MyApp());
}
</code>```

MyApp is a StatefullWidget and inside the _MyAppState I have:

```<code>    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
   @override
  void initState() {
    super.initState();
    NotificationHandler().initializeFcmNotification();
  }
</code>```

All the code is inside whe notification_handler.dart (thanks to @HarishPenta):

```<code>...
import 'package:firebase_messaging/firebase_messaging.dart';
...

class NotificationHandler {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  FirebaseMessaging _fcm = FirebaseMessaging();
  StreamSubscription iosSubscription;
  static final NotificationHandler _singleton =
  new NotificationHandler._internal();

  factory NotificationHandler() {
    return _singleton;
  }
  NotificationHandler._internal();

  Future<dynamic> myBackgroundMessageHandler(
      Map<String, dynamic> message) async {
    print("onLaunch: $message");
    // Or do other work.
  }

  initializeFcmNotification() async {
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();

    var initializationSettingsAndroid =
    new AndroidInitializationSettings('ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);

    if (Platform.isIOS) {
      iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
        // save the token  OR subscribe to a topic here
      });

      _fcm.requestNotificationPermissions(IosNotificationSettings());
    } else {
      _saveDeviceToken();
    }

    _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      //onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
  }

...}
</code>```

In my AndroidManifest.xml I have:

```<code><activity
            android:name=".MainActivity"
...
<intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
</code>```

and, finally, inside the app/src/main/java//Application.java I have:

```<code>package <my ID app>;  --> the same ID in google-services.json

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;

import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

public class Application extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        GeneratedPluginRegistrant.registerWith(registry);
    }
}
</code>```

Well, the app start OK, and, in foreground, when I send a notification, the app stop and I can see this error message:

```<code>D/AndroidRuntime(26933): Shutting down VM
E/AndroidRuntime(26933): FATAL EXCEPTION: main
E/AndroidRuntime(26933): Process: br.com.htsnet.emergencia, PID: 26933
E/AndroidRuntime(26933): java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/AndroidRuntime(26933):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3167)
E/AndroidRuntime(26933):    at android.app.ActivityThread.access$1900(ActivityThread.java:177)
E/AndroidRuntime(26933):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532)
E/AndroidRuntime(26933):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(26933):    at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime(26933):    at android.app.ActivityThread.main(ActivityThread.java:5951)
E/AndroidRuntime(26933):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(26933):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(26933):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
E/AndroidRuntime(26933):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
E/AndroidRuntime(26933): Caused by: java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/AndroidRuntime(26933):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
E/AndroidRuntime(26933):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:77)
E/AndroidRuntime(26933):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3157)
E/AndroidRuntime(26933):    ... 9 more
</code>```

I am using Android Studio 3.5, Firebase Functions to send notification whith data in paypload (click_action: 'FLUTTER_NOTIFICATION_CLICK').

答: Am faced same issue :  Just removed "Application.class" from android project. Code working fine.</p>

Body:
I am trying to use Firebase Messaging in a Flutter app. I follow all the instruction from the package.

In my pubspec.yaml I have these packages:

dependencies:
  flutter:
    sdk: flutter
  ...
  firebase_messaging: ^5.1.5
  ...

My main.app is just it:

void main() {
  runApp(MyApp());
}

MyApp is a StatefullWidget and inside the _MyAppState I have:

    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
   @override
  void initState() {
    super.initState();
    NotificationHandler().initializeFcmNotification();
  }

All the code is inside whe notification_handler.dart (thanks to @HarishPenta):

...
import 'package:firebase_messaging/firebase_messaging.dart';
...

class NotificationHandler {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  FirebaseMessaging _fcm = FirebaseMessaging();
  StreamSubscription iosSubscription;
  static final NotificationHandler _singleton =
  new NotificationHandler._internal();

  factory NotificationHandler() {
    return _singleton;
  }
  NotificationHandler._internal();

  Future<dynamic> myBackgroundMessageHandler(
      Map<String, dynamic> message) async {
    print("onLaunch: $message");
    // Or do other work.
  }

  initializeFcmNotification() async {
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();

    var initializationSettingsAndroid =
    new AndroidInitializationSettings('ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);

    if (Platform.isIOS) {
      iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
        // save the token  OR subscribe to a topic here
      });

      _fcm.requestNotificationPermissions(IosNotificationSettings());
    } else {
      _saveDeviceToken();
    }

    _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      //onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
  }

...}

In my AndroidManifest.xml I have:

<activity
            android:name=".MainActivity"
...
<intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

and, finally, inside the app/src/main/java//Application.java I have:

package <my ID app>;  --> the same ID in google-services.json

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;

import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

public class Application extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        GeneratedPluginRegistrant.registerWith(registry);
    }
}

Well, the app start OK, and, in foreground, when I send a notification, the app stop and I can see this error message:

D/AndroidRuntime(26933): Shutting down VM
E/AndroidRuntime(26933): FATAL EXCEPTION: main
E/AndroidRuntime(26933): Process: br.com.htsnet.emergencia, PID: 26933
E/AndroidRuntime(26933): java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/AndroidRuntime(26933):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3167)
E/AndroidRuntime(26933):    at android.app.ActivityThread.access$1900(ActivityThread.java:177)
E/AndroidRuntime(26933):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532)
E/AndroidRuntime(26933):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(26933):    at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime(26933):    at android.app.ActivityThread.main(ActivityThread.java:5951)
E/AndroidRuntime(26933):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(26933):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(26933):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
E/AndroidRuntime(26933):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
E/AndroidRuntime(26933): Caused by: java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/AndroidRuntime(26933):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
E/AndroidRuntime(26933):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:77)
E/AndroidRuntime(26933):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3157)
E/AndroidRuntime(26933):    ... 9 more

I am using Android Studio 3.5, Firebase Functions to send notification whith data in paypload (click_action: 'FLUTTER_NOTIFICATION_CLICK').


来源: stackexchange

问:
ZXingScannerView is showing blank screen on coming back from next activity
I am using ZXingScannerView in my android app to scan qr code. When i open app and scan qr code it works fine and go to next activity after scanning required qr code  but when i press back button and again click on scanner button to scan again it shows blank white screen.
I am taking all required permissions.

```<code>public class OpenCamera extends AppCompatActivity implements ZXingScannerView.ResultHandler {
ZXingScannerView scannerView;
    String text="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);
    }

    @Override
    public void handleResult(Result result) {
        try {
          text = result.getText();
            Toast.makeText(this, ""+text, Toast.LENGTH_SHORT).show();
            Intent intent2 = new Intent(this,MainActivity.class);
            intent2.putExtra("code",text);
            setResult(RESULT_OK,intent2);
            finish();
        }
        catch (Exception e)
        {
            Log.i("Open camera",e.getMessage());
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String []{Manifest.permission.CAMERA},
                        1);
                return;
            }
        }
        scannerView.setResultHandler(this);
        scannerView.startCamera();

    }

    @Override
    protected void onPause() {
        super.onPause();
        scannerView.stopCamera();
    }
    @Override
    protected void onStop() {
        super.onStop();
        scannerView.stopCamera();
    }
}
</code>```

Edit: build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.scanqr"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.material:material:1.2.0-alpha04'
    implementation 'com.chaos.view:pinview:1.3.2'
    implementation 'androidx.biometric:biometric:1.0.0-alpha03'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.budiyev.android:code-scanner:2.1.0'

    implementation 'com.google.android.gms:play-services-maps:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-places:16.0.0'
    implementation 'com.google.android.gms:play-services-vision:17.0.2'
    implementation 'com.google.firebase:firebase-appindexing:16.0.2'
    implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
    implementation 'me.dm7.barcodescanner:zxing:1.9'
    implementation 'com.google.android.gms:play-services-auth:16.0.0'
}
</code>```

This is my code...

答:
You have to call resumeCameraPreview() in onResume like this:

```<code> scannerView.setResultHandler(this);
 scannerView.startCamera();
 scannerView.resumeCameraPreview(this);
</code>```

And stop camera preview in onPause():

```<code>scannerView.stopCameraPreview();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using ZXingScannerView in my android app to scan qr code. When i open app and scan qr code it works fine and go to next activity after scanning required qr code  but when i press back button and again click on scanner button to scan again it shows blank white screen.
I am taking all required permissions.

public class OpenCamera extends AppCompatActivity implements ZXingScannerView.ResultHandler {
ZXingScannerView scannerView;
    String text="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);
    }

    @Override
    public void handleResult(Result result) {
        try {
          text = result.getText();
            Toast.makeText(this, ""+text, Toast.LENGTH_SHORT).show();
            Intent intent2 = new Intent(this,MainActivity.class);
            intent2.putExtra("code",text);
            setResult(RESULT_OK,intent2);
            finish();
        }
        catch (Exception e)
        {
            Log.i("Open camera",e.getMessage());
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String []{Manifest.permission.CAMERA},
                        1);
                return;
            }
        }
        scannerView.setResultHandler(this);
        scannerView.startCamera();

    }

    @Override
    protected void onPause() {
        super.onPause();
        scannerView.stopCamera();
    }
    @Override
    protected void onStop() {
        super.onStop();
        scannerView.stopCamera();
    }
}

Edit: build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.scanqr"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.material:material:1.2.0-alpha04'
    implementation 'com.chaos.view:pinview:1.3.2'
    implementation 'androidx.biometric:biometric:1.0.0-alpha03'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.budiyev.android:code-scanner:2.1.0'

    implementation 'com.google.android.gms:play-services-maps:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-places:16.0.0'
    implementation 'com.google.android.gms:play-services-vision:17.0.2'
    implementation 'com.google.firebase:firebase-appindexing:16.0.2'
    implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
    implementation 'me.dm7.barcodescanner:zxing:1.9'
    implementation 'com.google.android.gms:play-services-auth:16.0.0'
}

This is my code...

Body:
You have to call resumeCameraPreview() in onResume like this:

 scannerView.setResultHandler(this);
 scannerView.startCamera();
 scannerView.resumeCameraPreview(this);

And stop camera preview in onPause():

scannerView.stopCameraPreview();


问:
How can I share a function in a react-redux connected component with other components?
I have a function (initialize) defined in a React component that dispatches a bunch of redux actions.

import { setData, doThing, doSomethingElse } from "redux/actions";
import { fetchData } from "services/api";
import { connect } from "react-redux";

class Basic extends Component {
  initialize = () => {
    const { setData, doThing, doSomethingElse } = this.props;
    if (someLogic) {
      doThing();
    } else {
      doSomethingElse();
    }
    fetchData.then(data => setData(data));
  };

  componentDidMount() {
    this.initialize();
  }

  render() {
    const { loading } = this.props;
    if (loading) {
      return
Loading...
;
    }
    return
Content
;
  }
}

const mapStateToProps = ({ state }) => ({
  loading: state.loading
});

const mapDispatchToProps = {
  setData,
  doThing,
  doSomethingElse
};

export default connect(mapStateToProps, mapDispatchToProps)(Basic);```
</div>
</div>
</p>

<p>This works fine in this scenario, but as I'm developing my app I realize I might want to call 'initialize' in several other components as well. What would be the best way for me to extract this function for re-usability in other components?</p>

<p>I'm tempted extract it into a helper function like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import store from "redux/store";

export function initializeHelper() {
  if (someLogic) {
    store.dispatch(doThing());
  } else {
    store.dispatch(doSomethingElse());
  }
  fetchData.then(data => store.dispatch(setData(data)));
}</code>```

And it does work, since the store I'm importing in the helper function is the same store provided in my React app. However, it feels wrong tocall the store directly like this.

Another thing I've tried is using a render prop component that just passes the function as follows:

class Initialize extends Component {
  initialize = () => {
    const { setData, doThing, doSomethingElse } = this.props;
    if (someLogic) {
      doThing();
    } else {
      doSomethingElse();
    }
    fetchData.then(data => setData(data));
  };

  render() {
    return this.props.children(this.initialize)
  }
}

// Wrap any component to pass the function as a prop

<Initialize>
  {initialize => <OtherComponent initialize={initialize} />}
</Initialize>```

But this also feels like the wrong use of the render prop pattern, as the render prop is not sharing any state. It's just sharing a function that primarily dispatches redux actions.

Is there a better way to go about this?

Note: I am not yet planning to use React hooks in my current project.

答:
Have a look at Higher Order Components. As per the docs: 'A higher-order component (HOC) is an advanced technique in React for reusing component logic' which is exactly what you are trying to do.

A Higher Order Component which will share the desired behavior across your components might look like this:

```<code>const withInit = (componentToWrap) => (props) => {
  useEffect(() => {
    // something to execute on mount
  },[])

  return <componentToWrap {...props}/>
}
</code>```

The docs provide ways to do achieve this with classes as well. Hope this helps!

Body:
I have a function (initialize) defined in a React component that dispatches a bunch of redux actions.

import { setData, doThing, doSomethingElse } from "redux/actions";
import { fetchData } from "services/api";
import { connect } from "react-redux";

class Basic extends Component {
  initialize = () => {
    const { setData, doThing, doSomethingElse } = this.props;
    if (someLogic) {
      doThing();
    } else {
      doSomethingElse();
    }
    fetchData.then(data => setData(data));
  };

  componentDidMount() {
    this.initialize();
  }

  render() {
    const { loading } = this.props;
    if (loading) {
      return
Loading...
;
    }
    return
Content
;
  }
}

const mapStateToProps = ({ state }) => ({
  loading: state.loading
});

const mapDispatchToProps = {
  setData,
  doThing,
  doSomethingElse
};

export default connect(mapStateToProps, mapDispatchToProps)(Basic);

This works fine in this scenario, but as I'm developing my app I realize I might want to call 'initialize' in several other components as well. What would be the best way for me to extract this function for re-usability in other components?

I'm tempted extract it into a helper function like this:

import store from "redux/store";

export function initializeHelper() {
  if (someLogic) {
    store.dispatch(doThing());
  } else {
    store.dispatch(doSomethingElse());
  }
  fetchData.then(data => store.dispatch(setData(data)));
}

And it does work, since the store I'm importing in the helper function is the same store provided in my React app. However, it feels wrong tocall the store directly like this.

Another thing I've tried is using a render prop component that just passes the function as follows:

class Initialize extends Component {
  initialize = () => {
    const { setData, doThing, doSomethingElse } = this.props;
    if (someLogic) {
      doThing();
    } else {
      doSomethingElse();
    }
    fetchData.then(data => setData(data));
  };

  render() {
    return this.props.children(this.initialize)
  }
}

// Wrap any component to pass the function as a prop

<Initialize>
  {initialize => <OtherComponent initialize={initialize} />}
</Initialize>

But this also feels like the wrong use of the render prop pattern, as the render prop is not sharing any state. It's just sharing a function that primarily dispatches redux actions.

Is there a better way to go about this?

Note: I am not yet planning to use React hooks in my current project.

Body:
Have a look at Higher Order Components. As per the docs: 'A higher-order component (HOC) is an advanced technique in React for reusing component logic' which is exactly what you are trying to do.

A Higher Order Component which will share the desired behavior across your components might look like this:

const withInit = (componentToWrap) => (props) => {
  useEffect(() => {
    // something to execute on mount
  },[])

  return <componentToWrap {...props}/>
}

The docs provide ways to do achieve this with classes as well. Hope this helps!


问:
fetch all rows from mysql db with php using aFetch($sql) problem
i inherited this code from some-one and this only returns the first row it finds:

```<code>function getMessages($userID, $from, $limit)
{
  $id = $_SESSION['user_id'];
  $sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
  $row = $this->aFetch($sql);
  return $row;
}

function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
      $fnSql = $this->query($sSql);
    }

   while($row = mysql_fetch_assoc($fnSql))
   {
  $aResults[] = $row;
   }
   return  $aResults;
}
</code>```

how can i with this code return all rows where profile_id_to = {$userID} ??
thanks

答:
Try removing the LIMIT clause:

```<code>SELECT *
FROM rc_message_box_table
WHERE profile_id_to = {$userID}
AND rc_message_box_table.profile_id_from NOT IN
(
    SELECT profile_id_block
    FROM rc_blocklist_table
    WHERE profile_id = {$id}
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i inherited this code from some-one and this only returns the first row it finds:

function getMessages($userID, $from, $limit)
{
  $id = $_SESSION['user_id'];
  $sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
  $row = $this->aFetch($sql);
  return $row;
}

function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
      $fnSql = $this->query($sSql);
    }

   while($row = mysql_fetch_assoc($fnSql))
   {
  $aResults[] = $row;
   }
   return  $aResults;
}

how can i with this code return all rows where profile_id_to = {$userID} ??
thanks

Body:
Try removing the LIMIT clause:

SELECT *
FROM rc_message_box_table
WHERE profile_id_to = {$userID}
AND rc_message_box_table.profile_id_from NOT IN
(
    SELECT profile_id_block
    FROM rc_blocklist_table
    WHERE profile_id = {$id}
)


问:
Is it posible to implement functions that use non blocking setTimeout synchronically?
I wonder if it is possible to call these 2 IIF synchronically that they produce at the end something like that?

```<code>######
#####
####
###
##
#
#
##
###
####
#####
###### ?
</code>```

the functions below do delayed console log. The idea is to console log with some delay row by row.

```<code> (function whileLoop(n) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (--n) whileLoop(n);
        }, 2000)
    })(6);

    (function whileLoop(n, m) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (n < m) {
                ++n;
                whileLoop(n, m);
            }
        }, 2000)
    })(1, 6);
</code>```

答:
A typical way to handle the order of execution for two different asynchronous operations would be to use promises.

var d = $.Deferred();

(function whileLoop(n) {
  setTimeout(function () {
    let hashArr = Array.apply(null, Array(n)).map(() => {
      return '#'
    });
    console.log(hashArr);
    if (--n) whileLoop(n);
    else d.resolve();
  }, 2000)
})(6);

d.then(function() {
  (function whileLoop(n, m) {
    setTimeout(function () {
      let hashArr = Array.apply(null, Array(n)).map(() => {
        return '#'
      });
      console.log(hashArr);
      if (n < m) {
        ++n;
        whileLoop(n, m);
      }
    }, 2000)
  })(1, 6);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
I wonder if it is possible to call these 2 IIF synchronically that they produce at the end something like that?

######
#####
####
###
##
#
#
##
###
####
#####
###### ?

the functions below do delayed console log. The idea is to console log with some delay row by row.

 (function whileLoop(n) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (--n) whileLoop(n);
        }, 2000)
    })(6);

    (function whileLoop(n, m) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (n < m) {
                ++n;
                whileLoop(n, m);
            }
        }, 2000)
    })(1, 6);

Body:
A typical way to handle the order of execution for two different asynchronous operations would be to use promises.

var d = $.Deferred();

(function whileLoop(n) {
  setTimeout(function () {
    let hashArr = Array.apply(null, Array(n)).map(() => {
      return '#'
    });
    console.log(hashArr);
    if (--n) whileLoop(n);
    else d.resolve();
  }, 2000)
})(6);

d.then(function() {
  (function whileLoop(n, m) {
    setTimeout(function () {
      let hashArr = Array.apply(null, Array(n)).map(() => {
        return '#'
      });
      console.log(hashArr);
      if (n < m) {
        ++n;
        whileLoop(n, m);
      }
    }, 2000)
  })(1, 6);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Why is the string 'andy' not printing please enter a new username?
```<code>current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")
</code>```

Andy is being printed as username is available.
Also please help me simplify as I am just learning python.

答:
You should try using in to the list:

```<code>current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [i.lower() for i in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")
</code>```

Body:
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Andy is being printed as username is available.
Also please help me simplify as I am just learning python.

Body:
You should try using in to the list:

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [i.lower() for i in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")


问:
SELECT all (but one column as null)
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

```<code>SELECT *, id AS (SELECT '') FROM my_table WHERE 1
</code>```

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

答:
The truly relational language Tutorial D allows a projection (all other other relevant relational operators) to be expressed in terms of the attributes to be removed instead of the ones to be kept e.g.

```<code>my_relvar { ALL BUT ID }
</code>```

(but being truly relational Tutorial D of course doesn't have a concept of null!)

Sadly, SQL does not have such a language feature and you must write in longhand all the column names.

Title: SELECT all (but one column as null)

Body:
in mysql, is it possible to get all columns and data from a table, but select the ID column as NULL?

Something like

SELECT *, id AS (SELECT '') FROM my_table WHERE 1

I want to pull in the ID column, so it doesn't mess up the column count for a later data load, but I want to eliminate the column's value so it doesn't cause key conflicts.

Thanks!

Body:
The truly relational language Tutorial D allows a projection (all other other relevant relational operators) to be expressed in terms of the attributes to be removed instead of the ones to be kept e.g.

my_relvar { ALL BUT ID }

(but being truly relational Tutorial D of course doesn't have a concept of null!)

Sadly, SQL does not have such a language feature and you must write in longhand all the column names.


问:
Unable to run Apache nifi docker container in swarm. Empty response
I am unable to run official nifi image in docker swarm.
When I start container in regular mode:

```<code>docker run --name nifi -p 8080:8080 -d apache/nifi:latest
</code>```

everything works fine and I can access the application under http://localhost:8080/nifi

However when i try to run application in docker swarm:

```<code>docker swarm init
docker stack deploy -c docker-compose.yml nifi
</code>```

With the following docker-compose.yml

```<code>version: "3"
services:
  zookeeper:
    hostname: zookeeper
    container_name: zookeeper
    image: 'bitnami/zookeeper:latest'
    environment:
      - ALLOW_ANONYMOUS_LOGIN=yes
  nifi:
    image: apache/nifi:latest
    ports:
      - "8080:8080"
    expose:
      - "8080"
    environment:
      - NIFI_WEB_HTTP_PORT=8080
      - NIFI_WEB_HTTP_HOST=localhost
      - NIFI_CLUSTER_IS_NODE=true
      - NIFI_CLUSTER_NODE_PROTOCOL_PORT=8082
      - NIFI_ZK_CONNECT_STRING=zookeeper:2181
      - NIFI_ELECTION_MAX_WAIT=1 min
</code>```

Application starts (zookeeper and nifi) but is unaccessible under http://localhost:8080/nifi

```<code>curl http://localhost:8080
curl: (52) Empty reply from server
</code>```

However running the following code:

```<code>docker exec -it 629ecd6949d9 curl -v http://localhost:8080
</code>```

shows that nifi is up and running, but for some reason it does not work from outside container.

I am close to start hitting the wall with my head. How can I fix this?

Best
Paweł

答:
Sorry, if NIFI_WEB_HOST=0.0.0.0 then it will cause problem when nifi container try to communicate with each other.

```<code>    2020-02-20 03:20:13,509 WARN [Replicate Request Thread-5] o.a.n.c.c.h.r.ThreadPoolRequestReplicator
java.net.SocketTimeoutException: timeout
        at okio.Okio$4.newTimeoutException(Okio.java:232)
        at okio.AsyncTimeout.exit(AsyncTimeout.java:285)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:241)
        at okio.RealBufferedSource.indexOf(RealBufferedSource.java:355)
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:227)
        at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
        at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.replicate(OkHttpReplicationClient.java:138)
        at org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.replicate(OkHttpReplicationClient.java:132)
        at org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator.replicateRequest(ThreadPoolRequestReplicator.java:647)
        at org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator$NodeHttpRequest.run(ThreadPoolRequestReplicator.java:839)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Socket closed
        at java.net.SocketInputStream.read(SocketInputStream.java:204)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at okio.Okio$2.read(Okio.java:140)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
        ... 28 common frames omitted
</code>```

Body:
I am unable to run official nifi image in docker swarm.
When I start container in regular mode:

docker run --name nifi -p 8080:8080 -d apache/nifi:latest

everything works fine and I can access the application under http://localhost:8080/nifi

However when i try to run application in docker swarm:

docker swarm init
docker stack deploy -c docker-compose.yml nifi

With the following docker-compose.yml

version: "3"
services:
  zookeeper:
    hostname: zookeeper
    container_name: zookeeper
    image: 'bitnami/zookeeper:latest'
    environment:
      - ALLOW_ANONYMOUS_LOGIN=yes
  nifi:
    image: apache/nifi:latest
    ports:
      - "8080:8080"
    expose:
      - "8080"
    environment:
      - NIFI_WEB_HTTP_PORT=8080
      - NIFI_WEB_HTTP_HOST=localhost
      - NIFI_CLUSTER_IS_NODE=true
      - NIFI_CLUSTER_NODE_PROTOCOL_PORT=8082
      - NIFI_ZK_CONNECT_STRING=zookeeper:2181
      - NIFI_ELECTION_MAX_WAIT=1 min

Application starts (zookeeper and nifi) but is unaccessible under http://localhost:8080/nifi

curl http://localhost:8080
curl: (52) Empty reply from server

However running the following code:

docker exec -it 629ecd6949d9 curl -v http://localhost:8080

shows that nifi is up and running, but for some reason it does not work from outside container.

I am close to start hitting the wall with my head. How can I fix this?

Best
Paweł

Body:
Sorry, if NIFI_WEB_HOST=0.0.0.0 then it will cause problem when nifi container try to communicate with each other.

    2020-02-20 03:20:13,509 WARN [Replicate Request Thread-5] o.a.n.c.c.h.r.ThreadPoolRequestReplicator
java.net.SocketTimeoutException: timeout
        at okio.Okio$4.newTimeoutException(Okio.java:232)
        at okio.AsyncTimeout.exit(AsyncTimeout.java:285)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:241)
        at okio.RealBufferedSource.indexOf(RealBufferedSource.java:355)
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:227)
        at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
        at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall.execute(RealCall.java:77)
        at org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.replicate(OkHttpReplicationClient.java:138)
        at org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.replicate(OkHttpReplicationClient.java:132)
        at org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator.replicateRequest(ThreadPoolRequestReplicator.java:647)
        at org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator$NodeHttpRequest.run(ThreadPoolRequestReplicator.java:839)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Socket closed
        at java.net.SocketInputStream.read(SocketInputStream.java:204)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at okio.Okio$2.read(Okio.java:140)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
        ... 28 common frames omitted


问:
Trying to modify a data from a React Promise Response changes globally
I have created a codesandbox with a simplified version of my problem

https://codesandbox.io/s/new-react-context-api-ei92k

I get something from a fetch (in this case a user)

I then create a local copy of this user and make some changes to it

The problem: Any changes update my initial user object

Can someone tell me how this is possible? and how can I avoid this?

```<code>    import React, { useState, useEffect } from "react";
    import { AppSessionContext } from "./AppContext";
    import Header from "./Header";

    const user = {
      userName: "jsmith",
      firstName: "John",
      lastName: "Smith",
      isAdmin: true
    };
    const loadProfile = () => Promise.resolve(user);

    function createUserWithNewName(userToUpdate) {
      userToUpdate["userName"] = "Dummy";
      return userToUpdate;
    }

    const App = () => {
      const [user, setUser] = useState({});
      const [Loaded, setLoaded] = useState(false);

      var amendedUser = {};

      useEffect(() => {
        loadProfile()
          .then(user => {
            setUser(user);
            console.log(user);
          })
          .then(() => {
            amendedUser = createUserWithNewName(user);
            console.log(amendedUser);
            console.log(user);
          })
          .then(setLoaded(true));
      }, []);

      if (!Loaded) {
        return "Loading";
      }

      return (
        <AppSessionContext.Provider value={{ user }}>
          <div className="App">
            <Header />
          </div>
        </AppSessionContext.Provider>
      );
    };

    export default App;
</code>```

snippet of production code

```<code>loadTableDefault() {

    fetch(defaultUrl(), {method: 'GET'})
    .then(res => res.json())
    .then(response => {
            this.setState({
                data: response,
            })
            return response
        })
    .then(response => {
        this.setState({
            table_data: formatResponsePretty(response),
        })
    })
    .catch(error => console.error('Error:', error));
}
</code>```

formatResponsePretty

```<code>export function formatResponsePretty(oldData) {

    const newData = {
        ...oldData,
    };
    // consider re-writting the flask response to this format
    const obj = { allocations: [] };
    var theRemovedElement = ''
    var ports = []

    ports = Object.values(newData['allocations']['columns']);
    ports.shift();

    var dataArray = ['allocations', 'conditions', 'liquidity', 'hedging']

    for (const index of dataArray) {
        for (const i of newData[index]['data']) {
            theRemovedElement = i.shift();
            if (index === 'allocations') {
                obj[index][theRemovedElement] = i
            }
            else {
                obj[theRemovedElement] = i;
            }
        }
    }

    const rows = []

    let index = 0;

    Object.keys(obj).forEach(element => {
        index = formatting.findIndex(x => x.name === element)
        if (formatting[index] && formatting[index]['type'] === 'number') {
            var new_obj = obj[element].map(function (el) {
                return Number(el * formatting[index]['multiplier']).toFixed(formatting[index]['decimal']) + formatting[index]['symbol']
            })
            rows.push(new_obj)
        }
        else if (formatting[index] && formatting[index]['type'] === 'string') {
            rows.push(obj[element])
        }
        else if (formatting[index] && formatting[index]['type'] === 'boolean') {
            // there should be logic here to display true or false instead of 1 and 0
            // this could be in the upload
            rows.push(obj[element])
        }
        else {
            rows.push(obj[element])
        }

    })

    const arrOfObj = createRecords(ports, rows)

    return {obj: obj, ports: ports, rows: rows, arrOfObj: arrOfObj}
}
</code>```

答:
In createUserWithNewName() you are updating the original user object and returning it.

You instead want to create a new object with all the old user properties, but with just the username changed. Thankfully, object destructuring makes this super easy:

```<code>function createUserWithNewName(oldUser) {
    const newUser = {
        ...oldUser,
        userName: 'Dummy',
    };

    return newUser;
}
</code>```

This will copy all the properties of oldUser to a new object and then just update userName!

You're also going to want to pass user down to that second .then() as it won't currently be available in there:

```<code>  .then(user => {
    setUser(user);
    console.log(user);
    return user;
  })
  .then(user => {
    amendedUser = createUserWithNewName(user);
    console.log(user, amendedUser);
  })

</code>```

Update CodeSandbox link: https://codesandbox.io/s/new-react-context-api-tgqi3

Body:
I have created a codesandbox with a simplified version of my problem

https://codesandbox.io/s/new-react-context-api-ei92k

I get something from a fetch (in this case a user)

I then create a local copy of this user and make some changes to it

The problem: Any changes update my initial user object

Can someone tell me how this is possible? and how can I avoid this?

    import React, { useState, useEffect } from "react";
    import { AppSessionContext } from "./AppContext";
    import Header from "./Header";

    const user = {
      userName: "jsmith",
      firstName: "John",
      lastName: "Smith",
      isAdmin: true
    };
    const loadProfile = () => Promise.resolve(user);

    function createUserWithNewName(userToUpdate) {
      userToUpdate["userName"] = "Dummy";
      return userToUpdate;
    }

    const App = () => {
      const [user, setUser] = useState({});
      const [Loaded, setLoaded] = useState(false);

      var amendedUser = {};

      useEffect(() => {
        loadProfile()
          .then(user => {
            setUser(user);
            console.log(user);
          })
          .then(() => {
            amendedUser = createUserWithNewName(user);
            console.log(amendedUser);
            console.log(user);
          })
          .then(setLoaded(true));
      }, []);

      if (!Loaded) {
        return "Loading";
      }

      return (
        <AppSessionContext.Provider value={{ user }}>

        </AppSessionContext.Provider>
      );
    };

    export default App;

snippet of production code

loadTableDefault() {

    fetch(defaultUrl(), {method: 'GET'})
    .then(res => res.json())
    .then(response => {
            this.setState({
                data: response,
            })
            return response
        })
    .then(response => {
        this.setState({
            table_data: formatResponsePretty(response),
        })
    })
    .catch(error => console.error('Error:', error));
}

formatResponsePretty

export function formatResponsePretty(oldData) {

    const newData = {
        ...oldData,
    };
    // consider re-writting the flask response to this format
    const obj = { allocations: [] };
    var theRemovedElement = ''
    var ports = []

    ports = Object.values(newData['allocations']['columns']);
    ports.shift();

    var dataArray = ['allocations', 'conditions', 'liquidity', 'hedging']

    for (const index of dataArray) {
        for (const i of newData[index]['data']) {
            theRemovedElement = i.shift();
            if (index === 'allocations') {
                obj[index][theRemovedElement] = i
            }
            else {
                obj[theRemovedElement] = i;
            }
        }
    }

    const rows = []

    let index = 0;

    Object.keys(obj).forEach(element => {
        index = formatting.findIndex(x => x.name === element)
        if (formatting[index] && formatting[index]['type'] === 'number') {
            var new_obj = obj[element].map(function (el) {
                return Number(el * formatting[index]['multiplier']).toFixed(formatting[index]['decimal']) + formatting[index]['symbol']
            })
            rows.push(new_obj)
        }
        else if (formatting[index] && formatting[index]['type'] === 'string') {
            rows.push(obj[element])
        }
        else if (formatting[index] && formatting[index]['type'] === 'boolean') {
            // there should be logic here to display true or false instead of 1 and 0
            // this could be in the upload
            rows.push(obj[element])
        }
        else {
            rows.push(obj[element])
        }

    })

    const arrOfObj = createRecords(ports, rows)

    return {obj: obj, ports: ports, rows: rows, arrOfObj: arrOfObj}
}

Body:
In createUserWithNewName() you are updating the original user object and returning it.

You instead want to create a new object with all the old user properties, but with just the username changed. Thankfully, object destructuring makes this super easy:

function createUserWithNewName(oldUser) {
    const newUser = {
        ...oldUser,
        userName: 'Dummy',
    };

    return newUser;
}

This will copy all the properties of oldUser to a new object and then just update userName!

You're also going to want to pass user down to that second .then() as it won't currently be available in there:

  .then(user => {
    setUser(user);
    console.log(user);
    return user;
  })
  .then(user => {
    amendedUser = createUserWithNewName(user);
    console.log(user, amendedUser);
  })

Update CodeSandbox link: https://codesandbox.io/s/new-react-context-api-tgqi3


问:
Scan this from a text file into 2 arrays using C
Im having trouble parsing someething like this into an array.

So my text file test.txt has this line:
(1231212A, 1231212B)    (1231212C, 321128D)

im trying to scan this into an array but it needs to be divided up into parts

part1 of type int should be : 123

part2 : 12

part3 : 12

part4 (char): A

and I need to do this 4 times within the line

Here is the code i have but it is not working properly

```<code>{
int nums[1][12];
char chars[1][4];
FILE *file;

file = fopen("test.txt", "r");
if (file != NULL){

fscanf(file , "%*s%3d %2d %2d %s %*s %2d %2d %2d %s%*s        %*s%3d %2d %2d %s%*s %2d %2d %2d %s%*s"
, &nums[0][0],&nums[0][1],&nums[0][2],&chars[0][0],&nums[0][3],&nums[0][4],&nums[0][5],&chars[0]
[1],&nums[0][6],&nums[0][7],&nums[0][8],&chars[0][2],&nums[0][9],&chars[0][10],&nums[0][11],&chars[0]
[3]);
}
</code>```

when I print these arrays they do not print the right numbers and characters.
I need help with the fscanf part
Thank You

答:
After reading a line from the file with fgets(), parse the string with sscanf() including "%n" to detect how much was scanned.

Using string literal concatenation in the format helps too.

```<code>//                           v---not s
#define GROUP_FMT "%3d%2d%2d%c"

int n = 0;
sscanf(line, " (" GROUP_FMT " ," GROUP_FMT " ) (" GROUP_FMT " ," GROUP_FMT " ) %n",
  &nums[0][0], &nums[0][ 1], &nums[0][ 2], &chars[0][0],
  &nums[0][3], &nums[0][ 4], &nums[0][ 5], &chars[0][1],
  &nums[0][6], &nums[0][ 7], &nums[0][ 8], &chars[0][2],
  &nums[0][9], &nums[0][10], &nums[0][11], &chars[0][3], &n);
// Did scanning reach the %n and was that the end of the string?
if (n && line[n] == '\0') Success();
else Fail();
</code>```

Body:
Im having trouble parsing someething like this into an array.

So my text file test.txt has this line:
(1231212A, 1231212B)    (1231212C, 321128D)

im trying to scan this into an array but it needs to be divided up into parts

part1 of type int should be : 123

part2 : 12

part3 : 12

part4 (char): A

and I need to do this 4 times within the line

Here is the code i have but it is not working properly

{
int nums[1][12];
char chars[1][4];
FILE *file;

file = fopen("test.txt", "r");
if (file != NULL){

fscanf(file , "%*s%3d %2d %2d %s %*s %2d %2d %2d %s%*s        %*s%3d %2d %2d %s%*s %2d %2d %2d %s%*s"
, &nums[0][0],&nums[0][1],&nums[0][2],&chars[0][0],&nums[0][3],&nums[0][4],&nums[0][5],&chars[0]
[1],&nums[0][6],&nums[0][7],&nums[0][8],&chars[0][2],&nums[0][9],&chars[0][10],&nums[0][11],&chars[0]
[3]);
}

when I print these arrays they do not print the right numbers and characters.
I need help with the fscanf part
Thank You

Body:
After reading a line from the file with fgets(), parse the string with sscanf() including "%n" to detect how much was scanned.

Using string literal concatenation in the format helps too.

//                           v---not s
#define GROUP_FMT "%3d%2d%2d%c"

int n = 0;
sscanf(line, " (" GROUP_FMT " ," GROUP_FMT " ) (" GROUP_FMT " ," GROUP_FMT " ) %n",
  &nums[0][0], &nums[0][ 1], &nums[0][ 2], &chars[0][0],
  &nums[0][3], &nums[0][ 4], &nums[0][ 5], &chars[0][1],
  &nums[0][6], &nums[0][ 7], &nums[0][ 8], &chars[0][2],
  &nums[0][9], &nums[0][10], &nums[0][11], &chars[0][3], &n);
// Did scanning reach the %n and was that the end of the string?
if (n && line[n] == '\0') Success();
else Fail();


问:
How to print the const in html tag in react js?
I have a localstorage value in const i need to use in html tag.How to do so?

My js code is:

```<code>componentDidMount() {
  const userName = localStorage.getItem('userName');
  console.log(userName);

}
</code>```

My Html code where i need to use is:

```<code><Dropdown.Toggle className="nav-link count-indicator bg-transparent">
                  <span className="profile-text"></span>
                  userName here
                </Dropdown.Toggle>
</code>```

答:
You can render any dynamic value by wrapping the value using {} in JSX

```<code><Dropdown.Toggle className="nav-link count-indicator bg-transparent">
   <span className="profile-text"></span>{localStorage.getItem('userName');}
</Dropdown.Toggle>
</code>```

Or if that value is dynamic and if component should rerender when the value changes you can store it in a state

like

```<code> export default class App extends React.Component {
  state = {
    username: ""
  };

  componentDidMount() {
    localStorage.setItem("username", "TEST USERNAME");
    this.setState({ username: localStorage.getItem("username") });
  }

  componentWillUnmount() {
    localStorage.removeItem("username");
  }

  render() {
    return (
      <>
        <h1>Username from state is {this.state.username}</h1>
        <h1>
          Username directly from localStorage {localStorage.getItem("username")}
        </h1>
      </>
    );
  }
}
</code>```

Please find the working code sandbox in this link

Body:
I have a localstorage value in const i need to use in html tag.How to do so?

My js code is:

componentDidMount() {
  const userName = localStorage.getItem('userName');
  console.log(userName);

}

My Html code where i need to use is:

<Dropdown.Toggle className="nav-link count-indicator bg-transparent">

                  userName here
                </Dropdown.Toggle>

Body:
You can render any dynamic value by wrapping the value using {} in JSX

<Dropdown.Toggle className="nav-link count-indicator bg-transparent">
   <span className="profile-text"></span>{localStorage.getItem('userName');}
</Dropdown.Toggle>

Or if that value is dynamic and if component should rerender when the value changes you can store it in a state

like

 export default class App extends React.Component {
  state = {
    username: ""
  };

  componentDidMount() {
    localStorage.setItem("username", "TEST USERNAME");
    this.setState({ username: localStorage.getItem("username") });
  }

  componentWillUnmount() {
    localStorage.removeItem("username");
  }

  render() {
    return (
      <>
        <h1>Username from state is {this.state.username}</h1>
        <h1>
          Username directly from localStorage {localStorage.getItem("username")}
        </h1>
      </>
    );
  }
}

Please find the working code sandbox in this link


问:
Laravel : convert grouped data to one row
Hello please i want to convert grouped data with duplicated keys and different values to one row.
For example :

```<code>    "book1" {
    {
        "id" : "1",
        "group" : "book1",
        "name" : "Book X",
        "buy" : "null",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "100",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "null",
        "test" : "344",
    }
 },
    "book2" {
 {
        "id" : "1",
        "group" : "book2",
        "name" : "Book Y",
        "buy" : "null",
        "test" : "null",
    }
    ....
 }
    ...
</code>```

what i want to do is convert all this arrays with common key to one array or one row in the database where data are grouped like the example the data are grouped by group field
and what i want to do is like that :

```<code>{
  "id" : "1",
  "group" : "book1",
  "name" : "Book X",
  "buy" : "100",
  "test" : "344",
}
</code>```

Please could you help to fix by php code (laravel model) or SQL query and thank you so much !

答:
try this

```<code> $data = []; // your data
    $response = [];
    foreach($data as $key => $d){
       if($d['id'] != null) $response[$key]['id'] = $d['id'];
       if($d['group'] != null) $response[$key]['group'] = $d['group'];
       if($d['name'] != null) $response[$key]['name'] = $d['name'];
       if($d['buy'] != null) $response[$key]['buy'] = $d['buy'];
       if($d['test'] != null) $response[$key]['test'] = $d['test'];

    }
</code>```

EDITED

you have use " " fo null so use like below

```<code>$response = [];
        foreach($data as $key => $d){
           if($d['id'] != "null") $response[$d['group']]['id'] = $d['id'];
           if($d['group'] != "null") $response[$d['group']]['group'] = $d['group'];
           if($d['name'] != "null") $response[$d['group']]['name'] = $d['name'];
           if($d['buy'] != "null") $response[$d['group']]['buy'] = $d['buy'];
           if($d['test'] != "null") $response[$d['group']]['test'] = $d['test'];

        }
</code>```

EDITED 2

```<code>$response = [];
            foreach($data as $key => $row){
                $array = [];
               foreach($row as $d){
                if($d['id'] != null) $array['id'] = $d['id'];
                if($d['group'] != null) $array['group'] = $d['group'];
                if($d['name'] != null) $array['name'] = $d['name'];
                if($d['buy'] != null) $array['buy'] = $d['buy'];
                if($d['test'] != null) $array['test'] = $d['test'];
               }
              $response[$key][] = $array;
            }

    dd($response);
</code>```

Body:
Hello please i want to convert grouped data with duplicated keys and different values to one row.
For example :

    "book1" {
    {
        "id" : "1",
        "group" : "book1",
        "name" : "Book X",
        "buy" : "null",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "100",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "null",
        "test" : "344",
    }
 },
    "book2" {
 {
        "id" : "1",
        "group" : "book2",
        "name" : "Book Y",
        "buy" : "null",
        "test" : "null",
    }
    ....
 }
    ...

what i want to do is convert all this arrays with common key to one array or one row in the database where data are grouped like the example the data are grouped by group field
and what i want to do is like that :

{
  "id" : "1",
  "group" : "book1",
  "name" : "Book X",
  "buy" : "100",
  "test" : "344",
}

Please could you help to fix by php code (laravel model) or SQL query and thank you so much !

Body:
try this

 $data = []; // your data
    $response = [];
    foreach($data as $key => $d){
       if($d['id'] != null) $response[$key]['id'] = $d['id'];
       if($d['group'] != null) $response[$key]['group'] = $d['group'];
       if($d['name'] != null) $response[$key]['name'] = $d['name'];
       if($d['buy'] != null) $response[$key]['buy'] = $d['buy'];
       if($d['test'] != null) $response[$key]['test'] = $d['test'];

    }

EDITED

you have use " " fo null so use like below

$response = [];
        foreach($data as $key => $d){
           if($d['id'] != "null") $response[$d['group']]['id'] = $d['id'];
           if($d['group'] != "null") $response[$d['group']]['group'] = $d['group'];
           if($d['name'] != "null") $response[$d['group']]['name'] = $d['name'];
           if($d['buy'] != "null") $response[$d['group']]['buy'] = $d['buy'];
           if($d['test'] != "null") $response[$d['group']]['test'] = $d['test'];

        }

EDITED 2

$response = [];
            foreach($data as $key => $row){
                $array = [];
               foreach($row as $d){
                if($d['id'] != null) $array['id'] = $d['id'];
                if($d['group'] != null) $array['group'] = $d['group'];
                if($d['name'] != null) $array['name'] = $d['name'];
                if($d['buy'] != null) $array['buy'] = $d['buy'];
                if($d['test'] != null) $array['test'] = $d['test'];
               }
              $response[$key][] = $array;
            }

    dd($response);


问:
Unable to use AAC/AptX codec for bluetooth audio on macOS
When accessing the Bluetooth Explorer and setting the "Enable AAC" and "Force use AptX" to true, all the bluetooth audio devices still use the SBC codec.

When pressing "Reset audio defaults" - bluetooth explorer crashes with:

```<code>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'
</code>```

Tried to use these terminal commands, but still no luck.

```<code>sudo defaults write bluetoothaudiod "Enable AptX codec" -bool true
sudo defaults write bluetoothaudiod "Enable AAC codec" -bool true
</code>```

I'm on a MacBook Pro (Retina, 13-inch, Mid 2014), macOS Catalina 10.15.1
I feel like it's the first time I have a problem that I can't find any info on in google.

Please help! :p

答:
I have same issue with bluetooth exlplore so i tried disabled the aptx and enabled the AAC via terminal and it works. now my active coded is AAC</p>

```<code>sudo defaults write bluetoothaudiod "Enable AptX codec" -bool false
sudo defaults write bluetoothaudiod "Enable AAC codec" -bool true
</code>```

Body:
When accessing the Bluetooth Explorer and setting the "Enable AAC" and "Force use AptX" to true, all the bluetooth audio devices still use the SBC codec.

When pressing "Reset audio defaults" - bluetooth explorer crashes with:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'

Tried to use these terminal commands, but still no luck.

sudo defaults write bluetoothaudiod "Enable AptX codec" -bool true
sudo defaults write bluetoothaudiod "Enable AAC codec" -bool true

I'm on a MacBook Pro (Retina, 13-inch, Mid 2014), macOS Catalina 10.15.1
I feel like it's the first time I have a problem that I can't find any info on in google.

Please help! :p

Body:
I have same issue with bluetooth exlplore so i tried disabled the aptx and enabled the AAC via terminal and it works. now my active coded is AAC

sudo defaults write bluetoothaudiod "Enable AptX codec" -bool false
sudo defaults write bluetoothaudiod "Enable AAC codec" -bool true


问:
Make header available on all components except on login
Supposed I am importing a header component on layouts/default.vue

```<code><template>
  <div>
    <b-container class="mt-5">
      <b-row>
        <b-col md="6" class="mb-3">
          <Header />
        </b-col>
        <b-col md="6">
          <nuxt />
        </b-col>
      </b-row>
    </b-container>
    <Header/>
    <nuxt/>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";

export default {
  components: {
    Header
  }
};
</script>

<style>
...
</style>
</code>```

and that header will be render on all components.

My question is how can I make the header available on all components except on my Login.vue?

Any idea on where can I start to achieve this.

答:
Solved by reading the documentation on https://nuxtjs.org/guide/views/ layouts section. I created another layout file on layouts folder login.vue and use it on my main login.vue

```<code>export default {
  layout: 'login' // coming from layouts folder
  // page component definitions
}
</code>```

Body:
Supposed I am importing a header component on layouts/default.vue

<template>

          <nuxt />

    <nuxt/>

</template>

and that header will be render on all components.

My question is how can I make the header available on all components except on my Login.vue?

Any idea on where can I start to achieve this.

Body:
Solved by reading the documentation on https://nuxtjs.org/guide/views/ layouts section. I created another layout file on layouts folder login.vue and use it on my main login.vue

export default {
  layout: 'login' // coming from layouts folder
  // page component definitions
}


问:
Azure Subnet-to-Subnet Security Rules without Application Security Groups
I'm trying to understand the Network Security Groups and Application Security Groups. What I'm trying to achieve is I have a basic set up as below.

In my vnet, I have 2 subnets which are front-end and back-end and I have 2 NSGs that each subnet is assigned to.

Let's say I decided to allow RDP requests on my "back-end" subnet only for requests coming from the "front-end" subnet and deny any other RDP requests coming from other subnets.

I know that if I create ASGs and assign the FrontEnd VM and BackEnd VM an application security group then I can create a rule on NSG which is to allow RDP request from one ASG to the other ASG to achieve this but if you have dozens of VMs in a subnet then you wouldn't want to waste time to assign an ASG to every VM.

Is there a way to define a rule on a subnet that allows specific requests coming from other subnets?

答: create a rule and set the source to VirtualNetwork that will allow anyone from inside the Virtual Network (and peered ones) to send that type of traffic. If you want subnet granularity - you'd have to use subnet IP address ranges to allow\deny specific traffic patterns. You might also want to override the default rule to allow anything inside the virtual network


答:
You can use list comprehension to convert the usernames in current_users to lowercase. Secondly, you've to check whether the new_user is already present in current_users to do that you have to use in keyword.

The in keyword

tests whether or not a sequence contains a certain value.

here is code,

```<code>current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [user.lower() for user in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")
</code>```

Hope it helps!

Title: Why is the string 'andy' not printing please enter a new username?

Body:
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Andy is being printed as username is available.
Also please help me simplify as I am just learning python.

Body:
You can use list comprehension to convert the usernames in current_users to lowercase. Secondly, you've to check whether the new_user is already present in current_users to do that you have to use in keyword.

The in keyword

tests whether or not a sequence contains a certain value.

here is code,

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

current_users = [user.lower() for user in current_users]

for new_user in new_users:
    if new_user in current_users:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Hope it helps!


问:
Why are multiple media queries not working?
Trying to get multiple media queries to work on mobile but it only recognizes the first one and the second one does nothing. Please help and thanks.

It won't let me post without writing more text so just ignore this haha.

Again: It won't let me post without writing more text so just ignore this haha.

link to application

/* Medium sized screen */

@media all and (max-width: 1300px) {
  #left {
    width: 300px;
  }
  #right {
    width: calc(100% - 300px);
  }
  /* Filters */
  .filters {
    right: 100%;
    width: 100%;
    background-color: #F7F7F7;
    transition: right 1s;
    position: absolute;
    z-index: 1;
    top: 50px;
    height: calc(100% - 50px);
  }
  .filters .close {
    display: block;
    position: absolute;
    font-size: 30px;
    right: 0;
  }
  .filters.show {
    right: 0;
  }
  .filtersIcon {
    display: flex;
  }
  /* Drink list */
  .totalDrinks {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .drinkList {
    width: 100%;
  }
}

/* Small screens */

@media all and (max-width: 900px) {
  #right {
    left: 100%
  }
  #left {
    width: 100%;
    position: absolute;
  }
  .drinkItem {
    min-height: 280px;
  }
}```
</div>
</div>
</p>

<p><strong>EDIT</strong>
I found the issue, I forgot to add this in the header</p>

```<meta name="viewport" content="width=device-width, initial-scale=1.0">
```

答:
It may work try this..</p>

```<code>@media only screen and (max-width: 1300px) {
  //styles//
}
</code>```

Body:
Trying to get multiple media queries to work on mobile but it only recognizes the first one and the second one does nothing. Please help and thanks.

It won't let me post without writing more text so just ignore this haha.

Again: It won't let me post without writing more text so just ignore this haha.

link to application

/* Medium sized screen */

@media all and (max-width: 1300px) {
  #left {
    width: 300px;
  }
  #right {
    width: calc(100% - 300px);
  }
  /* Filters */
  .filters {
    right: 100%;
    width: 100%;
    background-color: #F7F7F7;
    transition: right 1s;
    position: absolute;
    z-index: 1;
    top: 50px;
    height: calc(100% - 50px);
  }
  .filters .close {
    display: block;
    position: absolute;
    font-size: 30px;
    right: 0;
  }
  .filters.show {
    right: 0;
  }
  .filtersIcon {
    display: flex;
  }
  /* Drink list */
  .totalDrinks {
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }
  .drinkList {
    width: 100%;
  }
}

/* Small screens */

@media all and (max-width: 900px) {
  #right {
    left: 100%
  }
  #left {
    width: 100%;
    position: absolute;
  }
  .drinkItem {
    min-height: 280px;
  }
}

EDIT
I found the issue, I forgot to add this in the header

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Body:
It may work try this..

@media only screen and (max-width: 1300px) {
  //styles//
}


问:
Concatenate strings from array in PHP ignoring blanks
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);
```

<p>However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?</p>

<pre class="lang-php prettyprint-override"><code>public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}
</code>```

答:
Adapted from an example using array_filter:

return implode($glue, array_filter($arrayOfStrings, function($element) {
    return $element !== null && $element !== '';
}));
```

Body:
Similar to this question but for PHP.  I want to concatenate an array of strings but ignore blanks.

For instance, suppose I want to build a full_name attribute in Laravel using $this->title, $this->first_name, and $this->last_name, each separated by single space.  The simplest thought I had was to put them all into an array and pass it into implode() as in below:

implode(' ', [$this->title, $this->first_name, $this->last_name]);

However I don't know whether those values are actually going to be set or not.  And if they are set, I don't want empty strings to pollute the output with multiple spaces between non-empty elements.  Is there a built-in function or at least a simpler/shorter way to do the below?

public function concatenateStringsFromArray($glue = ' ', $arrayOfStrings)
{
    $result = '';
    foreach($arrayOfStrings as $piece)
        $result .= isset($piece) ? $piece . $glue : '';
    return $result;
}


问:
Is there replacement for cat on Windows
I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

答:
If you have control over the machine where you're doing your work, I highly recommend installing GnuWin32. Just "Download All" and let the wget program retrieve all the packages. You will then have access to cat, grep, find, gzip, tar, less, and hundreds of others.

GnuWin32 is one of the first things I install on a new Windows box.

OwnerDisplayName: Artem Tikhomirov

Title: Is there replacement for cat on Windows

LastEditorDisplayName: Greg Hewgill

OwnerDisplayName: David Citron

ContentLicense: CC BY-SA 2.5