问:
Flutter - Render Text Class with value of Variable. Possible Type problem?
Creating a set of UI Tiles using a sizedBox with nested Text class. Trying to set the Text() class value on LINE 20 to equal a variable (variable is "symbol") of type String. When I replace the Text value with a String ("text placeholder") it compiles without issue. For some reason the Text class doesn't want to render a variable value, only a hard-coded String value.

The lint error in Android Studio says "The evaluation of a constant creation must be constant expressions. Try making the constant a valid constant, or use 'new' to call the constructor"

```<code>import 'package:flutter/material.dart';
import 'package:GDT360/gdtSymbols.dart';

var symbol = GdtKey().angularity.symbol;

GdtSymbol qgtSymbols = GdtKey as GdtSymbol;

class boxTile extends StatelessWidget {
  const boxTile({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 200.0,
      height: 300.0,
      child: const Card(
        child: Center(
          child: Text(symbol,
            style: TextStyle(
                color: Color(0XFF07BCE7),
                fontSize: 36
            ),
      )),
    )
    );
  }
}

</code>```

Here is the Class where the variable value is coming from:

```<code>class GdtSymbol {
  String name;
  String symbol;
  String translation;

  GdtSymbol({String name, String symbol, String translation}) {
    name = name;
    symbol = symbol;
    translation = translation;
  }

  }

  class GdtKey {
    GdtSymbol angularity = GdtSymbol(name: 'Angularity',
        symbol: '∠',
        translation: 'Angularity Placeholder Definition');

    GdtSymbol arkLength = GdtSymbol(name: 'Ark Length',
        symbol: '⌢',
        translation: 'Ark Length Placeholder Definition');

    GdtSymbol between = GdtSymbol(name: 'Between',
        symbol: '↔',
        translation: 'Between Placeholder Definition');
  }

</code>```

Any suggestions?

答:
You can copy paste run full code below

Step 1 : remove const keyword in front of Card

Step 2 : construction of GdtSymbol need this keyword

```<code>GdtSymbol({this.name, this.symbol, this.translation}) {
</code>```

working demo

full code

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

var symbol = GdtKey().angularity.symbol;

GdtSymbol qgtSymbols = GdtKey as GdtSymbol;

class boxTile extends StatelessWidget {
  const boxTile({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: 200.0,
        height: 300.0,
        child: Card(
          child: Center(
              child: Text(
            symbol,
            style: TextStyle(color: Color(0XFF07BCE7), fontSize: 36),
          )),
        ));
  }
}

class GdtSymbol {
  String name;
  String symbol;
  String translation;

  GdtSymbol({this.name, this.symbol, this.translation}) {
    name = name;
    symbol = symbol;
    translation = translation;
  }
}

class GdtKey {
  GdtSymbol angularity = GdtSymbol(
      name: 'Angularity',
      symbol: '∠',
      translation: 'Angularity Placeholder Definition');

  GdtSymbol arkLength = GdtSymbol(
      name: 'Ark Length',
      symbol: '⌢',
      translation: 'Ark Length Placeholder Definition');

  GdtSymbol between = GdtSymbol(
      name: 'Between',
      symbol: '↔',
      translation: 'Between Placeholder Definition');
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            boxTile(),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
Creating a set of UI Tiles using a sizedBox with nested Text class. Trying to set the Text() class value on LINE 20 to equal a variable (variable is "symbol") of type String. When I replace the Text value with a String ("text placeholder") it compiles without issue. For some reason the Text class doesn't want to render a variable value, only a hard-coded String value.

The lint error in Android Studio says "The evaluation of a constant creation must be constant expressions. Try making the constant a valid constant, or use 'new' to call the constructor"

import 'package:flutter/material.dart';
import 'package:GDT360/gdtSymbols.dart';

var symbol = GdtKey().angularity.symbol;

GdtSymbol qgtSymbols = GdtKey as GdtSymbol;

class boxTile extends StatelessWidget {
  const boxTile({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 200.0,
      height: 300.0,
      child: const Card(
        child: Center(
          child: Text(symbol,
            style: TextStyle(
                color: Color(0XFF07BCE7),
                fontSize: 36
            ),
      )),
    )
    );
  }
}

Here is the Class where the variable value is coming from:

class GdtSymbol {
  String name;
  String symbol;
  String translation;

  GdtSymbol({String name, String symbol, String translation}) {
    name = name;
    symbol = symbol;
    translation = translation;
  }

  }

  class GdtKey {
    GdtSymbol angularity = GdtSymbol(name: 'Angularity',
        symbol: '∠',
        translation: 'Angularity Placeholder Definition');

    GdtSymbol arkLength = GdtSymbol(name: 'Ark Length',
        symbol: '⌢',
        translation: 'Ark Length Placeholder Definition');

    GdtSymbol between = GdtSymbol(name: 'Between',
        symbol: '↔',
        translation: 'Between Placeholder Definition');
  }

Any suggestions?

Body:
You can copy paste run full code below

Step 1 : remove const keyword in front of Card

Step 2 : construction of GdtSymbol need this keyword

GdtSymbol({this.name, this.symbol, this.translation}) {

working demo

full code

import 'package:flutter/material.dart';

var symbol = GdtKey().angularity.symbol;

GdtSymbol qgtSymbols = GdtKey as GdtSymbol;

class boxTile extends StatelessWidget {
  const boxTile({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: 200.0,
        height: 300.0,
        child: Card(
          child: Center(
              child: Text(
            symbol,
            style: TextStyle(color: Color(0XFF07BCE7), fontSize: 36),
          )),
        ));
  }
}

class GdtSymbol {
  String name;
  String symbol;
  String translation;

  GdtSymbol({this.name, this.symbol, this.translation}) {
    name = name;
    symbol = symbol;
    translation = translation;
  }
}

class GdtKey {
  GdtSymbol angularity = GdtSymbol(
      name: 'Angularity',
      symbol: '∠',
      translation: 'Angularity Placeholder Definition');

  GdtSymbol arkLength = GdtSymbol(
      name: 'Ark Length',
      symbol: '⌢',
      translation: 'Ark Length Placeholder Definition');

  GdtSymbol between = GdtSymbol(
      name: 'Between',
      symbol: '↔',
      translation: 'Between Placeholder Definition');
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            boxTile(),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


来源: stackexchange

问:
Automate azure azcopy using python on windows
I am trying to use azcopy from python, I have already used this from CLI and it is working!

I have successfully executted the following commands:

for upload :

```<code>set AZCOPY_SPA_CLIENT_SECRET=<my client secret>
azcopy login --service-principal --application-id=<removed> --tenant-id=<removed>
azcopy copy "D:\azure\content" "https://dummyvalue.blob.core.windows.net/container1/result4" --overwrite=prompt --follow-symlinks --recursive --from-to=LocalBlob --blob-type=Detect
</code>```

Similarly for download

```<code>azcopy copy "https://dummyvalue.blob.core.windows.net/container1/result4" "D:\azure\azcopy_windows_amd64_10.4.3\temp\result2" --recursive
</code>```

Now, I want to automate these commands using python, I know that azcopy can also be used using SAS keys but that is out of scope for my working

First attempt:

```<code>from subprocess import call
call(["azcopy", "login", "--service-principal", "--application-id=<removed>", "--tenant-id=<removed>"])
</code>```

Second attempt:

```<code>import os
os.system("azcopy login --service-principal --application-id=<removed> --tenant-id=<removed>")
</code>```

I have already set AZCOPY_SPA_CLIENT_SECRET in my environment.

I am using python 3 on windows.

Every time I get this error:

Failed to perform login command:  service principal auth requires an
  application ID, and client secret/certificate

NOTE: If your credential was created in the last 5 minutes, please
  wait a few minutes and try again.

I don't want to use Azure VM to do this job

Could anyone please help me fix this problem?

答:
This is because the set cmd does not set a permanent environment variable, it only takes effect in the current windows cmd prompt.

You should manually set the environment variable via UI or try to use setx command.

I did a test by using your code, and manually set the environment variable of AZCOPY_SPA_CLIENT_SECRET as per UI, then the code can run without issues(it may take a few minutes to take effect).

Test result is as below:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use azcopy from python, I have already used this from CLI and it is working!

I have successfully executted the following commands:

for upload :

set AZCOPY_SPA_CLIENT_SECRET=<my client secret>
azcopy login --service-principal --application-id=<removed> --tenant-id=<removed>
azcopy copy "D:\azure\content" "https://dummyvalue.blob.core.windows.net/container1/result4" --overwrite=prompt --follow-symlinks --recursive --from-to=LocalBlob --blob-type=Detect

Similarly for download

azcopy copy "https://dummyvalue.blob.core.windows.net/container1/result4" "D:\azure\azcopy_windows_amd64_10.4.3\temp\result2" --recursive

Now, I want to automate these commands using python, I know that azcopy can also be used using SAS keys but that is out of scope for my working

First attempt:

from subprocess import call
call(["azcopy", "login", "--service-principal", "--application-id=<removed>", "--tenant-id=<removed>"])

Second attempt:

import os
os.system("azcopy login --service-principal --application-id=<removed> --tenant-id=<removed>")

I have already set AZCOPY_SPA_CLIENT_SECRET in my environment.

I am using python 3 on windows.

Every time I get this error:

Failed to perform login command:  service principal auth requires an
  application ID, and client secret/certificate

NOTE: If your credential was created in the last 5 minutes, please
  wait a few minutes and try again.

I don't want to use Azure VM to do this job

Could anyone please help me fix this problem?


问:
How to disable Remote JS Debugging in React-Native
I realize that the normal way to disable debugging is by going to the developer menu.
The problem is that since I turned on debugging for my app I am testing (React Native & Android emulator) I have been getting a white screen when the app loads with no information on the console and no ability to access the Dev menu to turn off the debugging.

So I am stuck. SInce JS debugging seens to be specific to the App I assume there is SOMEWHERE else either in the emulator or in react that I can turn it off.

Please advise?
Thanks

答: Sorry this is coming late but it will help others in the future. If you're facing this issue, just uninstall the expo client app on your mobile device or emulator and install the expo app again and it will fix that.</p>

ContentLicense: CC BY-SA 3.0


问:
NavigationManager does not works as expected?
If I create a page in Shared - LoginPage.razor :

```<code>@inherits LayoutComponentBase

@inject IJSRuntime JSRuntime;
@inject NavigationManager NavigationManager;

<button @onclick="onBtnClick"> sfsdf</button>

@code
{
    public void onBtnClick()
    {
        NavigationManager.NavigateTo( "/Error" );
    }
}
</code>```

in App.razor change DefaultLayout to the new page above:

```<code><Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(LoginPage)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(LoginPage)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
</code>```

Then create a page inside Pages. let say ErrorPage.razor :

```<code>@page "/Error"
<h3>ErrorPage</h3>

@code
{
}
</code>```

And if I run the app and click the button the page should be changing to Error page, but only the URL is changing.

how can I switch to Error page ?

答:
I think, you have missed @Body tag from LoginPage bootstrap component, which will load your error component on button click.

LoginPage.razor

```<code>@inherits LayoutComponentBase
@inject NavigationManager navigationManager

<button @onclick="onButtonClick">Go To Error Page</button>

<div class="bodyLoginPage">
    @Body
</div>

@code{
    public void onButtonClick()
    {
        navigationManager.NavigateTo("/Error");
    }
}
</code>```

Hope, it will help. Thanks

Body:
If I create a page in Shared - LoginPage.razor :

@inherits LayoutComponentBase

@inject IJSRuntime JSRuntime;
@inject NavigationManager NavigationManager;

<button @onclick="onBtnClick"> sfsdf</button>

@code
{
    public void onBtnClick()
    {
        NavigationManager.NavigateTo( "/Error" );
    }
}

in App.razor change DefaultLayout to the new page above:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(LoginPage)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(LoginPage)">

Sorry, there's nothing at this address.

        </LayoutView>
    </NotFound>
</Router>

Then create a page inside Pages. let say ErrorPage.razor :

@page "/Error"

ErrorPage

@code
{
}

And if I run the app and click the button the page should be changing to Error page, but only the URL is changing.

how can I switch to Error page ?

Body:
I think, you have missed @Body tag from LoginPage bootstrap component, which will load your error component on button click.

LoginPage.razor

@inherits LayoutComponentBase
@inject NavigationManager navigationManager

<button @onclick="onButtonClick">Go To Error Page</button>

<div class="bodyLoginPage">
    @Body
</div>

@code{
    public void onButtonClick()
    {
        navigationManager.NavigateTo("/Error");
    }
}

Hope, it will help. Thanks


问:
Detect Faces with ML Kit on Android using CameraView
I am trying to run this example of face detection with the firebase MLkit on Android. Instead of the built in CameraView I use the library CameraView.
Running the code the logs says: Faces: [], so no faces were found from the camera.

You can checkout the project here on github.

the code:

```<code>import android.os.Bundle
import android.util.Log
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import androidx.annotation.WorkerThread
import com.otaliastudios.cameraview.CameraView
import com.otaliastudios.cameraview.Frame
import com.otaliastudios.cameraview.FrameProcessor
import com.otaliastudios.cameraview.Size
import androidx.core.view.ViewCompat.getRotation
import com.google.android.gms.tasks.OnFailureListener
import com.google.firebase.FirebaseApp
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata
import com.google.firebase.ml.vision.face.FirebaseVisionFace
import com.google.firebase.ml.vision.face.FirebaseVisionFaceContour
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions
import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark

class MainActivity : AppCompatActivity() {

    private lateinit var textMessage: TextView
    private lateinit var camera:CameraView
    private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                textMessage.setText(R.string.title_home)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                textMessage.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                textMessage.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        textMessage = findViewById(R.id.message)
        navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)

        camera = findViewById<CameraView>(R.id.camera)
        camera.setLifecycleOwner(this)

        val realTimeOpts1 = FirebaseVisionFaceDetectorOptions.Builder()
            .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
            .build()
        val realTimeOpts = FirebaseVisionFaceDetectorOptions.Builder()
            .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
            .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
            .build()

        FirebaseApp.initializeApp(this);

        camera.addFrameProcessor { frame ->
            val data = frame.data
            val rotation = frame.rotation
            val time = frame.time
            val size = frame.size
            val format = frame.format
            val metadata = FirebaseVisionImageMetadata.Builder()
                .setWidth(480) // 480x360 is typically sufficient for
                .setHeight(360) // image recognition
                .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
                .setRotation(3)
                .build()
            val image = FirebaseVisionImage.fromByteArray(data, metadata)
            val detector = FirebaseVision.getInstance()
                .getVisionFaceDetector(realTimeOpts)

            val result = detector.detectInImage(image)
                .addOnSuccessListener { faces ->
                    // Task completed successfully
                    // ...
                    Log.e("FACE", faces.toString())

                    for (face in faces) {
                        val bounds = face.boundingBox
                        val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees
                        val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees

                        // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
                        // nose available):
                        val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR)
                        leftEar?.let {
                            val leftEarPos = leftEar.position
                        }

                        // If contour detection was enabled:
                        val leftEyeContour = face.getContour(FirebaseVisionFaceContour.LEFT_EYE).points
                        val upperLipBottomContour = face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).points

                        // If classification was enabled:
                        if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
                            val smileProb = face.smilingProbability
                        }
                        if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
                            val rightEyeOpenProb = face.rightEyeOpenProbability
                        }

                        // If face tracking was enabled:
                        if (face.trackingId != FirebaseVisionFace.INVALID_ID) {
                            val id = face.trackingId
                        }
                    }
        }.addOnFailureListener(
                    object : OnFailureListener {
                        override fun onFailure(e: Exception) {
                            // Task failed with an exception
                            // ...
                            Log.e("M", e.toString())
                        }
                    })
    }}

}
</code>```

in activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:text="@string/title_home"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <androidx.cardview.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:layout_gravity="center"
            android:layout_width="280dp"
            card_view:cardCornerRadius="280dp"
            android:layout_height="280dp">
        <com.otaliastudios.cameraview.CameraView
                android:id="@+id/camera"
                app:cameraFacing="front"
                android:keepScreenOn="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    </androidx.cardview.widget.CardView>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Tried the same also with Fotoapparat, same result: No faces found. What am I missing here?

答: I think the problem is frame.rotation value. Maybe you can use FirebaseVisionImageMetadata.ROTATION_90 for FirebaseVisionImageMetadata</p>

Body:
I am trying to run this example of face detection with the firebase MLkit on Android. Instead of the built in CameraView I use the library CameraView.
Running the code the logs says: Faces: [], so no faces were found from the camera.

You can checkout the project here on github.

the code:

import android.os.Bundle
import android.util.Log
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import androidx.annotation.WorkerThread
import com.otaliastudios.cameraview.CameraView
import com.otaliastudios.cameraview.Frame
import com.otaliastudios.cameraview.FrameProcessor
import com.otaliastudios.cameraview.Size
import androidx.core.view.ViewCompat.getRotation
import com.google.android.gms.tasks.OnFailureListener
import com.google.firebase.FirebaseApp
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata
import com.google.firebase.ml.vision.face.FirebaseVisionFace
import com.google.firebase.ml.vision.face.FirebaseVisionFaceContour
import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions
import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark

class MainActivity : AppCompatActivity() {

    private lateinit var textMessage: TextView
    private lateinit var camera:CameraView
    private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_home -> {
                textMessage.setText(R.string.title_home)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_dashboard -> {
                textMessage.setText(R.string.title_dashboard)
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_notifications -> {
                textMessage.setText(R.string.title_notifications)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        textMessage = findViewById(R.id.message)
        navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)

        camera = findViewById<CameraView>(R.id.camera)
        camera.setLifecycleOwner(this)

        val realTimeOpts1 = FirebaseVisionFaceDetectorOptions.Builder()
            .setContourMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
            .build()
        val realTimeOpts = FirebaseVisionFaceDetectorOptions.Builder()
            .setPerformanceMode(FirebaseVisionFaceDetectorOptions.ACCURATE)
            .setLandmarkMode(FirebaseVisionFaceDetectorOptions.ALL_LANDMARKS)
            .build()

        FirebaseApp.initializeApp(this);

        camera.addFrameProcessor { frame ->
            val data = frame.data
            val rotation = frame.rotation
            val time = frame.time
            val size = frame.size
            val format = frame.format
            val metadata = FirebaseVisionImageMetadata.Builder()
                .setWidth(480) // 480x360 is typically sufficient for
                .setHeight(360) // image recognition
                .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
                .setRotation(3)
                .build()
            val image = FirebaseVisionImage.fromByteArray(data, metadata)
            val detector = FirebaseVision.getInstance()
                .getVisionFaceDetector(realTimeOpts)

            val result = detector.detectInImage(image)
                .addOnSuccessListener { faces ->
                    // Task completed successfully
                    // ...
                    Log.e("FACE", faces.toString())

                    for (face in faces) {
                        val bounds = face.boundingBox
                        val rotY = face.headEulerAngleY // Head is rotated to the right rotY degrees
                        val rotZ = face.headEulerAngleZ // Head is tilted sideways rotZ degrees

                        // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
                        // nose available):
                        val leftEar = face.getLandmark(FirebaseVisionFaceLandmark.LEFT_EAR)
                        leftEar?.let {
                            val leftEarPos = leftEar.position
                        }

                        // If contour detection was enabled:
                        val leftEyeContour = face.getContour(FirebaseVisionFaceContour.LEFT_EYE).points
                        val upperLipBottomContour = face.getContour(FirebaseVisionFaceContour.UPPER_LIP_BOTTOM).points

                        // If classification was enabled:
                        if (face.smilingProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
                            val smileProb = face.smilingProbability
                        }
                        if (face.rightEyeOpenProbability != FirebaseVisionFace.UNCOMPUTED_PROBABILITY) {
                            val rightEyeOpenProb = face.rightEyeOpenProbability
                        }

                        // If face tracking was enabled:
                        if (face.trackingId != FirebaseVisionFace.INVALID_ID) {
                            val id = face.trackingId
                        }
                    }
        }.addOnFailureListener(
                    object : OnFailureListener {
                        override fun onFailure(e: Exception) {
                            // Task failed with an exception
                            // ...
                            Log.e("M", e.toString())
                        }
                    })
    }}

}

in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:text="@string/title_home"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <androidx.cardview.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:layout_gravity="center"
            android:layout_width="280dp"
            card_view:cardCornerRadius="280dp"
            android:layout_height="280dp">
        <com.otaliastudios.cameraview.CameraView
                android:id="@+id/camera"
                app:cameraFacing="front"
                android:keepScreenOn="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    </androidx.cardview.widget.CardView>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>

Tried the same also with Fotoapparat, same result: No faces found. What am I missing here?


问:
Openlayers 3 map contextmenu
I would like to have a right-click context menu with the information of the point clicked.

I.e. I right click on map, get a dropdown menu, here if I would pick 'add marker' or similar, I need to have the clicked position.

I think simplest for getting the version right would be, if someone could add a simple drpdown menu on rightclick to this Test Fiddle

```<code>var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }),
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});
</code>```

I've seen this solution, but it didn't work out:
https://gis.stackexchange.com/questions/148428/how-can-i-select-a-feature-in-openlayers-3-by-right-click-it

答: For anyone trawling through these pages in 2020, OpenLayers now has a map.on('contextmenu', function) event handler

Title: Openlayers 3 map contextmenu

Body:
I would like to have a right-click context menu with the information of the point clicked.

I.e. I right click on map, get a dropdown menu, here if I would pick 'add marker' or similar, I need to have the clicked position.

I think simplest for getting the version right would be, if someone could add a simple drpdown menu on rightclick to this Test Fiddle

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }),
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

I've seen this solution, but it didn't work out:
https://gis.stackexchange.com/questions/148428/how-can-i-select-a-feature-in-openlayers-3-by-right-click-it


问:
Why is HH:mm 00:00 when year is included in JavaScript moment format?
I want to format a time to 'DD-MM-yyyy HH:mm', but the 'HH:mm' part is unexpectedly 00:00.

In Node.js I have the following code using the moment library:

```<code>console.log(history.created_at)
console.log(moment(history.created_at).format('DD-MM-yyyy HH:mm'))
console.log(moment(history.created_at).format('DD-MM HH:mm'))
</code>```

which e.g. gives the output:

```<code>2020-06-03 08:43:07.778+02
03-06-2020 00:00
03-06 08:43
</code>```

As seen above, formatting with 'DD-MM-yyyy HH:mm' gives invalid hours and minutes, but when I remove the year from the formatting string, i.e. 'DD-MM HH:mm' the hours and minutes are correct.

Am I doing something wrong, or is this a bug?

答:
const created_at = '2020-06-03 08:43:07.778+02'

console.log(
  moment().format('DD-MM-YYYY HH:mm')
)
console.log(
  moment(created_at).format('DD-MM-YYYY HH:mm')
)
console.log(
  moment(created_at).format('DD-MM-yyyy HH:mm')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script></code>```

You should use YYYY instead yyyy

Body:
I want to format a time to 'DD-MM-yyyy HH:mm', but the 'HH:mm' part is unexpectedly 00:00.

In Node.js I have the following code using the moment library:

console.log(history.created_at)
console.log(moment(history.created_at).format('DD-MM-yyyy HH:mm'))
console.log(moment(history.created_at).format('DD-MM HH:mm'))

which e.g. gives the output:

2020-06-03 08:43:07.778+02
03-06-2020 00:00
03-06 08:43

As seen above, formatting with 'DD-MM-yyyy HH:mm' gives invalid hours and minutes, but when I remove the year from the formatting string, i.e. 'DD-MM HH:mm' the hours and minutes are correct.

Am I doing something wrong, or is this a bug?

Body:
const created_at = '2020-06-03 08:43:07.778+02'

console.log(
  moment().format('DD-MM-YYYY HH:mm')
)
console.log(
  moment(created_at).format('DD-MM-YYYY HH:mm')
)
console.log(
  moment(created_at).format('DD-MM-yyyy HH:mm')
)

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

You should use YYYY instead yyyy


问:
Cannot choose from an empty sequence Locust Error
I am attempting to run a Locust file and am repeatedly facing the following error:

```<code>    Traceback (most recent call last):
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 280, in run
    self.schedule_task(self.get_next_task())
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 408, in get_next_task
    return random.choice(self.user.tasks)
  File "/Applications/anaconda/lib/python3.6/random.py", line 260, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

</code>```

My locust file looks like this:

```<code>import base64

from locust import HttpUser, TaskSet, task
from random import randint, choice

class WebTasks(TaskSet):

    @task
    def load(self):
        base64string = base64.encodebytes(('%s:%s' % ('user', 'password')).encode()).decode().replace('\n', '')

        catalogue = self.client.get("/catalogue").json()
        category_item = choice(catalogue)
        item_id = category_item["id"]

        self.client.get("/")
        self.client.get("/login", headers={"Authorization":"Basic %s" % base64string})
        self.client.get("/category.html")
        self.client.get("/detail.html?id={}".format(item_id))
        self.client.delete("/cart")
        self.client.post("/cart", json={"id": item_id, "quantity": 1})
        self.client.get("/basket.html")
        self.client.post("/orders")

class Web(HttpUser):
    task_set = WebTasks
    min_wait = 0
    max_wait = 0
</code>```

I believe the issue normally arises from not having any tasks defined, but I do have a task defined here so I am not sure why I would be getting this error. I am running on Python 3.6.8 and Locust 1.0.2 on Mac OS.

答:
There have been some changes in Locust 1.0, so try replacing

```<code>task_set = WebTasks
</code>```

with

```<code>tasks = [WebTasks]
</code>```

Or do away with the TaskSet entirely and place your @task declarations directly on the User. For more info, see https://docs.locust.io/en/stable/changelog.html#changelog-1-0

The error message is bad though, I thought we had improved that...

Body:
I am attempting to run a Locust file and am repeatedly facing the following error:

    Traceback (most recent call last):
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 280, in run
    self.schedule_task(self.get_next_task())
  File "/Applications/anaconda/lib/python3.6/site-packages/locust/user/task.py", line 408, in get_next_task
    return random.choice(self.user.tasks)
  File "/Applications/anaconda/lib/python3.6/random.py", line 260, in choice
    raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence

My locust file looks like this:

import base64

from locust import HttpUser, TaskSet, task
from random import randint, choice

class WebTasks(TaskSet):

    @task
    def load(self):
        base64string = base64.encodebytes(('%s:%s' % ('user', 'password')).encode()).decode().replace('\n', '')

        catalogue = self.client.get("/catalogue").json()
        category_item = choice(catalogue)
        item_id = category_item["id"]

        self.client.get("/")
        self.client.get("/login", headers={"Authorization":"Basic %s" % base64string})
        self.client.get("/category.html")
        self.client.get("/detail.html?id={}".format(item_id))
        self.client.delete("/cart")
        self.client.post("/cart", json={"id": item_id, "quantity": 1})
        self.client.get("/basket.html")
        self.client.post("/orders")

class Web(HttpUser):
    task_set = WebTasks
    min_wait = 0
    max_wait = 0

I believe the issue normally arises from not having any tasks defined, but I do have a task defined here so I am not sure why I would be getting this error. I am running on Python 3.6.8 and Locust 1.0.2 on Mac OS.

Body:
There have been some changes in Locust 1.0, so try replacing

task_set = WebTasks

with

tasks = [WebTasks]

Or do away with the TaskSet entirely and place your @task declarations directly on the User. For more info, see https://docs.locust.io/en/stable/changelog.html#changelog-1-0

The error message is bad though, I thought we had improved that...


问:
css - How to change upload file button color without using "display:none"
I am currently using bootstrap for my HTML project. However, I am currently got stuck on how to change the color of upload file button. I tried to search on how to change it over the internet but everything uses display:none which hide the "no file chosen" or "the name file" appeared when the file is uploaded. That part is something that I really want to have.

This is the code that I have right now

```<code><form method="POST" action="/uploadFile" enctype="multipart/form-data">
                                          <label class="btn btn-primary"> File Upload <input type="file" name="file" style="display: none"/></label><br/><br/>
                                          <input type="submit" value="Submit" class="btn-primary" data-toggle="modal" data-target="#myModal"/>
                                      </form>
</code>```

How to change the button color to btn-primary without sacrificing the notice that it has from input type="file"?

/EDIT:
This is what I have right now,

This is what I want but the style of the button is btn-primary

this is the code that I have to achieve on the second picture

```<code><form method="POST" action="/uploadFile" enctype="multipart/form-data">
                                          <input type="file" name="file"/><br/><br/>
                                          <input type="submit" value="Submit" class="btn-primary" data-toggle="modal" data-target="#myModal"/>
                                      </form>
</code>```

答:
You may try this. I did not test it cross-browser but I think its no problem because the label is layered over the file input. You may change the css to have it in your styling.

Update: input type="file" for Bootstrap 3+4. Change the height at #form_upload .btn as commented in the css for Bootstrap 4.

```<code><form id="form_upload" class="form-inline" action="/uploadFile" method="post" enctype="multipart/form-data">
  <div class="form-group">
    <input id="file_upload" name="file" type="file" class="inputfile" data-multiple-caption="{count} files selected" multiple="multiple">
    <label for="file_upload" class="form-control"><span>Click to select file(s)</span></label>
    <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Upload</button>
  </div>
  <br/><br/>
</form>

<script>
var inputs = document.querySelectorAll('.inputfile');
Array.prototype.forEach.call(inputs, function(input) {
  var label = input.nextElementSibling;
  var labelVal = label.innerHTML;
  input.addEventListener('change', function(e) {
    var fileName = '';
    if (this.files && this.files.length > 1)
      fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
    else
      fileName = e.target.value.split('\\').pop();
    if (fileName)
      label.querySelector('span').innerHTML = fileName;
    else
      label.innerHTML = labelVal;
  });
});
</script>
</code>```

with this css

```<code>/* width of form */
#form_upload {
    display: block;
    max-width: 280px;
}
#form_upload .form-group {
    position: relative;
}
/* hide file input; width/height must be 1px! */
#form_upload .inputfile {
    position: absolute !important;
    clip: rect(0, 0, 0, 0);
    width: 1px;
    height: 1px;
    padding: 0;
    border: 0;
    overflow: hidden;
    white-space: nowrap;
}
/* label is new form-control */
#form_upload .form-control {
    /* next line: form-width minus button-width */
    width: 190px;
    margin-bottom: 1px;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-align: left;
    font-weight: 400;
    color: #555;
}
/* mouse over (copied from BS3) */
#form_upload .inputfile:focus + .form-control,
#form_upload .inputfile + .form-control:hover {
    border-color: #66afe9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, 0.6);
}
/* no pointer-events on touchscreen  */
#form_upload .form-control * {
    pointer-events: none;
}
/* upload button */
#form_upload .btn {
    /* Bootstrap 4 => height: 38px; */
    height: 38px;
    margin-top: -1px;
    margin-left: -0.5em;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
/* align middle on smartphone */
@media (max-width: 767px) {
    #form_upload .form-group,
    #form_upload .form-control {
        display: inline-block;
        margin-bottom: 0;
        vertical-align: middle;
    }
}
</code>```

Body:
I am currently using bootstrap for my HTML project. However, I am currently got stuck on how to change the color of upload file button. I tried to search on how to change it over the internet but everything uses display:none which hide the "no file chosen" or "the name file" appeared when the file is uploaded. That part is something that I really want to have.

This is the code that I have right now

<form method="POST" action="/uploadFile" enctype="multipart/form-data">
                                           File Upload <input type="file" name="file" style="display: none"/>

                                          <input type="submit" value="Submit" class="btn-primary" data-toggle="modal" data-target="#myModal"/>
                                      </form>

How to change the button color to btn-primary without sacrificing the notice that it has from input type="file"?

/EDIT:
This is what I have right now,

This is what I want but the style of the button is btn-primary

this is the code that I have to achieve on the second picture

<form method="POST" action="/uploadFile" enctype="multipart/form-data">
                                          <input type="file" name="file"/>

                                          <input type="submit" value="Submit" class="btn-primary" data-toggle="modal" data-target="#myModal"/>
                                      </form>

Body:
You may try this. I did not test it cross-browser but I think its no problem because the label is layered over the file input. You may change the css to have it in your styling.

Update: input type="file" for Bootstrap 3+4. Change the height at #form_upload .btn as commented in the css for Bootstrap 4.

<form id="form_upload" class="form-inline" action="/uploadFile" method="post" enctype="multipart/form-data">
  <div class="form-group">
    <input id="file_upload" name="file" type="file" class="inputfile" data-multiple-caption="{count} files selected" multiple="multiple">
    <label for="file_upload" class="form-control"><span>Click to select file(s)</span></label>
    <button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Upload</button>
  </div>
  <br/><br/>
</form>

<script>
var inputs = document.querySelectorAll('.inputfile');
Array.prototype.forEach.call(inputs, function(input) {
  var label = input.nextElementSibling;
  var labelVal = label.innerHTML;
  input.addEventListener('change', function(e) {
    var fileName = '';
    if (this.files && this.files.length > 1)
      fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
    else
      fileName = e.target.value.split('\\').pop();
    if (fileName)
      label.querySelector('span').innerHTML = fileName;
    else
      label.innerHTML = labelVal;
  });
});
</script>

with this css

/* width of form */
#form_upload {
    display: block;
    max-width: 280px;
}
#form_upload .form-group {
    position: relative;
}
/* hide file input; width/height must be 1px! */
#form_upload .inputfile {
    position: absolute !important;
    clip: rect(0, 0, 0, 0);
    width: 1px;
    height: 1px;
    padding: 0;
    border: 0;
    overflow: hidden;
    white-space: nowrap;
}
/* label is new form-control */
#form_upload .form-control {
    /* next line: form-width minus button-width */
    width: 190px;
    margin-bottom: 1px;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-align: left;
    font-weight: 400;
    color: #555;
}
/* mouse over (copied from BS3) */
#form_upload .inputfile:focus + .form-control,
#form_upload .inputfile + .form-control:hover {
    border-color: #66afe9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, 0.6);
}
/* no pointer-events on touchscreen  */
#form_upload .form-control * {
    pointer-events: none;
}
/* upload button */
#form_upload .btn {
    /* Bootstrap 4 => height: 38px; */
    height: 38px;
    margin-top: -1px;
    margin-left: -0.5em;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}
/* align middle on smartphone */
@media (max-width: 767px) {
    #form_upload .form-group,
    #form_upload .form-control {
        display: inline-block;
        margin-bottom: 0;
        vertical-align: middle;
    }
}


问:
Struggling to install/add JUnit plugin in Netbeans IDE 8.0.2
I am new to Netbeans and I am trying to install JUnit in the IDE.  I have searched multiple places and can not find a clear answer.  I am running Windows8 with the latest updates and Netbeans 8.0.2.  I have downloaded the jar file for JUnit opened Tools => Plugins then Downloaded tab.  I select the jar file but nothing happens.  I have also tried to run the jar file from commandline and double clicked it and nothing happens.  I am looking to expand my skills sets by practicing using JUnit so any help would be appreciated.

thank you.

答:
For some reason I am still using the old 8.0.2 version of Netbeans, and I found out that the install script apparently installs the junit plugin, but not the junit libs. Downloading the following files and adding them as test libs helped:

junit-4.13.jar

hamcrest-core-1.3.jar

At the time of this writing, they could be found here: https://github.com/junit-team/junit4/wiki/Download-and-Install


问:
Projecting data in R
Here my dataset, I have 194 countries with values from 2014 to 2018

```<code># A tibble: 10 x 3
   iso3  time  y
   <chr> <chr> <dbl>
 1 AFG   2014     0.50
 2 AFG   2015     0.55
 3 AFG   2016     0.63
 4 AFG   2017     0.68
 5 AFG   2018     0.69
 6 AGO   2014     0.54
 7 AGO   2015     0.58
 8 AGO   2016     0.57
 9 AGO   2017     0.51
10 AGO   2018     0.61
</code>```

What I would like to do is project data till 2023 using this function

```<code>proj <- function(y, time=2014:2018, target=2023){
  stopifnot(any(y>0) | any(y<1))
  period <- time[1]:target
  yhat <- predict(glm(y ~ time, family=quasibinomial), newdata=data.frame(time=period))
  return(data.frame(time=period, y=invlogit(yhat)))
}
</code>```

Now the problem is that I don't know how to use functions..how to apply the abive function to my dataset to create a new dataset where I have both historical data from 2014 to 2018 and projected data till 2023 for all countries, in the same format as above.

Could you help?

Thank you very much

Title: Projecting data in R

Body:
Here my dataset, I have 194 countries with values from 2014 to 2018

# A tibble: 10 x 3
   iso3  time  y
   <chr> <chr> <dbl>
 1 AFG   2014     0.50
 2 AFG   2015     0.55
 3 AFG   2016     0.63
 4 AFG   2017     0.68
 5 AFG   2018     0.69
 6 AGO   2014     0.54
 7 AGO   2015     0.58
 8 AGO   2016     0.57
 9 AGO   2017     0.51
10 AGO   2018     0.61

What I would like to do is project data till 2023 using this function

proj <- function(y, time=2014:2018, target=2023){
  stopifnot(any(y>0) | any(y<1))
  period <- time[1]:target
  yhat <- predict(glm(y ~ time, family=quasibinomial), newdata=data.frame(time=period))
  return(data.frame(time=period, y=invlogit(yhat)))
}

Now the problem is that I don't know how to use functions..how to apply the abive function to my dataset to create a new dataset where I have both historical data from 2014 to 2018 and projected data till 2023 for all countries, in the same format as above.

Could you help?

Thank you very much

Body:
Let's say this is your data:

df = structure(list(iso3 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L), .Label = c("AFG", "AGO"), class = "factor"), time = c(2014L,
2015L, 2016L, 2017L, 2018L, 2014L, 2015L, 2016L, 2017L, 2018L
), y = c(0.5, 0.55, 0.63, 0.68, 0.69, 0.54, 0.58, 0.57, 0.51,
0.61)), class = "data.frame", row.names = c(NA, 10L))

You still need a inverse logit function, which should be:

invlogit =function (x){ 1/(1 + exp(-x)) }

Then what you need to provide, are the y data in the time period for each country, so for example:

subset(df,iso3=="AFG" & time %in% 2014:2018)

gives you a subset of the data.frame in country AFG from 2014 to 2018. This only works in your function if the data is complete  (goes from 2014 to 2018) and sorted. We try that:

proj(subset(df,iso3=="AFG" & time %in% 2014:2018)$y)

   time         y
1  2014 0.5057644
2  2015 0.5598027
3  2016 0.6124600
4  2017 0.6626145
5  2018 0.7093585
6  2019 0.7520495
7  2020 0.7903234
8  2021 0.8240714
9  2022 0.8533952
10 2023 0.8785516

I suggest writing a function that handles situations when data is not sorted or is missing:

func = function(data,country){
data = subset(data,iso3==country)
data[match(2014:2018,data$time),]$y
}

res = lapply(unique(df$iso3),function(i){
data.frame(country=i,proj(func(df,country=i)))
})

res = do.call(rbind,res)

    country time         y
1       AFG 2014 0.5057644
2       AFG 2015 0.5598027
3       AFG 2016 0.6124600
4       AFG 2017 0.6626145
5       AFG 2018 0.7093585
6       AFG 2019 0.7520495
7       AFG 2020 0.7903234
8       AFG 2021 0.8240714
9       AFG 2022 0.8533952
10      AFG 2023 0.8785516
11      AGO 2014 0.5479759
21      AGO 2015 0.5550113
31      AGO 2016 0.5620247
41      AGO 2017 0.5690134
51      AGO 2018 0.5759748
61      AGO 2019 0.5829061
71      AGO 2020 0.5898048
81      AGO 2021 0.5966684
91      AGO 2022 0.6034943
101     AGO 2023 0.6102802


问:
Spring Data JPA - Stored procedure return multiple result with non-entity
I'm using the spring data JPA repository to call the stored procedure. As if throughout the application we have a tight dependency on the stored procedure I have to go with non-entity store procedure call. Below is the way I choose to call it:

```<code>@Query(value = "EXEC getAllOperation ?,?,?", nativeQuery = true)
Object[][] getAllOperation (@Param("user_details") int userId);
</code>```

It works well in all where stored procedure returns single resultset.

But it does not work with stored procedure returning multiple resultsets. It returns the first resultset only and not giving any error.

We have spring-boot-starter-data-jpa version 1.5.8 and hibernate-jpa version 2.1 in our project.

I have gone through several threads for this solution. But could not find any solution if I want to achieve this using the current approach only.

Please help me with this.

答:
In general Spring Data JPA supports multiple out parameters of stored procedures by returning them in a Map (see https://jira.spring.io/browse/DATAJPA-707).

I doubt though that this works with some parameters being ResultSets.

As an alternative you can always create a custom method and implement it directly on the EntityManager or a JdbcTemplate.

Body:
I'm using the spring data JPA repository to call the stored procedure. As if throughout the application we have a tight dependency on the stored procedure I have to go with non-entity store procedure call. Below is the way I choose to call it:

@Query(value = "EXEC getAllOperation ?,?,?", nativeQuery = true)
Object[][] getAllOperation (@Param("user_details") int userId);

It works well in all where stored procedure returns single resultset.

But it does not work with stored procedure returning multiple resultsets. It returns the first resultset only and not giving any error.

We have spring-boot-starter-data-jpa version 1.5.8 and hibernate-jpa version 2.1 in our project.

I have gone through several threads for this solution. But could not find any solution if I want to achieve this using the current approach only.

Please help me with this.


问:
How to cycle multiple forms in one page and retain same submit button in .NET core mvc?
I'm building a asp.net mvc web app, with razor pages to make things easier, and I ran into a bit of a snag because of my UI design.

I need to have multiple forms that can to cycled through by the user in a bootstrap navigation element. these forms are all unique, but they all have a 'comments' element (textbox and button) in a separate element to the right that serves as the submit button for the form.

Right now, I have both 'cards', rfi and knowledgebase, in one form with the comments element. When the user clicks submit on the comments element, is submits both cards, rfi and knowledgebase. I need the current form the user is looking at to be submitted when they click submit the form. Is there any way to do this? Should I use partial views?

```<code>@using (Html.BeginForm())
{
    <!--<div asp-validation-summary="All"></div>-->
    <div class="row">
        <div class="container col-sm-8">
            <div class="card form-nav-bar">
                <ul class="nav nav-pills">
                    <li class="nav-item">
                        <a class="nav-link active" data-toggle="pill" href="#rfi">RFI</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-toggle="pill" href="#kBase">Knowledge Base</a>
                    </li>
                </ul>
            </div>
            <div class="tab-content">
                <!--RFI card-->
                <div id="rfi" class="card container box-shadow tab-pane active">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-sm-12">
                                <h4>
                                    Consumer Information:
                                </h4>
                            </div>
                            <div class="field col-sm-4">
                                @Html.EditorFor(x => x.RFIModel.FirstName, new { htmlAttributes = new { placeholder = " " } })
                                @Html.LabelFor(x => x.RFIModel.FirstName)
                                @Html.ValidationMessageFor(x => x.RFIModel.FirstName, "", new { @class = "text-danger" })
                                . . .
                            </div>
                        </div>
                    </div>
                </div>
                <!--Knowledge Base card-->
                <div id="kBase" class="card container tab-pane">
                    <div class="card-body">
                        . . .
                    </div>
                </div>
            </div>
        </div>

        <!--Summary Modal-->
        <div class="container col-sm-4" role="dialog" id="Comments-Modal">
            <div class="modal-content box-shadow">
                <div class="modal-header">
                    <h5 class="modal-title">Summary</h5>
                </div>
                <div class="modal-body">
                    <div class="md-form">
                        <!--<label for="Comments"> </label>
                            <textarea type="text" id="Comments" class="md-textarea form-control" mdbInput></textarea>-->
                        @Html.LabelFor(x => x.RFIModel.Comments)
                        @Html.TextAreaFor(x => x.RFIModel.Comments, new { htmlAttributes = new { placeholder = " ", type = "text" }, @class = "md-textarea form-control" })
                        @Html.ValidationMessageFor(x => x.RFIModel.Comments, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
        </div>

    </div>
}
</code>```

答:
Yes, I think you can use js and ajax to reference the partial view dynamically:

```<code>@using (Html.BeginForm())
{
    <!--<div asp-validation-summary="All"></div>-->
    <div class="row">
        <div class="container col-sm-8">
            <div class="card form-nav-bar">
                <ul class="nav nav-pills">
                    <li class="nav-item">
                        <a id="rfiLink" class="nav-link active" data-toggle="pill" href="#rfi">RFI</a>
                    </li>
                    <li class="nav-item">
                        <a id="kBaseLink" class="nav-link" data-toggle="pill" href="#kBase">Knowledge Base</a>
                    </li>
                </ul>
            </div>
            <div class="tab-content">
                <div id="rfi" class="card container box-shadow tab-pane active">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-sm-12">
                                <h4>
                                    Consumer Information:
                                </h4>
                            </div>
                            <div class="field col-sm-4">
                                @Html.EditorFor(x => x.RFIModel.FirstName, new { htmlAttributes = new { placeholder = " " } })
                                @Html.LabelFor(x => x.RFIModel.FirstName)
                                @Html.ValidationMessageFor(x => x.RFIModel.FirstName, "", new { @class = "text-danger" })
                                . . .
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!--Summary Modal-->
        <div class="container col-sm-4" role="dialog" id="Comments-Modal">
            <div class="modal-content box-shadow">
                <div class="modal-header">
                    <h5 class="modal-title">Summary</h5>
                </div>
                <div class="modal-body">
                    <div class="md-form">
                        <!--<label for="Comments"> </label>
                            <textarea type="text" id="Comments" class="md-textarea form-control" mdbInput></textarea>-->
                        @Html.LabelFor(x => x.RFIModel.Comments)
                        @Html.TextAreaFor(x => x.RFIModel.Comments, new { htmlAttributes = new { placeholder = " ", type = "text" }, @class = "md-textarea form-control" })
                        @Html.ValidationMessageFor(x => x.RFIModel.Comments, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
        </div>

    </div>
}

@section scripts{
<script>
    $("#rfiLink").click(function () {
        $.ajax({
            type: "get",
            url: "Home/GetRFI",
            success: function (data) {
                $(".tab-content").empty();
                $(".tab-content").html(data);
            }
        })
    })

    $("#kBaseLink").click(function () {
        $.ajax({
            type: "get",
            url: "Home/GetkBase",
            success: function (data) {
                $(".tab-content").empty();
                $(".tab-content").html(data);
            }
        })
    })
</script>
}
</code>```

Define the corresponding method in the controller to return to the partial view:

```<code>public IActionResult GetRFI()
{
    return PartialView();
}

public IActionResult GetkBase()
{
    return PartialView();
}
</code>```

Body:
I'm building a asp.net mvc web app, with razor pages to make things easier, and I ran into a bit of a snag because of my UI design.

I need to have multiple forms that can to cycled through by the user in a bootstrap navigation element. these forms are all unique, but they all have a 'comments' element (textbox and button) in a separate element to the right that serves as the submit button for the form.

Right now, I have both 'cards', rfi and knowledgebase, in one form with the comments element. When the user clicks submit on the comments element, is submits both cards, rfi and knowledgebase. I need the current form the user is looking at to be submitted when they click submit the form. Is there any way to do this? Should I use partial views?

@using (Html.BeginForm())
{

                        RFI

                        Knowledge Base

                                    Consumer Information:

                                @Html.EditorFor(x => x.RFIModel.FirstName, new { htmlAttributes = new { placeholder = " " } })
                                @Html.LabelFor(x => x.RFIModel.FirstName)
                                @Html.ValidationMessageFor(x => x.RFIModel.FirstName, "", new { @class = "text-danger" })
                                . . .

                        . . .

Summary

                        @Html.LabelFor(x => x.RFIModel.Comments)
                        @Html.TextAreaFor(x => x.RFIModel.Comments, new { htmlAttributes = new { placeholder = " ", type = "text" }, @class = "md-textarea form-control" })
                        @Html.ValidationMessageFor(x => x.RFIModel.Comments, "", new { @class = "text-danger" })

                    <button type="submit" class="btn btn-primary">Submit</button>

}

Body:
Yes, I think you can use js and ajax to reference the partial view dynamically:

@using (Html.BeginForm())
{
    <!--<div asp-validation-summary="All"></div>-->
    <div class="row">
        <div class="container col-sm-8">
            <div class="card form-nav-bar">
                <ul class="nav nav-pills">
                    <li class="nav-item">
                        <a id="rfiLink" class="nav-link active" data-toggle="pill" href="#rfi">RFI</a>
                    </li>
                    <li class="nav-item">
                        <a id="kBaseLink" class="nav-link" data-toggle="pill" href="#kBase">Knowledge Base</a>
                    </li>
                </ul>
            </div>
            <div class="tab-content">
                <div id="rfi" class="card container box-shadow tab-pane active">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-sm-12">
                                <h4>
                                    Consumer Information:
                                </h4>
                            </div>
                            <div class="field col-sm-4">
                                @Html.EditorFor(x => x.RFIModel.FirstName, new { htmlAttributes = new { placeholder = " " } })
                                @Html.LabelFor(x => x.RFIModel.FirstName)
                                @Html.ValidationMessageFor(x => x.RFIModel.FirstName, "", new { @class = "text-danger" })
                                . . .
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!--Summary Modal-->
        <div class="container col-sm-4" role="dialog" id="Comments-Modal">
            <div class="modal-content box-shadow">
                <div class="modal-header">
                    <h5 class="modal-title">Summary</h5>
                </div>
                <div class="modal-body">
                    <div class="md-form">
                        <!--<label for="Comments"> </label>
                            <textarea type="text" id="Comments" class="md-textarea form-control" mdbInput></textarea>-->
                        @Html.LabelFor(x => x.RFIModel.Comments)
                        @Html.TextAreaFor(x => x.RFIModel.Comments, new { htmlAttributes = new { placeholder = " ", type = "text" }, @class = "md-textarea form-control" })
                        @Html.ValidationMessageFor(x => x.RFIModel.Comments, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
        </div>

    </div>
}

@section scripts{
<script>
    $("#rfiLink").click(function () {
        $.ajax({
            type: "get",
            url: "Home/GetRFI",
            success: function (data) {
                $(".tab-content").empty();
                $(".tab-content").html(data);
            }
        })
    })

    $("#kBaseLink").click(function () {
        $.ajax({
            type: "get",
            url: "Home/GetkBase",
            success: function (data) {
                $(".tab-content").empty();
                $(".tab-content").html(data);
            }
        })
    })
</script>
}

Define the corresponding method in the controller to return to the partial view:

public IActionResult GetRFI()
{
    return PartialView();
}

public IActionResult GetkBase()
{
    return PartialView();
}


问:
Retrieving data based with a where clause in firebase
Tried storing messages using firebase database. While retrieving the data using the reference messages i get all the messages.

```<code>firebase.database().ref('messages').on('child_added', function (snapshot{
    console.log(snapshot.val()
}
</code>```

How can i add a filter to it to receive only the messages sent by that particular user. I need the messages sent and received by the user ids I provide

答:
You need to perform a query:

```<code>firebase.database().ref('messages').orderByChild("user").equalTo("john").on('value', ((snapshot) =>{
    console.log(snapshot.val());
}
</code>```

Assuming you have the following database:

```<code>messages
   id
    user    : john
    message : message_here
</code>```

https://firebase.google.com/docs/database/web/lists-of-data

Body:
Tried storing messages using firebase database. While retrieving the data using the reference messages i get all the messages.

firebase.database().ref('messages').on('child_added', function (snapshot{
    console.log(snapshot.val()
}

How can i add a filter to it to receive only the messages sent by that particular user. I need the messages sent and received by the user ids I provide

Body:
You need to perform a query:

firebase.database().ref('messages').orderByChild("user").equalTo("john").on('value', ((snapshot) =>{
    console.log(snapshot.val());
}

Assuming you have the following database:

messages
   id
    user    : john
    message : message_here

https://firebase.google.com/docs/database/web/lists-of-data


问:
Exchange references between two same-level components
I have two custom-components that are spawned by a common parent with different data as two tabs on mat-tab-group.

<mat-tab-group>
  <mat-tab label="TAB1">
    <ng-template matTabContent>
      <custom-component [data]="tab1data"></custom-component>
    </ng-template>
  </mat-tab>
  <mat-tab label="TAB2">
    <ng-template matTabContent>
      <custom-component [data]="tab2data"></custom-component>
    </ng-template>
  </mat-tab>
</mat-tab-group>
```

<p>The <code>data</code> is a setter that sets the internal <code>_data</code> and wraps it in <code>MatTableDataSource</code>:  </p>

<pre class="lang-js prettyprint-override"><code>@Input()
set data(val: Data[]) {
    this._data = val;
    this.loadData();
}

loadData(): void {
    this.dataSource = new MatTableDataSource<Data>(this._data);
    this.dataSource.sort = this.sort;
}
</code>```

I have a situation where actions for component on the first tab should affect data on the other tab.
Is there any way to pass component references, so I could change _data and call loadData() from other component?

答:
You can do this with Rxjs observables

Here is stackblitz example of how to communicate between two components https://stackblitz.com/edit/angular-ivy-myr2kh

my-service.service.ts

```<code>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class MyServiceService {
  private dataChangeObservable = new Subject<any>();
    dataChangeStream = this.dataChangeObservable.asObservable();

  constructor() { }

  emitDataChange() {
    this.dataChangeObservable.next();
  }
}
</code>```

ComponentOne.component.ts

```<code>onclickDiv() {
    this.myService.emitDataChange(); // Here you are triggering for change
}
</code>```

ComponentTwo.component.ts

```<code>ngOnInit() {
    this.dataChangeSubscription$ = this.myService.dataChangeStream.subscribe(() => {
       this.count++; // Here you will get notified/listener of change
    })
 }
</code>```

Update

If you have same component instances, then you have to pass some value to determine on which instance should get updated

Like

https://stackblitz.com/edit/angular-ivy-4pznor

Your parent html

```<code><app-componentone [name]="'one'"></app-componentone>
<app-componentone [name]="'two'"></app-componentone>
</code>```

Here one and two pass as an input to just to identify the instance

Then your ts

```<code>import { Component, OnInit, Input } from '@angular/core';
import { MyServiceService } from '../my-service.service';

@Component({
   selector: 'app-componentone',
   templateUrl: './componentone.component.html',
   styleUrls: ['./componentone.component.css']
})
export class ComponentoneComponent implements OnInit {
  @Input() name; // it will have instance name
  count = 0;
  constructor(
     private myService: MyServiceService
  ) { }

  ngOnInit() {
    this.myService.dataChangeStream.subscribe((value) => { // here we will get to notify which instance should get updated
      if (this.name !== value) { // Here we checking for instance name for updating, if same component instance don't do anything else update
         this.count++;
      }
    })
  }

  onclickDiv() {
    // Here I am passing parameter, so if click is triggered from instance one, we have to update other instances, so passing parameter 'one' i.e. name, to avoid updating same component instance

    this.myService.emitDataChange(this.name);
  }
}
</code>```

Body:
I have two custom-components that are spawned by a common parent with different data as two tabs on mat-tab-group.

<mat-tab-group>
  <mat-tab label="TAB1">
    <ng-template matTabContent>
      <custom-component [data]="tab1data"></custom-component>
    </ng-template>
  </mat-tab>
  <mat-tab label="TAB2">
    <ng-template matTabContent>
      <custom-component [data]="tab2data"></custom-component>
    </ng-template>
  </mat-tab>
</mat-tab-group>

The data is a setter that sets the internal _data and wraps it in MatTableDataSource:

@Input()
set data(val: Data[]) {
    this._data = val;
    this.loadData();
}

loadData(): void {
    this.dataSource = new MatTableDataSource<Data>(this._data);
    this.dataSource.sort = this.sort;
}

I have a situation where actions for component on the first tab should affect data on the other tab.
Is there any way to pass component references, so I could change _data and call loadData() from other component?

Body:
You can do this with Rxjs observables

Here is stackblitz example of how to communicate between two components https://stackblitz.com/edit/angular-ivy-myr2kh

my-service.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class MyServiceService {
  private dataChangeObservable = new Subject<any>();
    dataChangeStream = this.dataChangeObservable.asObservable();

  constructor() { }

  emitDataChange() {
    this.dataChangeObservable.next();
  }
}

ComponentOne.component.ts

onclickDiv() {
    this.myService.emitDataChange(); // Here you are triggering for change
}

ComponentTwo.component.ts

ngOnInit() {
    this.dataChangeSubscription$ = this.myService.dataChangeStream.subscribe(() => {
       this.count++; // Here you will get notified/listener of change
    })
 }

Update

If you have same component instances, then you have to pass some value to determine on which instance should get updated

Like

https://stackblitz.com/edit/angular-ivy-4pznor

Your parent html

<app-componentone [name]="'one'"></app-componentone>
<app-componentone [name]="'two'"></app-componentone>

Here one and two pass as an input to just to identify the instance

Then your ts

import { Component, OnInit, Input } from '@angular/core';
import { MyServiceService } from '../my-service.service';

@Component({
   selector: 'app-componentone',
   templateUrl: './componentone.component.html',
   styleUrls: ['./componentone.component.css']
})
export class ComponentoneComponent implements OnInit {
  @Input() name; // it will have instance name
  count = 0;
  constructor(
     private myService: MyServiceService
  ) { }

  ngOnInit() {
    this.myService.dataChangeStream.subscribe((value) => { // here we will get to notify which instance should get updated
      if (this.name !== value) { // Here we checking for instance name for updating, if same component instance don't do anything else update
         this.count++;
      }
    })
  }

  onclickDiv() {
    // Here I am passing parameter, so if click is triggered from instance one, we have to update other instances, so passing parameter 'one' i.e. name, to avoid updating same component instance

    this.myService.emitDataChange(this.name);
  }
}


问:
Scale Regression Summary in Beamer Presentation
In order to create a presentation, I use R Markdown. I'd like to print a linear regression (lm) or mixed-effects model (lmer) summary on a slide. However, it does not fit neatly on the slide and I searched the web for a method that allows me to scale the summary, but I couldn't find anything useful. Of course, I could delve deeply into the LaTeX configuration of my Markdown document. However, I was wondering whether there is a quick solution e.g., using a certain package, function or set up the relevant chunk differently?</p>

答: I use stargazer to create the regresssion tables, there you can change the font size with font.size, the column spacing withcolumn.sep.width and/or print the regressions on one row with single.row = TRUE.


问:
What is the right API to use to remap keys in OSX?
I'm looking at Karabiner, the OSX keyboard remapper for Parallels development.  According to this issue this is best fixed by filing a bug with Apple.

What is the alternative (if any) supported API to create such a functionality?

答:
As noted by pkamb on the github issue that OP linked to (added since he posted), Apple technote TN2450 documents the proper API:

The IOKit HID APIs can be used for key remapping. The user will
provide a dictionary of key remapping that the HID event system will
apply to the keyboard.
 Listing 3 : Key Remapping using IOKit HID
APIs. // compiled with Xcode 8.2.1

```<code>#import <Foundation/Foundation.h>
#import <IOKit/hidsystem/IOHIDEventSystemClient.h>
#import <IOKit/hidsystem/IOHIDServiceClient.h>
#import <IOKit/hid/IOHIDUsageTables.h>

int main(int argc, char *argv[])
{
    IOHIDEventSystemClientRef system;
    CFArrayRef services;

    uint64_t aKey = 0x700000004;
    uint64_t bKey = 0x700000005;

    NSArray *map = @[
                     @{@kIOHIDKeyboardModifierMappingSrcKey:@(aKey),
                        @kIOHIDKeyboardModifierMappingDstKey:@(bKey)},
                     @{@kIOHIDKeyboardModifierMappingSrcKey:@(bKey),
                        @kIOHIDKeyboardModifierMappingDstKey:@(aKey)},
                     ];

    system = IOHIDEventSystemClientCreateSimpleClient(kCFAllocatorDefault);
    services = IOHIDEventSystemClientCopyServices(system);
    for(CFIndex i = 0; i < CFArrayGetCount(services); i++) {
        IOHIDServiceClientRef service = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(services, i);
        if(IOHIDServiceClientConformsTo(service, kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard)) {
            IOHIDServiceClientSetProperty(service, CFSTR(kIOHIDUserKeyUsageMapKey), (CFArrayRef)map);
        }
    }

    CFRelease(services);
    CFRelease(system);

    return 0;
}
</code>```

Example:

If you are trying to re-map the command / option / control keys on an external USB keyboard, take a look at the enum's defined in IOHIDUsageTables.h. For example, a Z-88 keyboard can be remapped to match the key layout on a MacBookPro using this mapping:

```<code>NSArray *remap = @[
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E3),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E2)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E2),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E3)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E6),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E7)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x700000065),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E6)}
];
</code>```

LeftGUI (E3) → LeftAlt (E2)

LeftAlt (E2) → LeftGUI (E3)

RightAlt (E6) → RightGUI (E7)

Application (65) → RightAlt (E6)

To undo a mapping, map the same keys back to their original values. Using the above example:

```<code>NSArray *unmap = @[
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E3),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E3)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E2),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E2)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E6),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E6)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x700000065),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x700000065)}
];
</code>```

Body:
As noted by pkamb on the github issue that OP linked to (added since he posted), Apple technote TN2450 documents the proper API:

The IOKit HID APIs can be used for key remapping. The user will
provide a dictionary of key remapping that the HID event system will
apply to the keyboard.
 Listing 3 : Key Remapping using IOKit HID
APIs. // compiled with Xcode 8.2.1

#import <Foundation/Foundation.h>
#import <IOKit/hidsystem/IOHIDEventSystemClient.h>
#import <IOKit/hidsystem/IOHIDServiceClient.h>
#import <IOKit/hid/IOHIDUsageTables.h>

int main(int argc, char *argv[])
{
    IOHIDEventSystemClientRef system;
    CFArrayRef services;

    uint64_t aKey = 0x700000004;
    uint64_t bKey = 0x700000005;

    NSArray *map = @[
                     @{@kIOHIDKeyboardModifierMappingSrcKey:@(aKey),
                        @kIOHIDKeyboardModifierMappingDstKey:@(bKey)},
                     @{@kIOHIDKeyboardModifierMappingSrcKey:@(bKey),
                        @kIOHIDKeyboardModifierMappingDstKey:@(aKey)},
                     ];

    system = IOHIDEventSystemClientCreateSimpleClient(kCFAllocatorDefault);
    services = IOHIDEventSystemClientCopyServices(system);
    for(CFIndex i = 0; i < CFArrayGetCount(services); i++) {
        IOHIDServiceClientRef service = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(services, i);
        if(IOHIDServiceClientConformsTo(service, kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard)) {
            IOHIDServiceClientSetProperty(service, CFSTR(kIOHIDUserKeyUsageMapKey), (CFArrayRef)map);
        }
    }

    CFRelease(services);
    CFRelease(system);

    return 0;
}

Example:

If you are trying to re-map the command / option / control keys on an external USB keyboard, take a look at the enum's defined in IOHIDUsageTables.h. For example, a Z-88 keyboard can be remapped to match the key layout on a MacBookPro using this mapping:

NSArray *remap = @[
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E3),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E2)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E2),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E3)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E6),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E7)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x700000065),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E6)}
];

LeftGUI (E3) → LeftAlt (E2)

LeftAlt (E2) → LeftGUI (E3)

RightAlt (E6) → RightGUI (E7)

Application (65) → RightAlt (E6)

To undo a mapping, map the same keys back to their original values. Using the above example:

NSArray *unmap = @[
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E3),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E3)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E2),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E2)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x7000000E6),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x7000000E6)},
  @{@kIOHIDKeyboardModifierMappingSrcKey:@(0x700000065),
    @kIOHIDKeyboardModifierMappingDstKey:@(0x700000065)}
];


问:
How to remove all lines from a text file starting at first empty line?
What is the best way to remove all lines from a text file starting at first empty line in Bash? External tools (awk, sed...) can be used!

Example

```<code>1: ABC
2: DEF
3:
4: GHI
</code>```

Line 3 and 4 should be removed and the remaining content should be saved in a new file.

答:
Another awk would be:

```<code>awk -vRS= '1;{exit}' file
</code>```

By setting the record separator RS to be an empty string, we define the records as paragraphs separated by a sequence of empty lines. It is now easily to adapt this to select the nth block as:

```<code>awk -vRS= '(FNR==n){print;exit}' file
</code>```

There is a problem with this method when processing files with a DOS line-ending (CRLF). There will be no empty lines as there will always be a CR in the line. But this problem applies to all presented methods.

Body:
What is the best way to remove all lines from a text file starting at first empty line in Bash? External tools (awk, sed...) can be used!

Example

1: ABC
2: DEF
3:
4: GHI

Line 3 and 4 should be removed and the remaining content should be saved in a new file.

Body:
Another awk would be:

awk -vRS= '1;{exit}' file

By setting the record separator RS to be an empty string, we define the records as paragraphs separated by a sequence of empty lines. It is now easily to adapt this to select the nth block as:

awk -vRS= '(FNR==n){print;exit}' file

There is a problem with this method when processing files with a DOS line-ending (CRLF). There will be no empty lines as there will always be a CR in the line. But this problem applies to all presented methods.