问:
How to create repeatable network requests with RxJava?
I need my request to repeat once every 30 seconds. How can I force repeatWhen in this code?</p>
```<code>override fun loadData() {
    disposable.add(
        weatherRepository.getCurrentLocation(activity)
            .flatMap { weatherRepository.getWeather(it.currentLocation).subscribeOn(Schedulers.io()) }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                mView.showWeather()
                mView.setupWeather(it)
            }, {
                checkNetworkConnection()
                Log.d("Error", it.toString())
            })
            )
        }
</code>```

答:
You need to add this before subscribeOn to repeat the same request:

```<code>.repeatWhen { completed -> completed.delay(30, TimeUnit.SECONDS) }
</code>```

So it will call the same request every 30 seconds of interval.

So your code becomes:

```<code>disposable.add(weatherRepository.getCurrentLocation(activity)
            .flatMap { weatherRepository.getWeather(it.currentLocation)
            .repeatWhen { completed -> completed.delay(30, TimeUnit.SECONDS) }
            .subscribeOn(Schedulers.io()) }
    ....
</code>```

Body:
I need my request to repeat once every 30 seconds. How can I force repeatWhen in this code?

override fun loadData() {
    disposable.add(
        weatherRepository.getCurrentLocation(activity)
            .flatMap { weatherRepository.getWeather(it.currentLocation).subscribeOn(Schedulers.io()) }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                mView.showWeather()
                mView.setupWeather(it)
            }, {
                checkNetworkConnection()
                Log.d("Error", it.toString())
            })
            )
        }

Body:
You need to add this before subscribeOn to repeat the same request:

.repeatWhen { completed -> completed.delay(30, TimeUnit.SECONDS) }

So it will call the same request every 30 seconds of interval.

So your code becomes:

disposable.add(weatherRepository.getCurrentLocation(activity)
            .flatMap { weatherRepository.getWeather(it.currentLocation)
            .repeatWhen { completed -> completed.delay(30, TimeUnit.SECONDS) }
            .subscribeOn(Schedulers.io()) }
    ....


来源: stackexchange

问:
WP SEO by Yoast - How to change og:image size?
I want to change the og:image that Yoast SEO generates, to some custom height and width (eg 1200x630) because I'm uploading very large images. I've tried adding this code in functions.php but doesn't work. Please help</p>
```<code>function add_share_image_sizes() {
    add_image_size( 'facebook-share', 1200, 630, true );

}
add_action( 'after_setup_theme', 'add_share_image_sizes' );

function set_yoast_facebook_share_image_size() {
    return 'facebook-share';
}
add_filter( 'wpseo_opengraph_image_size', 'set_yoast_facebook_share_image_size' );
</code>```

答:
You need to pass a parameter.</p>
```<code>function add_share_image_sizes() {
    add_image_size( 'facebook-share', 1200, 630, true );

}
add_action( 'after_setup_theme', 'add_share_image_sizes' );

function set_yoast_facebook_share_image_size($img_size) {
    return 'facebook-share';
}
add_filter( 'wpseo_opengraph_image_size', 'set_yoast_facebook_share_image_size' );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to change the og:image that Yoast SEO generates, to some custom height and width (eg 1200x630) because I'm uploading very large images. I've tried adding this code in functions.php but doesn't work. Please help

function add_share_image_sizes() {
    add_image_size( 'facebook-share', 1200, 630, true );

}
add_action( 'after_setup_theme', 'add_share_image_sizes' );

function set_yoast_facebook_share_image_size() {
    return 'facebook-share';
}
add_filter( 'wpseo_opengraph_image_size', 'set_yoast_facebook_share_image_size' );

Body:
You need to pass a parameter.

function add_share_image_sizes() {
    add_image_size( 'facebook-share', 1200, 630, true );

}
add_action( 'after_setup_theme', 'add_share_image_sizes' );

function set_yoast_facebook_share_image_size($img_size) {
    return 'facebook-share';
}
add_filter( 'wpseo_opengraph_image_size', 'set_yoast_facebook_share_image_size' );


问:
FailedAttachVolume in openshift for FC storage
I have created following yaml files

fc-pod.yaml

fc-pvc.yaml

when i create fc pod it always goes to ContainerCreating state and give me the following error when i describe the pod.

Warning  FailedAttachVolume  83s

attachdetach-controller  AttachVolume.Attach failed for volume
"csiunity-d93a52838d" : rpc error: code = InvalidArgument desc =
runid=95 Cannot publish volume as protocol in the Storage class is
'FC' but the node has no valid FC initiators   Warning  FailedMount

29s                    kubelet                  Unable to attach or
mount volumes: unmounted volumes=[dy-fc-unity], unattached
volumes=[dy-fc-unity kube-api-access-psrcp]: timed out waiting for the
condition   Warning  FailedAttachVolume  19s

attachdetach-controller  AttachVolume.Attach failed for volume
"csiunity-d93a52838d" : rpc error: code = InvalidArgument desc =
runid=96 Cannot publish volume as protocol in the Storage class is
'FC' but the node has no valid FC initiators

I have created pvc, storage classes and secrets etc.
I have already created nfs and iscsi pods with the same method and they are created.

please check my fc-pod.yaml file below

```<code>apiVersion: v1
kind: Pod
metadata:
  name: dynamic-fc-pod
  namespace: unity
spec:
  containers:
  - name: container
    image: nginx
    ports:
      - containerPort: 80
        name: "http-server"
    volumeMounts:
      - mountPath: "/usr/share/nginx/html"
        name: dy-fc-unity
  volumes:
    - name: dy-fc-unity
      persistentVolumeClaim:
        claimName: dynamic-fc-pvc
</code>```

答:
I found that I have fc connectivity issue on the backend. thats why FC pods were not creating.

If you faced similar problem, solve it with

Change nginx image tag.

Check fc connectivity

Check protocol in storage class

Delete the pvc and pod

When creating again change container name

Body:
I have created following yaml files

fc-pod.yaml

fc-pvc.yaml

when i create fc pod it always goes to ContainerCreating state and give me the following error when i describe the pod.

Warning  FailedAttachVolume  83s

attachdetach-controller  AttachVolume.Attach failed for volume
"csiunity-d93a52838d" : rpc error: code = InvalidArgument desc =
runid=95 Cannot publish volume as protocol in the Storage class is
'FC' but the node has no valid FC initiators   Warning  FailedMount

29s                    kubelet                  Unable to attach or
mount volumes: unmounted volumes=[dy-fc-unity], unattached
volumes=[dy-fc-unity kube-api-access-psrcp]: timed out waiting for the
condition   Warning  FailedAttachVolume  19s

attachdetach-controller  AttachVolume.Attach failed for volume
"csiunity-d93a52838d" : rpc error: code = InvalidArgument desc =
runid=96 Cannot publish volume as protocol in the Storage class is
'FC' but the node has no valid FC initiators

I have created pvc, storage classes and secrets etc.
I have already created nfs and iscsi pods with the same method and they are created.

please check my fc-pod.yaml file below

apiVersion: v1
kind: Pod
metadata:
  name: dynamic-fc-pod
  namespace: unity
spec:
  containers:
  - name: container
    image: nginx
    ports:
      - containerPort: 80
        name: "http-server"
    volumeMounts:
      - mountPath: "/usr/share/nginx/html"
        name: dy-fc-unity
  volumes:
    - name: dy-fc-unity
      persistentVolumeClaim:
        claimName: dynamic-fc-pvc


问:
How does Firefox process history to show in the location bar's small black down arrow popup?
There's a nice feature in Firefox's awesome bar. It displays your most popular sites in a dropdown list when clicking on a small black down arrow icon on the right side of bar.

There's also a Google Chrome extension which does almost the same but in a less usable way:
https://chrome.google.com/webstore/detail/logbmehmiacemkimbpcbjgaikobdndah

I want to optimize this extension a little so the results are like in Firefox. The main difference between Chrome's extension and Firefox's feature is that an extension doesn't process the urls to display shorter path versions. Firefox reduces urls and I often can see just domains without specified paths. However urls like twitter.com/username appear with the path part of url.

It would be great to learn the algorithm Firefox uses for that. I think it is dealing with frecencies somehow.

Any tips are welcome.
Thank you.

答:
That list purely contains url's you have visited using the awesomebar, or typing the url directly. From that list it picks the most popular.

Considering you usually do not type long url's, the list mostly contain short one's. I myself have 10 short and 2 long url's.

ContentLicense: CC BY-SA 3.0


问:
will golang closure memory leak?
let's say i have this closure func

```<code>package main

type A struct {
    Name string
}

func main() {
    s := func(name string) *A {
        return &A{
            Name: name,
        }
    }("checkmate")

    s.Name = "bbb"
}
</code>```

i have tested with benchmark and gcflags and this is the result

```<code>cpu: Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
BenchmarkMain-4         1000000000               0.4877 ns/op          0 B/op          0 allocs/op
</code>```

go build -gcflags "-m"

```<code>./main.go:8:7: can inline main.func1
./main.go:7:6: can inline main
./main.go:12:3: inlining call to main.func1
./main.go:12:3: &A{...} does not escape
</code>```

is this still memory safe? or maybe there's something missing for my memory allocation check?

答: No, closures do not leak memory.</p>

Title: will golang closure memory leak?

Body:
let's say i have this closure func

package main

type A struct {
    Name string
}

func main() {
    s := func(name string) *A {
        return &A{
            Name: name,
        }
    }("checkmate")

    s.Name = "bbb"
}

i have tested with benchmark and gcflags and this is the result

cpu: Intel(R) Core(TM) i3-10110U CPU @ 2.10GHz
BenchmarkMain-4         1000000000               0.4877 ns/op          0 B/op          0 allocs/op

go build -gcflags "-m"

./main.go:8:7: can inline main.func1
./main.go:7:6: can inline main
./main.go:12:3: inlining call to main.func1
./main.go:12:3: &A{...} does not escape

is this still memory safe? or maybe there's something missing for my memory allocation check?

Body: No, closures do not leak memory.


问:
Maps in Jetpack compose
I'm trying to get a simple map as my mainActivity to test how maps with compose works. Unfortunately I just fail at the beginning with an Errormessage which says basically nothing but "IllegalStateException".
I've tried to extract the map code from the original Google example here:
https://github.com/android/compose-samples/tree/main/Crane
I've tried to rebuild a simple Composable, made an API Key at Google Cloud Platform and added it to my manifest.

Thats the MainActivity:

package com.veloce.mapstesting

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.FloatRange
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.libraries.maps.CameraUpdateFactory
import com.google.android.libraries.maps.GoogleMap
import com.google.android.libraries.maps.MapView
import com.google.android.libraries.maps.model.LatLng
import com.google.maps.android.ktx.addMarker
import com.google.maps.android.ktx.awaitMap
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val mapView = rememberMapViewWithLifecycle()
            MapViewContainer(mapView)
        }
    }
}

const val InitialZoom = 5f
const val MinZoom = 2f
const val MaxZoom = 20f

@Composable
fun MapViewContainer(map: MapView) {
    val cameraPosition = remember {
        LatLng(48.2050491798, 16.3701485194)
    }

    LaunchedEffect(map) {
        val googleMap = map.awaitMap()
        googleMap.addMarker { position(cameraPosition) }
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(cameraPosition))
    }

    var zoom by rememberSaveable(map) { mutableStateOf(InitialZoom) }
    ZoomControls(zoom) {
        zoom = it.coerceIn(MinZoom, MaxZoom)
    }

    val coroutineScope = rememberCoroutineScope()
    AndroidView({ map }) { mapView ->
        val mapZoom = zoom
        coroutineScope.launch {
            val googleMap = mapView.awaitMap()
            googleMap.setZoom(mapZoom)
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(cameraPosition))
        }
    }
}

@Composable
private fun ZoomControls(
    zoom: Float,
    onZoomChanged: (Float) -> Unit
) {
    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
        ZoomButton("-", onClick = { onZoomChanged(zoom * 0.8f) })
        ZoomButton("+", onClick = { onZoomChanged(zoom * 1.2f) })
    }
}

@Composable
fun ZoomButton(text: String, onClick: () -> Unit) {
    Button(
        modifier = Modifier.padding(8.dp),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = MaterialTheme.colors.onPrimary,
            contentColor = MaterialTheme.colors.primary
        ),
        onClick = onClick
    ) {
        Text(text = text, style = MaterialTheme.typography.h5)
    }
}

fun GoogleMap.setZoom(
    @FloatRange(from = MinZoom.toDouble(), to = MaxZoom.toDouble()) zoom: Float
) {
    resetMinMaxZoomPreference()
    setMinZoomPreference(zoom)
    setMaxZoomPreference(zoom)
}
```
<p>And these are the <code>MapUtils</code>:</p>
<pre class="lang-kotlin prettyprint-override"><code>package com.veloce.mapstesting

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.google.android.libraries.maps.MapView
import java.lang.IllegalStateException

@Composable
fun rememberMapViewWithLifecycle(): MapView {
    val context = LocalContext.current
    val mapView = remember {
        MapView(context).apply { id = R.id.map }
    }

    val lifecycleObserver = rememberMapLifecycleObserver(mapView)
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    DisposableEffect(lifecycle) {
        lifecycle.addObserver(lifecycleObserver)
        onDispose { lifecycle.removeObserver(lifecycleObserver) }
    }
    return mapView
}

private fun rememberMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
    LifecycleEventObserver { _, event ->
        when (event) {
            Lifecycle.Event.ON_CREATE -> mapView.onStart()
            Lifecycle.Event.ON_RESUME -> mapView.onResume()
            Lifecycle.Event.ON_PAUSE -> mapView.onPause()
            Lifecycle.Event.ON_STOP -> mapView.onStop()
            Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
            else -> throw IllegalStateException()
        }
    }
</code>```

Did I miss something?

答:
Official Google Maps library for Jetpack Compose came out recently, check it out:

Google Maps Compose

Title: Maps in Jetpack compose

Body:
I'm trying to get a simple map as my mainActivity to test how maps with compose works. Unfortunately I just fail at the beginning with an Errormessage which says basically nothing but "IllegalStateException".
I've tried to extract the map code from the original Google example here:
https://github.com/android/compose-samples/tree/main/Crane
I've tried to rebuild a simple Composable, made an API Key at Google Cloud Platform and added it to my manifest.

Thats the MainActivity:

package com.veloce.mapstesting

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.FloatRange
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.libraries.maps.CameraUpdateFactory
import com.google.android.libraries.maps.GoogleMap
import com.google.android.libraries.maps.MapView
import com.google.android.libraries.maps.model.LatLng
import com.google.maps.android.ktx.addMarker
import com.google.maps.android.ktx.awaitMap
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val mapView = rememberMapViewWithLifecycle()
            MapViewContainer(mapView)
        }
    }
}

const val InitialZoom = 5f
const val MinZoom = 2f
const val MaxZoom = 20f

@Composable
fun MapViewContainer(map: MapView) {
    val cameraPosition = remember {
        LatLng(48.2050491798, 16.3701485194)
    }

    LaunchedEffect(map) {
        val googleMap = map.awaitMap()
        googleMap.addMarker { position(cameraPosition) }
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(cameraPosition))
    }

    var zoom by rememberSaveable(map) { mutableStateOf(InitialZoom) }
    ZoomControls(zoom) {
        zoom = it.coerceIn(MinZoom, MaxZoom)
    }

    val coroutineScope = rememberCoroutineScope()
    AndroidView({ map }) { mapView ->
        val mapZoom = zoom
        coroutineScope.launch {
            val googleMap = mapView.awaitMap()
            googleMap.setZoom(mapZoom)
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(cameraPosition))
        }
    }
}

@Composable
private fun ZoomControls(
    zoom: Float,
    onZoomChanged: (Float) -> Unit
) {
    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
        ZoomButton("-", onClick = { onZoomChanged(zoom * 0.8f) })
        ZoomButton("+", onClick = { onZoomChanged(zoom * 1.2f) })
    }
}

@Composable
fun ZoomButton(text: String, onClick: () -> Unit) {
    Button(
        modifier = Modifier.padding(8.dp),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = MaterialTheme.colors.onPrimary,
            contentColor = MaterialTheme.colors.primary
        ),
        onClick = onClick
    ) {
        Text(text = text, style = MaterialTheme.typography.h5)
    }
}

fun GoogleMap.setZoom(
    @FloatRange(from = MinZoom.toDouble(), to = MaxZoom.toDouble()) zoom: Float
) {
    resetMinMaxZoomPreference()
    setMinZoomPreference(zoom)
    setMaxZoomPreference(zoom)
}

And these are the MapUtils:

package com.veloce.mapstesting

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.google.android.libraries.maps.MapView
import java.lang.IllegalStateException

@Composable
fun rememberMapViewWithLifecycle(): MapView {
    val context = LocalContext.current
    val mapView = remember {
        MapView(context).apply { id = R.id.map }
    }

    val lifecycleObserver = rememberMapLifecycleObserver(mapView)
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    DisposableEffect(lifecycle) {
        lifecycle.addObserver(lifecycleObserver)
        onDispose { lifecycle.removeObserver(lifecycleObserver) }
    }
    return mapView
}

private fun rememberMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
    LifecycleEventObserver { _, event ->
        when (event) {
            Lifecycle.Event.ON_CREATE -> mapView.onStart()
            Lifecycle.Event.ON_RESUME -> mapView.onResume()
            Lifecycle.Event.ON_PAUSE -> mapView.onPause()
            Lifecycle.Event.ON_STOP -> mapView.onStop()
            Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
            else -> throw IllegalStateException()
        }
    }

Did I miss something?


问:
In Scala how to access match case value in each case block
I want to access to the case value in the case block</p>
```<code> val a = "hello"
  a match {
    case "hello" | "Hi" =>
      println("hello") // how can I access the right case value? Hello or Hi?
    case _ =>
      print("NA")
  }
</code>```

答:
Another way could be -</p>
```<code>a match {
case str if str == "hello" | str == "Hi" => println(str)
case _ => println("NA")
}
</code>```

Body:
I want to access to the case value in the case block

 val a = "hello"
  a match {
    case "hello" | "Hi" =>
      println("hello") // how can I access the right case value? Hello or Hi?
    case _ =>
      print("NA")
  }

Body:
Another way could be -

a match {
case str if str == "hello" | str == "Hi" => println(str)
case _ => println("NA")
}


问:
how to get only one value from array data and convert it into comma separted values. using javascript without template literals
i have array data in the format given below

```<code>const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]
</code>```

from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-

```<code>product1name: "productname",
product2name: "productname2",
...
</code>```

i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried

```<code>    var dataByComa = '';

  var Values = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "prod" +" " + ": " + JSON.stringify(data[i][k]);
    });
  }).map(function (v) {
    return v.join(",\n"); });
  var commaValues = Values.join(",\n");
return commaValues;
</code>```

with this code i can able to convert array data into comma separated values but i want only productnames.

Note :- Without using template template literals.

答:
You can do that using reduce. It takes a function as first and an initial value as second parameter (here an empty object {}).
The variable "previous" keeps track of the current state of the (initially empty) new object while the function adds the name of every single Element from the "data" array to the object.

```<code>var result = data.reduce((previous, element) => {
    previous[element.name] = element.name;
    return previous;
}, {})
</code>```

EDIT:
As i realized, you actually want a string as result. In that case you could do:

```<code>var result = data.reduce((previous, element) => {
    previous[element.name] = element.name;
    return previous;
}, {})
var csvWithBrackets = JSON.stringify(result)
var csv = csvWithBrackets.substring(1, csvWithBrackets.length-1)
</code>```

However the answer from Pzutils seems more compact.

Body:
i have array data in the format given below

const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]

from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-

product1name: "productname",
product2name: "productname2",
...

i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried

    var dataByComa = '';

  var Values = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "prod" +" " + ": " + JSON.stringify(data[i][k]);
    });
  }).map(function (v) {
    return v.join(",\n"); });
  var commaValues = Values.join(",\n");
return commaValues;

with this code i can able to convert array data into comma separated values but i want only productnames.

Note :- Without using template template literals.

Body:
You can do that using reduce. It takes a function as first and an initial value as second parameter (here an empty object {}).
The variable "previous" keeps track of the current state of the (initially empty) new object while the function adds the name of every single Element from the "data" array to the object.

var result = data.reduce((previous, element) => {
    previous[element.name] = element.name;
    return previous;
}, {})

EDIT:
As i realized, you actually want a string as result. In that case you could do:

var result = data.reduce((previous, element) => {
    previous[element.name] = element.name;
    return previous;
}, {})
var csvWithBrackets = JSON.stringify(result)
var csv = csvWithBrackets.substring(1, csvWithBrackets.length-1)

However the answer from Pzutils seems more compact.


问:
Non nullable instance field must be initalised
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

```<code>import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}
</code>```

in that video it runs, but for me it shows error as

```<code>Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.
</code>```

i have no idea what the problem is..
can you guys help me to troubleshoot the error

答:
```<code>var rawJson = '{"url": "https://helo.com","id": 2}';
</code>```

Actually it is a Sting Json and Encoding is not perform properly  So follow the step..

Map data={"url": "https://helo.com","id": 2};

Encode that data.   json.encode(data);

Now the Encoding is done then you can send the data any server if you have..

When you get back data then... json.decode(rawData)

Then parsing work properly

Body:
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}

in that video it runs, but for me it shows error as

Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.

i have no idea what the problem is..
can you guys help me to troubleshoot the error

Body:
var rawJson = '{"url": "https://helo.com","id": 2}';

Actually it is a Sting Json and Encoding is not perform properly  So follow the step..

Map data={"url": "https://helo.com","id": 2};

Encode that data.   json.encode(data);

Now the Encoding is done then you can send the data any server if you have..

When you get back data then... json.decode(rawData)

Then parsing work properly


问:
How to draw a line using a texture with Cocos2D
How can I draw a line using a texture in Cocos2D? Specifically I'm looking to create an effect similar to: http://www.slickcar.com/products/purple-neon.jpg

Thanks!

答: Check out this repository https://github.com/hiepnd/cocos2d-ext/. CCNode+Ext.h has a function called (drawLineFrom:to:texture:baseLength:stretch:). Hope it helps :)</p>


问:
Drag and drop in jAVASCRIPT not working on mobile devices
I'm working with this drag and drop option and It's not running on mobile device anyone please help
Here is the codepen link : [https://codepen.io/paulobrien/pen/yLVgzMz][1]</p>

答:
html5 drag and drop doesn't work on mobile browsers.
You can check this https://caniuse.com/?search=drag ..
Also https://www.w3schools.com/html/html5_draganddrop.asp is a simple drag-n-drop example which works fine on laptop but doesn't work on mobile browsers ..</p>


问:
Using c++20 with gcc 10 is limited to c++17
When i try to set c++20 standard with gcc 10.3, it sets _cplusplus macro to 201709L

```<code>gcc -x c++ -std=c++20  -E -dM -< /dev/null | grep _cplusplus
</code>```

outputs:

```<code>#define __cplusplus 201709
</code>```

Getting gcc version

```<code> gcc --version
</code>```

outputs:

```<code>gcc (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
</code>```

Any ideas ?

答:
__cplusplus

This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to STDC_VERSION, in that it expands to a version number. Depending on the language standard selected, the value of the macro is 199711L for the 1998 C++ standard, 201103L for the 2011 C++ standard, 201402L for the 2014 C++ standard, 201703L for the 2017 C++ standard, or an unspecified value strictly larger than 201703L for the experimental languages enabled by -std=c++2a and -std=gnu++2a.

As quoted in the gcc 10.3 doc. Since C++20 is not complete in gcc 10.3 yet.

For who interested in the macro difference between -std=c++17 and std=c++20, see here

Body:
When i try to set c++20 standard with gcc 10.3, it sets _cplusplus macro to 201709L

gcc -x c++ -std=c++20  -E -dM -< /dev/null | grep _cplusplus

outputs:

#define __cplusplus 201709

Getting gcc version

 gcc --version

outputs:

gcc (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0

Any ideas ?


问:
iOS - MVVM Data Binding
I am working with MVVM design architecture, I have gone through multiple articles about data binding. We can achieve data binding through Protocol, Closure, and Third Party(like RxSwift).
So, if I am wrong please correct me otherwise let me know "how many ways to bind the data in iOS(Swift) MVVM design architecture?"</p>

答:
The easiest one is by using Observable class binding known as Boxing.
create an Observable class:

```<code>class Observable<T> {

var value: T? {
    didSet {
        DispatchQueue.main.async {
            self.listener?(self.value)
        }
    }
}

init( _ value: T?) {
    self.value = value
}

private var listener: ((T?) -> Void)?

func bind(_ listener: @escaping (T?) -> Void) {
    listener(value)
    self.listener = listener
}
}
</code>```

in your viewModel define it in this way:
(this is a sample for showing loader in your view controller)

```<code>var isLoadingData: Observable<Bool> = Observable(false)
</code>```

Because the Observable class is a generic type, you can pass other types to it.

in your view model you can set the value:

```<code>isLoadingData.value = true
</code>```

then in your view controller use something like this:

```<code>   viewModel.isLoadingData.bind { [weak self] loading in
        guard let loading = loading, let self = self else {
            return
        }
        DispatchQueue.main.async {
            if loading {
                //Show a loader
            } else {
                //Hide a loader
            }
        }
    }
</code>```

As soon as a value is assigned to the isLoadingData object, it will trigger your view controller. We have to use [Weak self] to avoid strong references.

Title: iOS - MVVM Data Binding

Body:
The easiest one is by using Observable class binding known as Boxing.
create an Observable class:

class Observable<T> {

var value: T? {
    didSet {
        DispatchQueue.main.async {
            self.listener?(self.value)
        }
    }
}

init( _ value: T?) {
    self.value = value
}

private var listener: ((T?) -> Void)?

func bind(_ listener: @escaping (T?) -> Void) {
    listener(value)
    self.listener = listener
}
}

in your viewModel define it in this way:
(this is a sample for showing loader in your view controller)

var isLoadingData: Observable<Bool> = Observable(false)

Because the Observable class is a generic type, you can pass other types to it.

in your view model you can set the value:

isLoadingData.value = true

then in your view controller use something like this:

   viewModel.isLoadingData.bind { [weak self] loading in
        guard let loading = loading, let self = self else {
            return
        }
        DispatchQueue.main.async {
            if loading {
                //Show a loader
            } else {
                //Hide a loader
            }
        }
    }

As soon as a value is assigned to the isLoadingData object, it will trigger your view controller. We have to use [Weak self] to avoid strong references.


问:
show date in correct format angular
I am making an application in which I want user to submit date date is getting stored in database in this format 2003-06-01T00:00:00.000+00:00 I want to display it as 01/06/2003 or 1st June 2003 can any body help me how can I do this?

答:
You can use angular date pipe
https://angular.io/api/common/DatePipe</p>
```<code><span>{{startDate | date:'MM/dd/yyyy'}}</span>
</code>```

Title: show date in correct format angular

Body:
You can use angular date pipe
https://angular.io/api/common/DatePipe

<span>{{startDate | date:'MM/dd/yyyy'}}</span>


问:
Given a start time of a slot in 12hrs time format (say "2: 45 PM") and a period in mins after this ends 15 for eg. How would you calculate end time?
I have a date slot in string (12hrs) format eg - "2:45 PM" and a time period to when this slot ends say 15 (mins). So time slots starts at "2: 45 PM" and ends in 15 mins. I want to show the ending time in the same format as time string in 12hrs format.

Example - Slot: "2: 45 PM", ends: 15
endingSlot will be "3: 00 PM"

答:
I'd use a library for that — e.g. Moment.js:</p>
```<code>import * as moment from 'moment';

const slot = '2.45 PM';
const endingSlot = moment(slot, 'h:mm A').add(15, 'minutes').format('h:mm A');

console.log(endingSlot); // 3:00 PM
</code>```

Body:
I'd use a library for that — e.g. Moment.js:

import * as moment from 'moment';

const slot = '2.45 PM';
const endingSlot = moment(slot, 'h:mm A').add(15, 'minutes').format('h:mm A');

console.log(endingSlot); // 3:00 PM


问:
Is there any way to make normal int(65) to hex int(0x65) in flutter?
I'm using flutter_blue for ble communication. I need to send list in write characteristic.

eg. Let say input value is 'A'.
I want the result to be 0x41(int).
Instead I got the result 41(int).

When I send to ble device 0x41 then the reader can get the correct result 'A'.I can't find how to put 0x to infront of a int value.

答:
I have the same problem;
I want to get an integer like 0x61 (runtimeType == int)</p>
```<code>int count = 9999;
/// count.toRadixString(16);  ===> 0x270F   runtimeType == String
int.parse(count.toRadixString(16)); /// output => 9999
</code>```

Body:
I have the same problem;
I want to get an integer like 0x61 (runtimeType == int)

int count = 9999;
/// count.toRadixString(16);  ===> 0x270F   runtimeType == String
int.parse(count.toRadixString(16)); /// output => 9999


问:
ion toast blocks focus on any input in Ionic 6
Case: I have a very simple form, and when the user clicks submit while it's invalid, I display a toast with an error message.

problem:
this problem only occurred after I had migrated to Ionic 6, while the toast is displayed I cannot focus on any input till the toast disappears.

any solution ?

答:
Apparently the issue occurs because the toast steals focus from the inputs and
it has something to do with tapindex set to -1

solution:

```<code>   this.toast.removeAttribute("tabindex");
    await this.toast.present();
</code>```

there is an open issue at their github repo.

Body:
Apparently the issue occurs because the toast steals focus from the inputs and
it has something to do with tapindex set to -1

solution:

   this.toast.removeAttribute("tabindex");
    await this.toast.present();

there is an open issue at their github repo.


问:
How to enable open link in new tab in click event in angular 12
My click event:

```<code>html:
 <div class="image"   (click)="onClickOperation(product);">
.......
</div>
TS:
onClickOperation(product: any): void {
    // debugger
    if (this.regularView) {
      if (this.details) {
        this.openLightbox(product);
      } else {
        this.router.navigate(['/product', product.productId]);
      }
    } else {
      this.router.navigate(['/store', product.shopId]);
      this.productsender.changeMessage(product);
    }
  }

</code>```

its working fine how I want to implement right click to  open link in new tab option .how can I do it need

答:
If you mean you want to be able to open the link via the right-click menu then you need to pass routerLink to the a tag.
There is the solution: How to enable "ctrl+click" with "routerLink" in Angular

And an example:

link to user component
```
<p>or</p>
<pre class="lang-html prettyprint-override"><code>Jim
</code>```

You need "a" tag because in HTML only this tag has the property to open links by HTML functionality.

Information on how to use routerLink you can find in angular routerLink docs

In your case probably you should use *ngIf make a condition to display a correct element with the correct URL.

There is an example of how to make it. Conditionally add RouterLink or other attribute directives to an element in Angular 2

If you want to replace the context menu with your function, just look at this issue:
How to handle right click event in Angular app?

Body:
My click event:

html:

.......

TS:
onClickOperation(product: any): void {
    // debugger
    if (this.regularView) {
      if (this.details) {
        this.openLightbox(product);
      } else {
        this.router.navigate(['/product', product.productId]);
      }
    } else {
      this.router.navigate(['/store', product.shopId]);
      this.productsender.changeMessage(product);
    }
  }

its working fine how I want to implement right click to  open link in new tab option .how can I do it need

Body:
If you mean you want to be able to open the link via the right-click menu then you need to pass routerLink to the a tag.
There is the solution: How to enable "ctrl+click" with "routerLink" in Angular

And an example:

<a routerLink="/user/bob">link to user component</a>

or

<a [routerLink]="['/user/jim']">Jim</a>

You need "a" tag because in HTML only this tag has the property to open links by HTML functionality.

Information on how to use routerLink you can find in angular routerLink docs

In your case probably you should use *ngIf make a condition to display a correct element with the correct URL.

There is an example of how to make it. Conditionally add RouterLink or other attribute directives to an element in Angular 2

If you want to replace the context menu with your function, just look at this issue:
How to handle right click event in Angular app?


问:
Does BR tag posseses height?
I know that BR is used to create line-breaks. I'm just wondering if it also creates space between lines? Please consider these example:

```<code><p>
Hello <br/> Stackoverflow <br/><br/><br/> !
</p>
</code>```

The output looks like:

```<code>Hello
Stackoverflow

!
</code>```

By putting more and more BR I found distance between lines increase. Is it because of
? But when I try to control
 height in CSS, it doesn't follow, it seems like it has no height at all, just a line-break. If
 is not the cause of the space between line, then which is which and how to control it in CSS? Also, I usually use
 to create large distance between lines, I do that to replace \n\r or the like when the data is from the database, is that okay?

答:
I found out that the space that we see when we put multiple BR is not actually caused by BR but the P element's line height.

Consider the following markup:

```<code><p>
Hello <br/> Stackoverflow <br/><br/><br/> !
</p>
</code>```

Output

```<code>1. Hello
2. Stackoverflow
3.
4.
5.    !
</code>```

Line 3 and 4 here are just empty lines. Despite being empty, they still posses line height.

Title: Does BR tag posseses height?

Body:
I know that BR is used to create line-breaks. I'm just wondering if it also creates space between lines? Please consider these example:

Hello
 Stackoverflow

 !

The output looks like:

Hello
Stackoverflow

!

By putting more and more BR I found distance between lines increase. Is it because of
? But when I try to control
 height in CSS, it doesn't follow, it seems like it has no height at all, just a line-break. If
 is not the cause of the space between line, then which is which and how to control it in CSS? Also, I usually use
 to create large distance between lines, I do that to replace \n\r or the like when the data is from the database, is that okay?

Body:
I found out that the space that we see when we put multiple BR is not actually caused by BR but the P element's line height.

Consider the following markup:

<p>
Hello <br/> Stackoverflow <br/><br/><br/> !
</p>

Output

1. Hello
2. Stackoverflow
3.
4.
5.    !

Line 3 and 4 here are just empty lines. Despite being empty, they still posses line height.


问:
No bundle URL present (react native)
Just installed react native and trying to get Hello World up and running. Been receiving this error for the last few hours:

```<code> "No bundle URL present.Make sure you're running a packager server
 or have included a .jsbundle file in your application bundle."
</code>```

I've referred to this: What means of no bundle URL present in react-native? and other similar questions, and tried everything: using my ip addresse, different combos of react-native run-iso and npm install while running and not running, tried deleting builds, cleaning project, restarting Xcode, simulator multiple times,  tried react-native-upgrade, edited into.plist to allow arbitrary loads, manually setting the path to my index.ios.js, everything, and nothing works.

I noticed many ran into this issue when trying to build on their device. i'm not trying to do anything fancy, just get 'hello world' up and running.

Any other solutions I am not aware of?

答:
Lots of answers are given, but one thing you should surely be taking care of while facing this issue is to

make sure that your Metro server is running.

Title: No bundle URL present (react native)

Body:
Just installed react native and trying to get Hello World up and running. Been receiving this error for the last few hours:

 "No bundle URL present.Make sure you're running a packager server
 or have included a .jsbundle file in your application bundle."

I've referred to this: What means of no bundle URL present in react-native? and other similar questions, and tried everything: using my ip addresse, different combos of react-native run-iso and npm install while running and not running, tried deleting builds, cleaning project, restarting Xcode, simulator multiple times,  tried react-native-upgrade, edited into.plist to allow arbitrary loads, manually setting the path to my index.ios.js, everything, and nothing works.

I noticed many ran into this issue when trying to build on their device. i'm not trying to do anything fancy, just get 'hello world' up and running.

Any other solutions I am not aware of?


问:
Multiple view models when sharing data between fragments?
I have an activity with three fragments. All three fragments share a few pieces of data, but they each also have some data that is unique to their respective fragment.

I know it is common practice to use shared viewModels as referenced in the Google docs.

But my question is, how do I handle the data that is not shared between the fragments? Should I create another viewModel for each fragment, and have each fragment reference a shared viewModel as well as a viewModel that only has their own specific data, for a total of 4 viewModels? Or do I put everything in the shared viewModel and have each fragment only reference that?

答:
I think you need to create viewModel in Activity then call any api in ViewModel after that, api response you can use anywhere in fragments

Create ViewModel instance in Activity :
SettingViewModel settingViewModel = ViewModelProviders.of(this).get(SettingViewModel::class.java)

you can use settingViewModel in any fragment but you need to typecast fragment reference (e.g requireActivity()) to your activity after that you can use api data in fragment


问:
pub get failed. exit code 65. flutter
Everything is ok. every package is working. but the shimmer package not working.
this is my implementation.

```<code>version: 1.0.0+1
environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  shimmer:
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter
</code>```

error:

```<code>[shimmer] flutter pub get
Running "flutter pub get" in shimmer...
Error on line 26, column 3 of pubspec.yaml: A package may not list itself as a dependency.

   ╷

26 │   shimmer:
   │   ^^^^^^^

   ╵
pub get failed (65;    ╵)
exit code 65
</code>```

答:
In case the project name and package name are the same. It will throw an error.

So, make sure the project name and package name must be unique.

For example, You created a project, you gave it the name provider. and you also added a package which is the provider. So, they will conflict with each other.

Title: pub get failed. exit code 65. flutter

Body:
Everything is ok. every package is working. but the shimmer package not working.
this is my implementation.

version: 1.0.0+1
environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  shimmer:
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

error:

[shimmer] flutter pub get
Running "flutter pub get" in shimmer...
Error on line 26, column 3 of pubspec.yaml: A package may not list itself as a dependency.

   ╷

26 │   shimmer:
   │   ^^^^^^^

   ╵
pub get failed (65;    ╵)
exit code 65


问:
How to set the  tag with basic authentication
I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.

In Firefox and Chrome I can do this:

```<code><img width="320" height="200" src="http://username:password@server/Path" />
</code>```

But in Internet Explorer 8, I get an empty image box.  If I use JQuery to set the src attribute, IE8 displays a blank src.  It looks like IE8 is checking the string and rejecting it.

Is there a way to put the basic authentication credentials in the img tag?

答:
Try http proxy.

On server side, enable tinyProxy, create ReversePath to
basic authentication server in configuration like:

```<code>AddHeader "Authorization" "Basic dXNlcjpwYXNz"
ReversePath "/foo/" "http://somewhere:3480/foo/"
</code>```

dXNlcjpwYXNz is base64 encoded string from user:pass

Enable reverse proxy in Apache or NGINX to tinyProxy path http://localhot:8888/foo/

Img Source accessable from local server instead of old way deprecated, without http auth pop-up or CORS error.

```<code>http://user:pass@somewhere:3480/foo/DEST.jpg
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to set the <img> tag with basic authentication

Body:
I would like to display the image from a network camera on my web page, but the image is behind a HTTP basic authentication server.

In Firefox and Chrome I can do this:

But in Internet Explorer 8, I get an empty image box.  If I use JQuery to set the src attribute, IE8 displays a blank src.  It looks like IE8 is checking the string and rejecting it.

Is there a way to put the basic authentication credentials in the img tag?

Body:
Try http proxy.

On server side, enable tinyProxy, create ReversePath to
basic authentication server in configuration like:

AddHeader "Authorization" "Basic dXNlcjpwYXNz"
ReversePath "/foo/" "http://somewhere:3480/foo/"

dXNlcjpwYXNz is base64 encoded string from user:pass

Enable reverse proxy in Apache or NGINX to tinyProxy path http://localhot:8888/foo/

Img Source accessable from local server instead of old way deprecated, without http auth pop-up or CORS error.

http://user:pass@somewhere:3480/foo/DEST.jpg


问:
I'd like to make a software which will be executed with BIOS
I have a little brother who spends his time playing online games. It makes my parent worried. So, I'd like to build a blocking software which will be executed right after booting process.

My program will do

Print out questions(related to physics, literature and math), and ask him to type a right answer.

If he gives right answer, let him proceed to log in his laptop.

If he fails system will be shut down automatically.

So, my question is what should I know in order to accomplish my plan. Or any books to recommend me?

At my University, I 'd been taught only Java and C++ until now.
Through this project, I want to push myself to learn more and do actual practical tasks.

答:
You could write your own bootloader, or you could modify an existing open-source bootloader like GRUB that already has code for printing menus.

You might just make a menu where the prompt is a question and the options (instead of being different things to boot) are just GRUB print commands or shutdown, except for the right answer which goes to the next menu.  If your sibling doesn't find the keystrokes to escape from GRUB's menus to its command-line, or doesn't know what to do with it to boot successfully, that could be useful.

To update with (a) new question(s), you can have that done by a program that runs after the OS boots, so you don't have to figure out how to do that with GRUB's command / config language.  (Although that might be possible if you can use the low digit of the current time as an index into something.)

I think GRUB can work as a UEFI bootloader, so you don't have to set your PC's firmware to boot in legacy BIOS mode.  ("compatibility support modules", aka CSM in the BIOS menu.)


问:
HTML5 + discord.js Event Listener
What I Want:

I am trying to make it so when a member is added or removed from staff in my discord it will update it on the website I have. I've tried doing this with node.js, but then I can't use document attributes and etc. Basically I am wondering if this is possible.

Code JS:

const headBoardOfDirectors = document.querySelector('#hbod-role');
const boardOfDirectors = document.querySelector('#bod-role');
const headAdmin = document.querySelector('#ha-role');
const seniorAdmin = document.querySelector('#sa-role');
const admin = document.querySelector('#a-role');
const headModerator = document.querySelector('#hm-role');
const moderator = document.querySelector('#m-role');
const trialModerator = document.querySelector('#tm-role');

// Below is just an example of what I am talking about.

staff = [
    bunch of staff roles here
]

if (some member role add or remove event) {
    if (role added or removed is staff) {
        if (role name is Head Board of Directors) {
            headBoardOfDirectors.innerHTML = `${headBoardOfDirectors.innerHTML}\n${member name}`
        }
    }
}
```
<p><strong>Code HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code>        <div id="staff">
            <table>
                <tr>
                    <th class="main"></th>
                    <th class="main">Staff</th>
                    <th class="main"></th>
                </tr>
                <tr>
                    <th></th>
                    <th>Founder</th>
                    <th></th>
                </tr>
                <tr>
                    <td></td>
                    <td>killrebeest#1001</td>
                    <td></td>
                </tr>
                <tr>
                    <th></th>
                    <th>Owner</th>
                    <th></th>
                </tr>
                <tr>
                    <td></td>
                    <td>fluffy#9459</td>
                    <td></td>
                </tr>
                <tr>
                    <th></th>
                    <th>Head of Board of Directors</th>
                    <th></th>
                </tr>
                <tr>
                    <td></td>
                    <td id="hbod-role"></td>
                    <td></td>
                </tr>
                <tr>
                    <th></th>
                    <th>Board of Directors</th>
                    <th></th>
                </tr>
                <tr id="bod-role">

                </tr>
                <tr>
                    <th></th>
                    <th>Head Administration</th>
                    <th></th>
                </tr>
                <tr id="ha-role">

                </tr>
                <tr>
                    <th></th>
                    <th>Senior Administration</th>
                    <th></th>
                </tr>
                <tr id="sa-role">

                </tr>
                <tr>
                <tr>
                    <th></th>
                    <th>Administration</th>
                    <th></th>
                </tr>
                <tr id="a-role">

                </tr>
                <tr>
                    <th></th>
                    <th>Head Moderation</th>
                    <th></th>
                </tr>
                <tr id="hm-role">

                </tr>
                <tr>
                    <th></th>
                    <th>Moderation</th>
                    <th></th>
                </tr>
                <tr id="m-role">

                </tr>
                <tr>
                    <th></th>
                    <th>Trial Moderation</th>
                    <th></th>
                </tr>
                <tr id="tm-role">

                </tr>
            </table>
        </div>
</code>```

Summary:

Basically I mainly want to know if this is possible, which I think it most definitly should be. If it is possible, how can the be done, or is there any references that you can answer with to help me solve this issue.

Thanks,

killrebeest

答:
You can just connect your node.js with your client. I would recommend using EJS. First, you install express, ejs and discord.js by doing npm i express ejs discord.js. Then, you can set up your ejs.

index.js:

const express = require("express");
const app = express(); // setting up express

let staff = [ "john doe#1234", "jane doe#4321", "some other name#0001" ]; // example staff members

app.set("view engine", "ejs"); // using ejs

app.get("/", (req, res) => { res.render("index", { staff }); }); // rendering the ejs file

app.listen(80); // listening at port 80 (http://localhost)
```
<p><code>views/index.ejs</code>:</p>
<pre class="lang-html prettyprint-override"><code><h1>Our staff</h1>
<ul>
  <% staff.forEach(user => { %> <!-- for each staff member, list it -->
    <li><%= user %></li>
  <% }); %>
</ul>
</code>```

You need to register a Discord bot. Just go to https://discord.com/developers/applications, create an application, create a bot for said application, enable GUILD_MEMBERS intent and copy the token. You can then invite the bot to your server. From there, you can code the part with discord.js.

index.js

const express = require("express");
const app = express(); // setting up express

const { Client, Intents } = require("discord.js");
const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS],
}); // intents stuff

const token = "replace with your own bot token";
const serverId = "replace with the id of your server"; // you can get the ids by enabling developer mode (user settings > advanced) and then right clicking on the server or the role
const staffRoleId = "replace with id of the staff role";

app.set("view engine", "ejs"); // using ejs

app.get("/", async (req, res) => {
  const server = await (
    await client.guilds.fetch()
  ) // get all servers
    .find((v) => v.id == serverId) // find your server
    .fetch(); // get the server object

  const staff = (await server.members.fetch()) // get all members
    .filter((v) => v.roles.cache.filter((r) => r.id == staffRoleId).size > 0) // filter out the ones without admin role
    .map((v) => {
      return [v.displayAvatarURL({ format: "png", size: 128 }), v.user.tag];
    }); // avatars and names instead of objects
  res.render("index", { staff });
}); // rendering the ejs file

app.listen(80); // listening at port 80 (http://localhost)

client.login(token); // login
```
<p>You also need to change up the ejs a little bit (I decided to add some styling so it doesn't look completely horrible).</p>
<p><code>views/index.ejs</code>:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Our staff</title>
  </head>
  <body
    style="
      margin: 0;
      font-size: 200%;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
        Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    "
  >
    <h1 style="margin: 0; padding: 10px; padding-bottom: 0">Our staff</h1>
    <ul>
      <% staff.forEach(user => { %>
      <!-- for each staff member, list it -->
      <li>
        <img
          src="<%= user[0] %>"
          alt="<%= user[1] %>"
          style="border-radius: 50%; width: 32px; height: 32px"
        />
        <%= user[1] %>
      </li>
      <% }); %>
    </ul>
  </body>
</html>
</code>```

And with that, you're pretty much done.

Title: HTML5 + discord.js Event Listener

Body:
What I Want:

I am trying to make it so when a member is added or removed from staff in my discord it will update it on the website I have. I've tried doing this with node.js, but then I can't use document attributes and etc. Basically I am wondering if this is possible.

Code JS:

const headBoardOfDirectors = document.querySelector('#hbod-role');
const boardOfDirectors = document.querySelector('#bod-role');
const headAdmin = document.querySelector('#ha-role');
const seniorAdmin = document.querySelector('#sa-role');
const admin = document.querySelector('#a-role');
const headModerator = document.querySelector('#hm-role');
const moderator = document.querySelector('#m-role');
const trialModerator = document.querySelector('#tm-role');

// Below is just an example of what I am talking about.

staff = [
    bunch of staff roles here
]

if (some member role add or remove event) {
    if (role added or removed is staff) {
        if (role name is Head Board of Directors) {
            headBoardOfDirectors.innerHTML = `${headBoardOfDirectors.innerHTML}\n${member name}`
        }
    }
}

Code HTML:

                    Staff

                    Founder

                    killrebeest#1001

                    Owner

                    fluffy#9459

                    Head of Board of Directors

                    Board of Directors

                    Head Administration

                    Senior Administration

                    Administration

                    Head Moderation

                    Moderation

                    Trial Moderation

Summary:

Basically I mainly want to know if this is possible, which I think it most definitly should be. If it is possible, how can the be done, or is there any references that you can answer with to help me solve this issue.

Thanks,

killrebeest

Body:
You can just connect your node.js with your client. I would recommend using EJS. First, you install express, ejs and discord.js by doing npm i express ejs discord.js. Then, you can set up your ejs.

index.js:

const express = require("express");
const app = express(); // setting up express

let staff = [ "john doe#1234", "jane doe#4321", "some other name#0001" ]; // example staff members

app.set("view engine", "ejs"); // using ejs

app.get("/", (req, res) => { res.render("index", { staff }); }); // rendering the ejs file

app.listen(80); // listening at port 80 (http://localhost)

views/index.ejs:

<h1>Our staff</h1>
<ul>
  <% staff.forEach(user => { %> <!-- for each staff member, list it -->
    <li><%= user %></li>
  <% }); %>
</ul>

You need to register a Discord bot. Just go to https://discord.com/developers/applications, create an application, create a bot for said application, enable GUILD_MEMBERS intent and copy the token. You can then invite the bot to your server. From there, you can code the part with discord.js.

index.js

const express = require("express");
const app = express(); // setting up express

const { Client, Intents } = require("discord.js");
const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS],
}); // intents stuff

const token = "replace with your own bot token";
const serverId = "replace with the id of your server"; // you can get the ids by enabling developer mode (user settings > advanced) and then right clicking on the server or the role
const staffRoleId = "replace with id of the staff role";

app.set("view engine", "ejs"); // using ejs

app.get("/", async (req, res) => {
  const server = await (
    await client.guilds.fetch()
  ) // get all servers
    .find((v) => v.id == serverId) // find your server
    .fetch(); // get the server object

  const staff = (await server.members.fetch()) // get all members
    .filter((v) => v.roles.cache.filter((r) => r.id == staffRoleId).size > 0) // filter out the ones without admin role
    .map((v) => {
      return [v.displayAvatarURL({ format: "png", size: 128 }), v.user.tag];
    }); // avatars and names instead of objects
  res.render("index", { staff });
}); // rendering the ejs file

app.listen(80); // listening at port 80 (http://localhost)

client.login(token); // login

You also need to change up the ejs a little bit (I decided to add some styling so it doesn't look completely horrible).

views/index.ejs:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Our staff</title>
  </head>
  <body
    style="
      margin: 0;
      font-size: 200%;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
        Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    "
  >
    <h1 style="margin: 0; padding: 10px; padding-bottom: 0">Our staff</h1>
    <ul>
      <% staff.forEach(user => { %>
      <!-- for each staff member, list it -->
      <li>
        <img
          src="<%= user[0] %>"
          alt="<%= user[1] %>"
          style="border-radius: 50%; width: 32px; height: 32px"
        />
        <%= user[1] %>
      </li>
      <% }); %>
    </ul>
  </body>
</html>

And with that, you're pretty much done.


问:
Make navigation via NSString? or Make UILabel/UITextview contents for navigation
I have string data and height is changable, it can be like this:

John Colman to
   Android Market, Iphone Developers, PHP grups

or just

John Colman to
   Edward Python

but except "to" all the words must be navigate other viewController? What is the best solution for this? It is easy the navigate something via UITableView delegate or UIButton but it is just NSString??

答:
I used open framework of facebook:
http://three20.info/

create an linkable textlabel and it works..


问:
What is printed when you print a pandas dataframe?
I printed my data frame and it came out looking like this:

```<code>       date eye   pct_change \cheese...    date mouse pct_change  \cat
29   29-Nov-2019          0.002555  ...          NaN               NaN
30   02-Dec-2019          0.006483  ...          NaN               NaN
31   03-Dec-2019         -0.040024  ...          NaN               NaN
32   04-Dec-2019          0.009405  ...          NaN               NaN
33   01-Jan-2020         -0.226805  ...          NaN               NaN
..           ...               ...  ...          ...               ...
758          NaN               NaN  ...  04-Dec-2019          0.002225
759          NaN               NaN  ...  01-Jan-2020          0.004440
760          NaN               NaN  ...  02-Jan-2020          0.004420
761          NaN               NaN  ...  03-Jan-2020          0.004400
762          NaN               NaN  ...  06-Jan-2020         -0.002191

[7412 rows x 20 columns]
</code>```

It says the dimensions are [7412 rows x 20 columns],but on the left it lists the index from 29 to 762.

答:
```<code> df = pandas.concat([col1,col2,col3,...],axis=1,ignore_index=True)
</code>```

Is probably the answer

Im operating on the assumption that you have something like

```<code>df = pandas.concat([col1,col2,col3,...])
</code>```

which is likely stacking them on top of eachother     instead of next to each other

but your columns need to all be the same height ... so maybe that throws an error ...

if they are not the same height you can make them the same height or use pandas.merge to join them on a column ... but we are getting in the weeds...

Body:
I printed my data frame and it came out looking like this:

       date eye   pct_change \cheese...    date mouse pct_change  \cat
29   29-Nov-2019          0.002555  ...          NaN               NaN
30   02-Dec-2019          0.006483  ...          NaN               NaN
31   03-Dec-2019         -0.040024  ...          NaN               NaN
32   04-Dec-2019          0.009405  ...          NaN               NaN
33   01-Jan-2020         -0.226805  ...          NaN               NaN
..           ...               ...  ...          ...               ...
758          NaN               NaN  ...  04-Dec-2019          0.002225
759          NaN               NaN  ...  01-Jan-2020          0.004440
760          NaN               NaN  ...  02-Jan-2020          0.004420
761          NaN               NaN  ...  03-Jan-2020          0.004400
762          NaN               NaN  ...  06-Jan-2020         -0.002191

[7412 rows x 20 columns]

It says the dimensions are [7412 rows x 20 columns],but on the left it lists the index from 29 to 762.

Body:
 df = pandas.concat([col1,col2,col3,...],axis=1,ignore_index=True)

Is probably the answer

Im operating on the assumption that you have something like

df = pandas.concat([col1,col2,col3,...])

which is likely stacking them on top of eachother     instead of next to each other

but your columns need to all be the same height ... so maybe that throws an error ...

if they are not the same height you can make them the same height or use pandas.merge to join them on a column ... but we are getting in the weeds...


问:
How to measure similarity between two arbitrary files?
I have two arbitrary files. Git does not consider them as one renamed file. Is it possible to measure (in percent) similarity between them?</p>

答:
Here is a pure Perl5 solution based on @Adder's answer that adds a few optimizations in case you are dealing with large files.

#!/usr/bin/perl

use strict;
use warnings;

use Tie::File;
use Fcntl 'O_RDONLY';

sub flines ($) {
  my %opts = (
    mode   => O_RDONLY, # No need to cache or write,
    memory => 0,        #   as we are not using read data.
    recsep => "\n",     # Use "\r\n" if Windows
  );
  tie @_, 'Tie::File', shift, %opts or die "tie: $!\n";
  $_ = scalar @_;
  untie @_;
  return $_
}

sub slines ($) {
  my $fh = $_[0];
  next for <$fh>;
  return $.
}

my ($f1, $f2) = @ARGV;

# count number of lines in unified diff
open my ($fh), "diff -u1 $f1 $f2 |" or die "open: $!\n";

my $sD = slines $fh;
my $s1 = flines $f1;
my $s2 = flines $f2;

printf "%8.3g\n", 1.0 - ( $sD / 2.0 ) / ( $s1 > $s2 ? $s1 : $s2 )
```
<p>It is used and called the same as in his example:</p>
<pre class="lang-sh prettyprint-override"><code>$ similarity foo bar
   0.327
</code>```

Body:
Here is a pure Perl5 solution based on @Adder's answer that adds a few optimizations in case you are dealing with large files.

#!/usr/bin/perl

use strict;
use warnings;

use Tie::File;
use Fcntl 'O_RDONLY';

sub flines ($) {
  my %opts = (
    mode   => O_RDONLY, # No need to cache or write,
    memory => 0,        #   as we are not using read data.
    recsep => "\n",     # Use "\r\n" if Windows
  );
  tie @_, 'Tie::File', shift, %opts or die "tie: $!\n";
  $_ = scalar @_;
  untie @_;
  return $_
}

sub slines ($) {
  my $fh = $_[0];
  next for <$fh>;
  return $.
}

my ($f1, $f2) = @ARGV;

# count number of lines in unified diff
open my ($fh), "diff -u1 $f1 $f2 |" or die "open: $!\n";

my $sD = slines $fh;
my $s1 = flines $f1;
my $s2 = flines $f2;

printf "%8.3g\n", 1.0 - ( $sD / 2.0 ) / ( $s1 > $s2 ? $s1 : $s2 )

It is used and called the same as in his example:

$ similarity foo bar
   0.327


问:
How can I add or remove class using querySelectorAll() in react functional component
I am trying to add or remove an active class if I click any list item but the code is not working.
Here is my function

```<code>    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))
</code>```

Full code with HTML

```<code>

export default function MobileNavigation() {
    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))

    return <div className='mobile-navigation'>
        <ul>
            <li className='m-list active'>
                <a href="#">
                    <span className='m-icon'><i className="fa-solid fa-house"></i></span>
                    <span className='m-text'>Home</span>
                </a>
            </li>
            <li className='m-list'>
                <a href="#">
                    <span className='m-icon'><i className="fa-solid fa-shop"></i></span>
                    <span className='m-text'>Shop</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-store"></i></span>
                    <span className='m-text'>Vendors</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-address-card"></i></span>
                    <span className='m-text'>About us</span></a>
            </li>
            <li className='m-list'>
                <a href="#"><span className='m-icon'><i className="fa-solid fa-headset"></i></span>
                    <span className='m-text'>Contact Us</span></a>
            </li>
            <div className="indicator"></div>
        </ul>
    </div>;
}

</code>```

答:
```<code>const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

 function activeLink(e:any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        e.classList.add('active')
    }
 list.forEach(item => item.addEventListener('click', (e)=>activeLink(item)))
</code>```

Just replace this with your code ... it will start working now .
I hope this helped you solve your issue :)

Body:
I am trying to add or remove an active class if I click any list item but the code is not working.
Here is my function

    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))

Full code with HTML

export default function MobileNavigation() {
    const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

    function activeLink(this: any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        this.classList.add('active')
    }
    list.forEach(item => item.addEventListener('click', activeLink))

    return

                    Home

                    Shop

                    Vendors

                    About us

                    Contact Us

;
}

Body:
const list = document.querySelectorAll('.m-list') as NodeListOf<Element>

 function activeLink(e:any) {
        list.forEach((item) => item.classList.remove('active'))
        // list.forEach((item) => item.classList.add('active'))
        e.classList.add('active')
    }
 list.forEach(item => item.addEventListener('click', (e)=>activeLink(item)))

Just replace this with your code ... it will start working now .
I hope this helped you solve your issue :)


问:
What are practical uses of applicative style?
I am a Scala programmer, learning Haskell now. It's easy to find practical use cases and real world examples for OO concepts, such as decorators, strategy pattern etc. Books and interwebs are filled with it.

I came to the realization that this somehow is not the case for functional concepts. Case in point: applicatives.

I am struggling to find practical use cases for applicatives. Almost all of the tutorials and books I have come across so far provide the examples of [] and Maybe. I expected applicatives to be more applicable than that, seeing all the attention they get in the FP community.

I think I understand the conceptual basis for applicatives (maybe I am wrong), and I have waited long for my moment of enlightenment. But it doesn't seem to be happening. Never while programming, have I had a moment when I would shout with a joy, "Eureka! I can use applicative here!" (except again, for [] and Maybe).

Can someone please guide me how applicatives can be used in a day-to-day programming? How do I start spotting the pattern? Thanks!

答:
I think Applicatives ease the general usage of monadic code. How many times have you had the situation that you wanted to apply a function but the function was not monadic and the value you want to apply it to is monadic? For me: quite a lot of times!

Here is an example that I just wrote yesterday:

ghci> import Data.Time.Clock
ghci> import Data.Time.Calendar
ghci> getCurrentTime >>= return . toGregorian . utctDay
```

<p>in comparison to this using Applicative:</p>

<pre class="lang-hs prettyprint-override"><code>ghci> import Control.Applicative
ghci> toGregorian . utctDay <$> getCurrentTime
</code>```

This form looks "more natural" (at least to my eyes :)

Body:
I think Applicatives ease the general usage of monadic code. How many times have you had the situation that you wanted to apply a function but the function was not monadic and the value you want to apply it to is monadic? For me: quite a lot of times!

Here is an example that I just wrote yesterday:

ghci> import Data.Time.Clock
ghci> import Data.Time.Calendar
ghci> getCurrentTime >>= return . toGregorian . utctDay

in comparison to this using Applicative:

ghci> import Control.Applicative
ghci> toGregorian . utctDay <$> getCurrentTime

This form looks "more natural" (at least to my eyes :)


问:
How to get the start of line of the current position in a UITextView
I want to get the start of the line for the current cursor position on a UITextView

First I get the current position, thats easy.

```<code>let currentPosition = textView.selectedTextRange!.start
</code>```

Then I should get the startOfLinePosition with this method, but I´m unsure of how to get the offset

```<code>let startOfLinePosition = textView.positionFromPosition(currentPosition, inDirection: .Left, offset: ?)
</code>```

How can I get the differential offset ?

答:
Swift 5.5 version of the answer above:</p>
```<code>let attachment = NSTextAttachment()
attachment.image = scaledImage
let imageString = NSAttributedString(attachment: attachment)
if let currentPosition = textView.selectedTextRange?.start,
   let startOfLinePosition = textView.tokenizer.position(from: currentPosition, toBoundary: .line, inDirection: UITextDirection.storage(.backward)){
    let intPosition = textView.offset(from: textView.beginningOfDocument, to: startOfLinePosition)
    textView.textStorage.insert(imageString, at: intPosition)
</code>```

Body:
I want to get the start of the line for the current cursor position on a UITextView

First I get the current position, thats easy.

let currentPosition = textView.selectedTextRange!.start

Then I should get the startOfLinePosition with this method, but I´m unsure of how to get the offset

let startOfLinePosition = textView.positionFromPosition(currentPosition, inDirection: .Left, offset: ?)

How can I get the differential offset ?

Body:
Swift 5.5 version of the answer above:

let attachment = NSTextAttachment()
attachment.image = scaledImage
let imageString = NSAttributedString(attachment: attachment)
if let currentPosition = textView.selectedTextRange?.start,
   let startOfLinePosition = textView.tokenizer.position(from: currentPosition, toBoundary: .line, inDirection: UITextDirection.storage(.backward)){
    let intPosition = textView.offset(from: textView.beginningOfDocument, to: startOfLinePosition)
    textView.textStorage.insert(imageString, at: intPosition)


问:
Azure DevOps YAML pipeline - git diff not working correctly
I am executing a git command in my Azure DevOps YAML pipeline to get changes between two commits like git diff commit1 commit2 --name-only via a PowerShell script - see full code below:

```<code>Write-Information "git diff --name-only $git_event_before $git_event_after --diff-filter=ACM ""*.txt"""
$txt_files = @($(git diff --name-only $git_event_before $git_event_after --diff-filter=ACM "*.txt"))
$txt_files = $txt_files | ForEach-Object { Join-Path $root_path $_ | Get-Item }

if ($txt_files.Count -eq 0) {
    Write-Error "Something went wrong, could not find any changed .txt files using the above 'git diff'"
}
</code>```

This throws an error claiming no files were found.
However, if I execute the very same git diff command locally where I do also have the repository synced, it returns the changed files as expected.

Do I need to manually update the repository that is already downloaded by the checkout-step of the pipeline ?

答:
Could you try to run "git diff" this way</p>
```<code>$gitDiffCmd = 'diff "origin/{0}" "origin/{0}@{{1}}" --name-only' -f $buildSourceBranch
$gitCommitFiles = Invoke-Git $gitDiffCmd

function Invoke-Git {
    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory)]
        [string] $Command
    )
    try {
        $old_env = $env:GIT_REDIRECT_STDERR
        $env:GIT_REDIRECT_STDERR = '2>&1'
        $response = Invoke-Expression "git $Command "
        return $response
    } catch {
        Write-Host $_.ScriptStackTrace
    } finally {
        $env:GIT_REDIRECT_STDERR = $old_env
    }
}
</code>```

Body:
I am executing a git command in my Azure DevOps YAML pipeline to get changes between two commits like git diff commit1 commit2 --name-only via a PowerShell script - see full code below:

Write-Information "git diff --name-only $git_event_before $git_event_after --diff-filter=ACM ""*.txt"""
$txt_files = @($(git diff --name-only $git_event_before $git_event_after --diff-filter=ACM "*.txt"))
$txt_files = $txt_files | ForEach-Object { Join-Path $root_path $_ | Get-Item }

if ($txt_files.Count -eq 0) {
    Write-Error "Something went wrong, could not find any changed .txt files using the above 'git diff'"
}

This throws an error claiming no files were found.
However, if I execute the very same git diff command locally where I do also have the repository synced, it returns the changed files as expected.

Do I need to manually update the repository that is already downloaded by the checkout-step of the pipeline ?

Body:
Could you try to run "git diff" this way

$gitDiffCmd = 'diff "origin/{0}" "origin/{0}@{{1}}" --name-only' -f $buildSourceBranch
$gitCommitFiles = Invoke-Git $gitDiffCmd

function Invoke-Git {
    [CmdletBinding()]
    [OutputType([string])]
    param (
        [Parameter(Mandatory)]
        [string] $Command
    )
    try {
        $old_env = $env:GIT_REDIRECT_STDERR
        $env:GIT_REDIRECT_STDERR = '2>&1'
        $response = Invoke-Expression "git $Command "
        return $response
    } catch {
        Write-Host $_.ScriptStackTrace
    } finally {
        $env:GIT_REDIRECT_STDERR = $old_env
    }
}


问:
How to detect if left mousebutton is being held down with SDL2
I know how to use events to detect when the mouse button is pressed, however, how do detect if a mouse button is currently held down? Note I am not asking how to get it from an event.

I have not tried anything apart from SDL_GetMouseState(&x, &y); however it seems to only return the X and Y position of the mouse.

答:
SDL_GetMouseState() returns the buttons that were pressed. Example:

```<code>if (SDL_GetMouseState(...) & SDL_BUTTON_LMASK)
    // Left button is pressed.
</code>```

Body:
SDL_GetMouseState() returns the buttons that were pressed. Example:

if (SDL_GetMouseState(...) & SDL_BUTTON_LMASK)
    // Left button is pressed.


问:
Pull Request warning in Azure Repos
I have created a PR, no merge conflict displayed. In Azure Repos a warning is displayed:
Warning: Multiple merge bases detected. The list of commits displayed might be incomplete.</p>

答:
Pull master and merge=> the warning will disappear.

for more info on this issue see:
Warning: Multiple merge bases detected. The list of commits displayed might be incomplete

Title: Pull Request warning in Azure Repos


问:
iSeries stored procedure - how to get handle on the spool file output?
We have a stored procedure written using a CL and RPG program combination. When called locally on the iSeries all is fine. When called externally (for example from a SQL frontend) the RPG program cannot get a hadle on the spool file it produces because the spool file appears under a different (random?) job number and user.
The jobs run as QUSER in the QUSRWRK subsystem but the spool file gets the user id of which the connection was made externally in the connection pool (i.e USERA).

Is there a way of being able reliably to get a handle on the correct sppol file as the job runs (rather than relying on picking the last spool fiel from that queue etc).

答:
I need a bit more information, but I'll make some assumptions. Please clarify if I assumed wrong.

The QUSER in QUSRWRK behavior is correct. You are now running through the SQL server (or similar server). All connections run under these settings.

There are a couple approaches.

1) Assuming that this all runs in one job. Using '*" for the job information should work.

2) The other option is to use RTVJOBA CURUSER(&ME). The current user is the person that is logged in. USER would not work in this case.

OwnerDisplayName: Mike Wills


问:
Chaining a new object instance in PHP
We have the following chaining:

```<code>$obj = new obj();
$obj->setname($params1)->setcolor($params2);
</code>```

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

```<code>$obj = new obj()->setname($params1)->setcolor($params2);
</code>```

答:
Since PHP 5.4, class member access on instantiation has been added so you can do it like this:

```<code>$obj = (new obj())->setname($params1)->setcolor($params2);
</code>```

In previous versions, like you I hate that you have to instantiate the object on one line and then start using it on another, so I have a global function _i() which looks like this:

```<code>function _i($i) { return $i; }
</code>```

I use it like this:

```<code>_i(new Obj)->doThis($param)->doThat($param2);
</code>```

Some people will find it ugly but PHP lacks language expression power, so it works for me :)

Title: Chaining a new object instance in PHP

Body:
We have the following chaining:

$obj = new obj();
$obj->setname($params1)->setcolor($params2);

Is there a way to do the same chaining on one line, without creating a dummy function?

P.S: I want to skip the part where the constructor itself is on a new line. I want to construct the object and start the chaining on the same line. Something like this:

$obj = new obj()->setname($params1)->setcolor($params2);

Body:
Since PHP 5.4, class member access on instantiation has been added so you can do it like this:

$obj = (new obj())->setname($params1)->setcolor($params2);

In previous versions, like you I hate that you have to instantiate the object on one line and then start using it on another, so I have a global function _i() which looks like this:

function _i($i) { return $i; }

I use it like this:

_i(new Obj)->doThis($param)->doThat($param2);

Some people will find it ugly but PHP lacks language expression power, so it works for me :)


问:
how do i add dummy values to my dataframe (is this how you say it?)
A quick summary of what I'm trying to do:
I'm trying to retrieve sales data from a CSV file, put them in a dataframe, and make a visualisation from them.

My issue is, for the year 2014, only months November and December are present. And for 2015, all the months are present. So when i make the visualisation, there is an error with the dimensions.

I tried to solve this by making new lists and adding 0's to imply that there were no sales in the previous months, and clearly that did not work.

(I'm new to making graphs with python and the graph I'm making is a line chart showing the sales in each month in both years)

```<code># Retrieve data from each year
month = ['January', 'February', 'March', 'April', 'May', 'June',
         'July', 'August', 'September', 'October', 'November', 'December']

#2014
#only 2 months instead of 12 as shown above
#month2018 = ['November', 'December']
revenue2014 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
profits2014 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

year2014 = df[df['order_year'] == 2014]
temp1 = year2014.groupby('order_month')['unitprice_in_usd'].sum().round(decimals = 2)
cost2014 = year2014.groupby('order_month')['unitcost_in_usd'].sum()
temp2 = (temp1 - cost2014).round(decimals = 2)
revenue2014.append(temp1)
profits2014.append(temp2)

#2015
year2015 = df[df['order_year'] == 2015]
revenue2015 = year2015.groupby('order_month')['unitprice_in_usd'].sum().round(decimals = 2)
cost2015 = year2015.groupby('order_month')['unitcost_in_usd'].sum()
profits2015 = (revenue2015 - cost2015).round(decimals = 2)
</code>```

If you wanna see my code for making the graphs...

```<code>fig, axes = plt.subplots(nrows = 1, ncols = 1, figsize=(15, 5))

axes.plot(month, revenue2014, c = 'r', label = '2014')
axes.plot(month, revenue2015, c = 'g', label = '2015')

axes.set_title('Revenue In Each Month From Each Year', fontsize = 20);

axes.set_xlabel('Months', fontsize = 15)
axes.set_ylabel('Revenue ($)', fontsize = 15)

axes.tick_params(axis = 'x', labelsize = 10)
axes.tick_params(axis = 'y', labelsize = 10)

axes.set_xlim(left = -1, right = 12)

axes.grid(c = 'r', alpha = .2, linestyle = '--')

axes.legend(loc = (1.02, 0), borderaxespad = 0, fontsize = 20)

fig.tight_layout()

plt.show()
</code>```

I appreciate any and all suggestions :))

答:
You can convert column order_month to categorical with all months, so if aggregate sum get all months and for missing values 0:

```<code>df['order_month'] = pd.Categorical(df['order_month'], categories=month, ordered=True)
</code>```

Body:
A quick summary of what I'm trying to do:
I'm trying to retrieve sales data from a CSV file, put them in a dataframe, and make a visualisation from them.

My issue is, for the year 2014, only months November and December are present. And for 2015, all the months are present. So when i make the visualisation, there is an error with the dimensions.

I tried to solve this by making new lists and adding 0's to imply that there were no sales in the previous months, and clearly that did not work.

(I'm new to making graphs with python and the graph I'm making is a line chart showing the sales in each month in both years)

# Retrieve data from each year
month = ['January', 'February', 'March', 'April', 'May', 'June',
         'July', 'August', 'September', 'October', 'November', 'December']

#2014
#only 2 months instead of 12 as shown above
#month2018 = ['November', 'December']
revenue2014 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
profits2014 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

year2014 = df[df['order_year'] == 2014]
temp1 = year2014.groupby('order_month')['unitprice_in_usd'].sum().round(decimals = 2)
cost2014 = year2014.groupby('order_month')['unitcost_in_usd'].sum()
temp2 = (temp1 - cost2014).round(decimals = 2)
revenue2014.append(temp1)
profits2014.append(temp2)

#2015
year2015 = df[df['order_year'] == 2015]
revenue2015 = year2015.groupby('order_month')['unitprice_in_usd'].sum().round(decimals = 2)
cost2015 = year2015.groupby('order_month')['unitcost_in_usd'].sum()
profits2015 = (revenue2015 - cost2015).round(decimals = 2)

If you wanna see my code for making the graphs...

fig, axes = plt.subplots(nrows = 1, ncols = 1, figsize=(15, 5))

axes.plot(month, revenue2014, c = 'r', label = '2014')
axes.plot(month, revenue2015, c = 'g', label = '2015')

axes.set_title('Revenue In Each Month From Each Year', fontsize = 20);

axes.set_xlabel('Months', fontsize = 15)
axes.set_ylabel('Revenue ($)', fontsize = 15)

axes.tick_params(axis = 'x', labelsize = 10)
axes.tick_params(axis = 'y', labelsize = 10)

axes.set_xlim(left = -1, right = 12)

axes.grid(c = 'r', alpha = .2, linestyle = '--')

axes.legend(loc = (1.02, 0), borderaxespad = 0, fontsize = 20)

fig.tight_layout()

plt.show()

I appreciate any and all suggestions :))

Body:
You can convert column order_month to categorical with all months, so if aggregate sum get all months and for missing values 0:

df['order_month'] = pd.Categorical(df['order_month'], categories=month, ordered=True)


问:
Is there any shortcut to select the current line in Visual Studio?
I couldn't find such feature in VS's shortcut list. Is there anyway?</p>

答: You can enter, home then shift + end as well. What it will do is take you to the beginning of line then select the whole line till end. Or alternatively first enter end then shift + home