问:
Android using MaterialDatePicker and TextInputLayout
I am new to android development and currently trying to integrate material design into my app.
I would like to evaluate a simple form, for this purpose I used the components com.google.android.material.textfield.TextInputLayout and com.google.android.material.textfield.TextInputEditText for user input. Besides the text input, I need a date, which I want to read with a MaterialDatePicker.

I tried to display the MaterialDatePicker with OnFocusChangeListener, this works too, but I have two problems.

the display is a little bit delayed because first a keyboard is opened which is closed immediately after calling the MaterialDatePicker.

when the display is closed with the Back button, the focus is still on TextInputLayout. So I would have to change the focus first to open a MaterialDatePicker again.

This is how I implemented the OnFocusChangeListener

```<code>@Override
public void onFocusChange(View view, boolean selected) {

    if( view.getId() == R.id.myId&& selected ){

        MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.datePicker();
        MaterialDatePicker picker = builder.build();
        picker.show( this.getParentFragmentManager(), "DATE_PICKER" );
    }
}
</code>```

Are there alternative components of Material Design that are better suited for the presentation?  I would like to keep the behavior within the form, so as soon as the date is entered by the user, a small label should be displayed above, like this:

Thank you for your help.

答:
I recently encountered the same problem.

The first issue concerning the keyboard, is solved by calling:

```<code>mTextInputEditText.setInputType(InputType.TYPE_NULL);
</code>```

By setting the InputType to TYPE_NULL the keyboard won't open by clicking on the text field.
In addition, if you no longer want the user to be able to input any text, you can add:

```<code>mTextInputEditText.setKeyListener(null);
</code>```

The second issue, to show the DatePicker again while it is already in focus, you can set an extra onClickListener:

```<code>mTextInputEditText.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                openDatePicker();
            }
        });
</code>```

The OnClickListener is called as soon as the user clicks the text field again. Sadly it will not work with the first click.
You can look at this answer https://stackoverflow.com/a/11799891/9612595 for more information. Unfortunately, making the text field unfocusable resolves into weird behavior with the hint from Material.

I hope that helps!

Body:
I am new to android development and currently trying to integrate material design into my app.
I would like to evaluate a simple form, for this purpose I used the components com.google.android.material.textfield.TextInputLayout and com.google.android.material.textfield.TextInputEditText for user input. Besides the text input, I need a date, which I want to read with a MaterialDatePicker.

I tried to display the MaterialDatePicker with OnFocusChangeListener, this works too, but I have two problems.

the display is a little bit delayed because first a keyboard is opened which is closed immediately after calling the MaterialDatePicker.

when the display is closed with the Back button, the focus is still on TextInputLayout. So I would have to change the focus first to open a MaterialDatePicker again.

This is how I implemented the OnFocusChangeListener

@Override
public void onFocusChange(View view, boolean selected) {

    if( view.getId() == R.id.myId&& selected ){

        MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.datePicker();
        MaterialDatePicker picker = builder.build();
        picker.show( this.getParentFragmentManager(), "DATE_PICKER" );
    }
}

Are there alternative components of Material Design that are better suited for the presentation?  I would like to keep the behavior within the form, so as soon as the date is entered by the user, a small label should be displayed above, like this:

Thank you for your help.

Body:
I recently encountered the same problem.

The first issue concerning the keyboard, is solved by calling:

mTextInputEditText.setInputType(InputType.TYPE_NULL);

By setting the InputType to TYPE_NULL the keyboard won't open by clicking on the text field.
In addition, if you no longer want the user to be able to input any text, you can add:

mTextInputEditText.setKeyListener(null);

The second issue, to show the DatePicker again while it is already in focus, you can set an extra onClickListener:

mTextInputEditText.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                openDatePicker();
            }
        });

The OnClickListener is called as soon as the user clicks the text field again. Sadly it will not work with the first click.
You can look at this answer https://stackoverflow.com/a/11799891/9612595 for more information. Unfortunately, making the text field unfocusable resolves into weird behavior with the hint from Material.

I hope that helps!


来源: stackexchange

问:
Puppet 6 how to split or truncate domian name
I have array of domains like this:
'us1.domain.com', 'us2.domain.com', 'us3.domain.com', 'anotherdomain.com', 'yet.third.com'

I would split or truncate these domain names to:

```<code>domain.com
anotherdomain.com
third.com
</code>```

Could anybody prompt me, please?

This new array will use for certificate file name.

Thanks in advance

答:
You can solve that problem like this:

$array = [
  'us1.domain.com', 'us2.domain.com', 'us3.domain.com',
  'anotherdomain.com', 'yet.third.com'
]
notice($array.map |$x| { $y=$x.split(/\./); [$y[-2], $y[-1]].join('.') }.unique)
```

<p>Testing:</p>

```▶ puppet apply test.pp
Notice: Scope(Class[main]): [domain.com, anotherdomain.com, third.com]
Notice: Compiled catalog for 192-168-1-103.tpgi.com.au in environment production in 0.05 seconds
Notice: Applied catalog in 0.01 seconds
```

Key insights there:

You can split each element on a period using using the split function.

You can take the last and second last elements of an array using $arr[-1] and $arr[-2].

You can join it all back together again using the join function.

You can transform the list into a new list using the map function.

You can remove the duplicates using the unique function.

ContentLicense: CC BY-SA 4.0

Body:
I have array of domains like this:
'us1.domain.com', 'us2.domain.com', 'us3.domain.com', 'anotherdomain.com', 'yet.third.com'

I would split or truncate these domain names to:

domain.com
anotherdomain.com
third.com

Could anybody prompt me, please?

This new array will use for certificate file name.

Thanks in advance

Body:
You can solve that problem like this:

$array = [
  'us1.domain.com', 'us2.domain.com', 'us3.domain.com',
  'anotherdomain.com', 'yet.third.com'
]
notice($array.map |$x| { $y=$x.split(/\./); [$y[-2], $y[-1]].join('.') }.unique)

Testing:

▶ puppet apply test.pp
Notice: Scope(Class[main]): [domain.com, anotherdomain.com, third.com]
Notice: Compiled catalog for 192-168-1-103.tpgi.com.au in environment production in 0.05 seconds
Notice: Applied catalog in 0.01 seconds

Key insights there:

You can split each element on a period using using the split function.

You can take the last and second last elements of an array using $arr[-1] and $arr[-2].

You can join it all back together again using the join function.

You can transform the list into a new list using the map function.

You can remove the duplicates using the unique function.


问:
Array of types?
I have several structs, and I want to create an array of them so that I can use its members as an argument for a template, something like types = {int, float}; multiply<types[i]>();. It can be done through overloading, but I have lots of functions so this is not a way. As far as I know, we can store types only as pointers (so I'll actually have to dereference it: multiply<*types[i]>();), but here I stop to understand because to create a pointer I have to know type of variable it's pointing to, and what is a type of a class (of a type)? I thought "screw it, I'll use auto", but then it seems to be that pointers to different classes are of different types, so that I have to erase their type to store them in a common array, and so on, I have this now:

```<code>auto types = {std::make_shared<void>(Student), std::make_shared<void>(Citizen)};
</code>```

And it says that Student and Citizen don't refer to a value.

答:
I have several structs, and I want to create an array of them

In C++, arrays contain elements all of the same type. At runtime, types have disappeared since they have been erased (except with RTTI, related to dynamic_cast). So you cannot directly have an array containing elements of different types (or don't call that an array).

Please refer to this site and later to the C++11 standard n3337 for more about C++. You could find the C++17 standard too.

It looks that you want some tagged union in C++. Consider then using the standard std::variant template from C++17.

If you want a product type, use of course std::tuple as answered by Artyer

Take advantage of existing C++ containers, when they fit your needs. Of course you can combine them with product types, sum types, strings, nested containers, smart pointers, etc...

If you cannot use C++17 but just C++11 and need to implement some tagged union, use some anonymous union but be aware of the rule of five. Consider also using Boost or Qt (both provide tagged unions in their own way).

Read also a good C++ programming book, since C++ is a very difficult programming language (that I don't claim to master, just to use).

Title: Array of types?

Body:
I have several structs, and I want to create an array of them so that I can use its members as an argument for a template, something like types = {int, float}; multiply<types[i]>();. It can be done through overloading, but I have lots of functions so this is not a way. As far as I know, we can store types only as pointers (so I'll actually have to dereference it: multiply<*types[i]>();), but here I stop to understand because to create a pointer I have to know type of variable it's pointing to, and what is a type of a class (of a type)? I thought "screw it, I'll use auto", but then it seems to be that pointers to different classes are of different types, so that I have to erase their type to store them in a common array, and so on, I have this now:

auto types = {std::make_shared<void>(Student), std::make_shared<void>(Citizen)};

And it says that Student and Citizen don't refer to a value.


问:
How to implement video recorder in Camera2 API android?
How to implement video recorder in Camera2 API android? Code will be really helpful.</p>

答:
```<code>public void startRecordingVideo() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
  return;
}
try {
  closePreviewSession();
  setUpMediaRecorder();
  SurfaceTexture texture = mTextureView.getSurfaceTexture();
  assert texture != null;
  texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
  List<Surface> surfaces = new ArrayList<>();
  /**
   * Surface for the camera preview set up
   */
  Surface previewSurface = new Surface(texture);
  surfaces.add(previewSurface);
  mPreviewBuilder.addTarget(previewSurface);
  //MediaRecorder setup for surface
  Surface recorderSurface = mMediaRecorder.getSurface();
  surfaces.add(recorderSurface);
  mPreviewBuilder.addTarget(recorderSurface);
  // Start a capture session
  mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
    @Override
    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
      mPreviewSession = cameraCaptureSession;
      updatePreview();
      getActivity().runOnUiThread(() -> {
        mIsRecordingVideo = true;
        // Start recording
        mMediaRecorder.start();
      });
    }
    @Override
    public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
      Log.e(TAG, "onConfigureFailed: Failed");
    }
  }, mBackgroundHandler);
} catch (CameraAccessException | IOException e) {
  e.printStackTrace();
}
</code>```

}

on this site there is an example with your question
https://androidwave.com/video-recording-with-camera2-api-android/

Body:
public void startRecordingVideo() {
if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
  return;
}
try {
  closePreviewSession();
  setUpMediaRecorder();
  SurfaceTexture texture = mTextureView.getSurfaceTexture();
  assert texture != null;
  texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
  List<Surface> surfaces = new ArrayList<>();
  /**
   * Surface for the camera preview set up
   */
  Surface previewSurface = new Surface(texture);
  surfaces.add(previewSurface);
  mPreviewBuilder.addTarget(previewSurface);
  //MediaRecorder setup for surface
  Surface recorderSurface = mMediaRecorder.getSurface();
  surfaces.add(recorderSurface);
  mPreviewBuilder.addTarget(recorderSurface);
  // Start a capture session
  mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
    @Override
    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
      mPreviewSession = cameraCaptureSession;
      updatePreview();
      getActivity().runOnUiThread(() -> {
        mIsRecordingVideo = true;
        // Start recording
        mMediaRecorder.start();
      });
    }
    @Override
    public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
      Log.e(TAG, "onConfigureFailed: Failed");
    }
  }, mBackgroundHandler);
} catch (CameraAccessException | IOException e) {
  e.printStackTrace();
}

}

on this site there is an example with your question
https://androidwave.com/video-recording-with-camera2-api-android/


问:
Android openFileOutput - no permission to create storage
I have a problem with permissions in my application. It looks like my app does not have permissions to create files on storage.

```<code>String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;

try
{
   fos = getApplicationContext()
           .openFileOutput(FILENAME, Context.MODE_PRIVATE);
   fos.write(string.getBytes());
   fos.close();
}
catch (Exception e)
{
   e.printStackTrace();
}
</code>```

In my main class onCreate handler, and I always get:

```<code>06-02 13:23:52.996: WARN/ApplicationContext(6278): Unable to create files directory
06-02 13:23:54.203: WARN/System.err(6278): java.lang.NullPointerException
06-02 13:23:54.226: WARN/System.err(6278):     at android.app.ContextImpl.openFileOutput(ContextImpl.java:464)
06-02 13:23:54.234: WARN/ActivityManager(2470): Activity idle timeout for HistoryRecord{485ebe10 com.servision.svclient/.Main}
06-02 13:23:54.257: WARN/System.err(6278):     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
06-02 13:23:54.273: WARN/System.err(6278):     at com.servision.svclient.Main.onCreate(Main.java:59)
06-02 13:23:54.277: WARN/System.err(6278):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-02 13:23:54.285: WARN/System.err(6278):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-02 13:23:54.293: WARN/System.err(6278):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-02 13:23:54.296: WARN/System.err(6278):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-02 13:23:54.304: WARN/System.err(6278):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-02 13:23:54.312: WARN/System.err(6278):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 13:23:54.320: WARN/System.err(6278):     at android.os.Looper.loop(Looper.java:123)
06-02 13:23:54.324: WARN/System.err(6278):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-02 13:23:54.332: WARN/System.err(6278):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 13:23:54.336: WARN/System.err(6278):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 13:23:54.343: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
06-02 13:23:54.355: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-02 13:23:54.359: WARN/System.err(6278):     at dalvik.system.NativeStart.main(Native Method)
</code>```

in response.

I believe its something very simple in definitions of my project. But I can't figure out what it is.

If I create another project and put same code in to it, it works fine.

my manifest file looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.servision.svclient"
      android:versionCode="1"
      android:versionName="1.0">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

  <application android:icon="@drawable/main" android:label="@string/app_name" android:debuggable="true">
    <activity android:name=".Main" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name=".StreamActivity" android:label="@string/app_name"/>
    <activity android:name=".MainActivity"/>
    <activity android:name=".GatewayList"/>
    <activity android:name=".StatisticsActivity"/>
    <activity android:name=".SettingsActivity"/>
    <activity android:name=".MapsActivity"/>
    <activity android:name=".AboutActivity"/>
  </application>
  <uses-sdk android:minSdkVersion="8" />

</manifest>
</code>```

答:
Your FILENAME variable is wrong: what is the value of FILENAME?

That error occurs because an attempt to produce a file based off your FILENAME variable results in a null value inside openFileOutput. So FILENAME is not producing a valid file.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with permissions in my application. It looks like my app does not have permissions to create files on storage.

String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;

try
{
   fos = getApplicationContext()
           .openFileOutput(FILENAME, Context.MODE_PRIVATE);
   fos.write(string.getBytes());
   fos.close();
}
catch (Exception e)
{
   e.printStackTrace();
}

In my main class onCreate handler, and I always get:

06-02 13:23:52.996: WARN/ApplicationContext(6278): Unable to create files directory
06-02 13:23:54.203: WARN/System.err(6278): java.lang.NullPointerException
06-02 13:23:54.226: WARN/System.err(6278):     at android.app.ContextImpl.openFileOutput(ContextImpl.java:464)
06-02 13:23:54.234: WARN/ActivityManager(2470): Activity idle timeout for HistoryRecord{485ebe10 com.servision.svclient/.Main}
06-02 13:23:54.257: WARN/System.err(6278):     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
06-02 13:23:54.273: WARN/System.err(6278):     at com.servision.svclient.Main.onCreate(Main.java:59)
06-02 13:23:54.277: WARN/System.err(6278):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-02 13:23:54.285: WARN/System.err(6278):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-02 13:23:54.293: WARN/System.err(6278):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-02 13:23:54.296: WARN/System.err(6278):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-02 13:23:54.304: WARN/System.err(6278):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-02 13:23:54.312: WARN/System.err(6278):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 13:23:54.320: WARN/System.err(6278):     at android.os.Looper.loop(Looper.java:123)
06-02 13:23:54.324: WARN/System.err(6278):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-02 13:23:54.332: WARN/System.err(6278):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 13:23:54.336: WARN/System.err(6278):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 13:23:54.343: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
06-02 13:23:54.355: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-02 13:23:54.359: WARN/System.err(6278):     at dalvik.system.NativeStart.main(Native Method)

in response.

I believe its something very simple in definitions of my project. But I can't figure out what it is.

If I create another project and put same code in to it, it works fine.

my manifest file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.servision.svclient"
      android:versionCode="1"
      android:versionName="1.0">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

  <application android:icon="@drawable/main" android:label="@string/app_name" android:debuggable="true">
    <activity android:name=".Main" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name=".StreamActivity" android:label="@string/app_name"/>
    <activity android:name=".MainActivity"/>
    <activity android:name=".GatewayList"/>
    <activity android:name=".StatisticsActivity"/>
    <activity android:name=".SettingsActivity"/>
    <activity android:name=".MapsActivity"/>
    <activity android:name=".AboutActivity"/>
  </application>
  <uses-sdk android:minSdkVersion="8" />

</manifest>


问:
Instance pointers in an array
I'm trying to save pointers of class instances into a mutable array. I'm able to do this but getting them back into use seems to be a problem. The next is how I inserted the pointers into the array:

```<code>Class *class = [Class new];
/* Do something with the instance */

[instanceArray addObject:class];
</code>```

I am able to retrieve the wanted index from the array but when I try to access the instance variables etc. I only get compiler shouting at me or sometimes I get every variable as zero.

How am I supposed to get the instance back to use from the array? I know they are pointers but playing with them didn't seem to work.

答:
Using addObject: the element is inserted at the end of the array. To retrieve it you can use -[NSArray objectAtIndex:]

Pointer arithmetic works in C since then your array is just a pointer to the first index, and array[i] is the same as *(array + i). In Objective-C this may still be done, however you're using an NSArray object. Now you don't have a pointer to the first object anymore, but to the instance of the class. To retrieve the objects stored in the array, you'll have to call the corresponding methods.

EDIT
So you are able to retrieve it from the array and then your pointer is not nil, so you do have access to the object. You know in Objective-C, all instance variables are private so you can't access them from outside. You'd have to declare them as properties first (please refer to the documentation). Also, when you declare a variable to be of type id, accessing a property with dot-syntax doesn't work, it will cause a compiler error.

Title: Instance pointers in an array

Body:
I'm trying to save pointers of class instances into a mutable array. I'm able to do this but getting them back into use seems to be a problem. The next is how I inserted the pointers into the array:

Class *class = [Class new];
/* Do something with the instance */

[instanceArray addObject:class];

I am able to retrieve the wanted index from the array but when I try to access the instance variables etc. I only get compiler shouting at me or sometimes I get every variable as zero.

How am I supposed to get the instance back to use from the array? I know they are pointers but playing with them didn't seem to work.


问:
Cucumber cannot be resolved to a type
I created a RunTest class to run my test scenarios using Cucumber with JUnit. To run the tests before, I need to import into my project the RunWith class (@RunWith) and pass as parameter the Cucumber.class. Then, the RunWith parameter of the class recognizes more of the parameter that is passed to it, no.
The eclipse displays the message:

Multiple markers at this line
  - Class  can not be resolved to a type.
  - Cucumber can not be resolved to a type.
  - The annotation @RunWith must define the attribute value

I'm using Maven to organize my JARS files.
Following is the code and error screens.

My POM.XML

```<code>    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-core -->
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>1.2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-jvm -->
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm</artifactId>
        <version>1.2.5</version>
        <type>pom</type>
    </dependency>

</dependencies>
</code>```

My Libraries

答:
I have removed the  test  tag and it worked.</p>

```<code>      <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
        <dependency>
           <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
        </dependency>
</code>```

Title: Cucumber cannot be resolved to a type

Body:
I created a RunTest class to run my test scenarios using Cucumber with JUnit. To run the tests before, I need to import into my project the RunWith class (@RunWith) and pass as parameter the Cucumber.class. Then, the RunWith parameter of the class recognizes more of the parameter that is passed to it, no.
The eclipse displays the message:

Multiple markers at this line
  - Class  can not be resolved to a type.
  - Cucumber can not be resolved to a type.
  - The annotation @RunWith must define the attribute value

I'm using Maven to organize my JARS files.
Following is the code and error screens.

My POM.XML

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.5</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.5</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>1.2.5</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm</artifactId>
        <version>1.2.5</version>
        <type>pom</type>
    </dependency>

</dependencies>

My Libraries

Body:
I have removed the  test  tag and it worked.

      <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
        <dependency>
           <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.2.5</version>
        </dependency>


问:
Calcute mean for same time on different dates
I have data that shows a numeric amount of something measured at a few seconds after every minute of every day over a period of several days. Here is an example for two minutes on three days:

```<code>dat <- read.table(textConnection('
date_and_time amount
"2020-05-01 13:23:02" 8
"2020-05-01 13:24:06" 26
"2020-05-02 13:23:01" 5
"2020-05-02 13:24:01" 30
"2020-05-03 13:23:03" 6
"2020-05-03 13:24:02" 27
'), header = TRUE, colClasses=c("POSIXct", "numeric"))
</code>```

For that data, I want to calculate the mean amount for each minute over all days. For the above sample data, the result would look like this:

```<code>time_of_day mean_amount
13:23:00 6.333333
13:24:00 27.66667
</code>```

To get that result, I have converted the datetime objects to character strings, stripped the dates and the seconds from the strings, converted the strings to a factor, and calculated the means for each factor.

Is there a way to achieve that result with the datetime objects? That is, is there a function to calculate means over the same time of different dates?

答:
additional solution</p>

```<code>library(tidyverse)
library(lubridate)
library(hms)

dat %>%
  mutate(time = floor_date(x = date_and_time, unit = "min") %>% hms::as_hms()) %>%
  group_by(time) %>%
  summarise(mean_amount = mean(amount))
</code>```

Body:
I have data that shows a numeric amount of something measured at a few seconds after every minute of every day over a period of several days. Here is an example for two minutes on three days:

dat <- read.table(textConnection('
date_and_time amount
"2020-05-01 13:23:02" 8
"2020-05-01 13:24:06" 26
"2020-05-02 13:23:01" 5
"2020-05-02 13:24:01" 30
"2020-05-03 13:23:03" 6
"2020-05-03 13:24:02" 27
'), header = TRUE, colClasses=c("POSIXct", "numeric"))

For that data, I want to calculate the mean amount for each minute over all days. For the above sample data, the result would look like this:

time_of_day mean_amount
13:23:00 6.333333
13:24:00 27.66667

To get that result, I have converted the datetime objects to character strings, stripped the dates and the seconds from the strings, converted the strings to a factor, and calculated the means for each factor.

Is there a way to achieve that result with the datetime objects? That is, is there a function to calculate means over the same time of different dates?

Body:
additional solution

library(tidyverse)
library(lubridate)
library(hms)

dat %>%
  mutate(time = floor_date(x = date_and_time, unit = "min") %>% hms::as_hms()) %>%
  group_by(time) %>%
  summarise(mean_amount = mean(amount))


问:
Maven test resources are blank in target
I am working on a Maven project that has some test resources; these are specified inside <build> with the following:

```<code>            <testResource>
                <filtering>true</filtering>
                <directory>src/test/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.csv</include>
                    <include>**/*.zip</include>
                    <include>**/*.xls</include>
                    <include>**/*.xlsx</include>
                    <include>**/*.jpg</include>
                    <include>**/*.pdf</include>
                </includes>
            </testResource>
</code>```

When the tests are run all of the files that match these extensions are copied over form the src/test/resources into /target/test-classes to be used for the tests.

The problem is, the PDF files are copied over blank.  So, the file name is there; a valid PDF is in it's place, just completely blank.  There is no content, but it must have all of the necessary header information as it does open as a valid PDF file.

I can't understand where it is getting these blank files from.

Example

Original file -https://github.com/aembleton/files/blob/master/original.pdf

Blank - https://github.com/aembleton/files/blob/master/blank.pdf

What I've tried doing

mvn clean

Tried running tests on the command line and in IntelliJ

Tried copying the files to other sub directories and to the top of src/test/resources.  The files are copied over into their new places, but still blank.

Moved the PDFs to to src/main/resources.  The POM is set to include PDFs in this directory too for resources.  The PDFs are once again copied over blank, but to target/classes

Rebooted

Environment

Ubuntu 20.04 with 5.4.0-31 kernel

Ext4 file system

OpenJDK 1.8.0_252

Apache Maven 3.6.3

Does anyone have any ideas why this might be happening?

答:
Try doing something like this:

```<code><testResource>
    <filtering>true</filtering>
    <directory>src/test/resources</directory>
    <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
        <include>**/*.csv</include>
    </includes>
</testResource>
<testResource>
    <filtering>false</filtering>
    <directory>src/test/resources</directory>
    <includes>
        <include>**/*.pdf</include>
        <include>**/*.jpg</include>
        <include>**/*.zip</include>
        <include>**/*.xls</include>
        <include>**/*.xlsx</include>
    </includes>
</testResource>
</code>```

Explanation:

Filtering maybe be corrupting the PDF.
Filtering works by replacing specific string tokens with other values.
The solution would be to exclude the filtering from the PDF.

Body:
I am working on a Maven project that has some test resources; these are specified inside <build> with the following:

            <testResource>
                <filtering>true</filtering>
                <directory>src/test/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.csv</include>
                    <include>**/*.zip</include>
                    <include>**/*.xls</include>
                    <include>**/*.xlsx</include>
                    <include>**/*.jpg</include>
                    <include>**/*.pdf</include>
                </includes>
            </testResource>

When the tests are run all of the files that match these extensions are copied over form the src/test/resources into /target/test-classes to be used for the tests.

The problem is, the PDF files are copied over blank.  So, the file name is there; a valid PDF is in it's place, just completely blank.  There is no content, but it must have all of the necessary header information as it does open as a valid PDF file.

I can't understand where it is getting these blank files from.

Example

Original file -https://github.com/aembleton/files/blob/master/original.pdf

Blank - https://github.com/aembleton/files/blob/master/blank.pdf

What I've tried doing

mvn clean

Tried running tests on the command line and in IntelliJ

Tried copying the files to other sub directories and to the top of src/test/resources.  The files are copied over into their new places, but still blank.

Moved the PDFs to to src/main/resources.  The POM is set to include PDFs in this directory too for resources.  The PDFs are once again copied over blank, but to target/classes

Rebooted

Environment

Ubuntu 20.04 with 5.4.0-31 kernel

Ext4 file system

OpenJDK 1.8.0_252

Apache Maven 3.6.3

Does anyone have any ideas why this might be happening?

Body:
Try doing something like this:

<testResource>
    <filtering>true</filtering>
    <directory>src/test/resources</directory>
    <includes>
        <include>**/*.properties</include>
        <include>**/*.xml</include>
        <include>**/*.csv</include>
    </includes>
</testResource>
<testResource>
    <filtering>false</filtering>
    <directory>src/test/resources</directory>
    <includes>
        <include>**/*.pdf</include>
        <include>**/*.jpg</include>
        <include>**/*.zip</include>
        <include>**/*.xls</include>
        <include>**/*.xlsx</include>
    </includes>
</testResource>

Explanation:

Filtering maybe be corrupting the PDF.
Filtering works by replacing specific string tokens with other values.
The solution would be to exclude the filtering from the PDF.


问:
Using Multi Cast transformation for destinations with different columns
What is the use of Multicast Transformation Task ? With this task, is it possible to send to two destinations from a single source, while each destination has different columns ?</p>

答:
I assume that you are referring to Multicast Transformation inside the Data Flow task. If so, yes it is possible. The purpose of the transformation is to channel data from a single source to n number of Transformation tasks or Destinations.

If source has following columns

```<code>Source
Column 1
Column 2
Column 3
</code>```

and destinations have these columns.

```<code>Destination 1   Destination 2
Column 1        Column 2
Column 3
</code>```

Both destinations will be able to see Columns 1 - 3 that are available in Source. You have to map the columns accordingly in the respective destinations. Refer below example:

Example:

Screenshot #1 shows that Source has two columns Header and Value.

Screenshot #2 shows that Destination 1 has both columns Header and Value. They are mapped accordingly.

Screenshot #3 shows that Destination 2 has only column Header. It is mapped accordingly.

Screenshot #4 shows sample package execution.

Hope that helps.

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Body:
I assume that you are referring to Multicast Transformation inside the Data Flow task. If so, yes it is possible. The purpose of the transformation is to channel data from a single source to n number of Transformation tasks or Destinations.

If source has following columns

Source
Column 1
Column 2
Column 3

and destinations have these columns.

Destination 1   Destination 2
Column 1        Column 2
Column 3

Both destinations will be able to see Columns 1 - 3 that are available in Source. You have to map the columns accordingly in the respective destinations. Refer below example:

Example:

Screenshot #1 shows that Source has two columns Header and Value.

Screenshot #2 shows that Destination 1 has both columns Header and Value. They are mapped accordingly.

Screenshot #3 shows that Destination 2 has only column Header. It is mapped accordingly.

Screenshot #4 shows sample package execution.

Hope that helps.

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:


问:
How to avoid running out of memory reading a complex PDF via iText7?
I'm using iText7 and Java to read PDFs that are not very large (10-30MB), but they contain a massive number of objects, causing OutOfMemoryError problems when creating and using a PdfDocument. (The internal xref table and Map/Tree/Pdf[Dict/Array] objects are in the millions.)

For example, a single PDF might only be 33MB but it contains a single table with a million rows spanning 800 pages, and the bookkeeping inside of PdfDocument is blowing up to 400MB. Here's the sample code and heap dump:

```<code>public static void main(String[] args) throws Exception {

    // PDF file is 33MB on disk (one big table over 800 pages)
    File pdf = new File("big.pdf"); // Also tried InputStream

    PdfReader reader = new PdfReader(pdf); // 35MB heap

    PdfDocument document = new PdfDocument(reader); // 400MB+ heap

    // do stuff ... assuming we didn't get an OOM above
}
</code>```

We added more memory to the JVM, but we don't know how big/complex some of these PDFs might be, so a long-term solution is needed, ideally one that lets us read contents in pieces or in an event-like callback manner (like XML+STAX/SAX).

Is there a more efficient way to either stream the PDF or break it up into sub PdfDocuments given a file or InputStream? We want to locate and extract objects like forms, tables, tooltips, etc.

Update: I got in contact with the IText team and IText7 doesn't allow partial readings of PDFs. So there isn't much I can do in this case except add more RAM or pre-parse the PDF mysql and look for "too much data" (a lot of work). I also checked PDFBox and it suffers from the same problem.

答:
You can do the following for reading large files:</p>

```<code>RandomAccessSourceFactory rasf = new RandomAccessSourceFactory();

RandomAccessSource ras = rasf.createBestSource(file);

RandomAccessFileOrArray rafoa = new RandomAccessFileOrArray(ras);

PdfReader pdfReader = new PdfReader(rafoa, null);
</code>```

Body:
I'm using iText7 and Java to read PDFs that are not very large (10-30MB), but they contain a massive number of objects, causing OutOfMemoryError problems when creating and using a PdfDocument. (The internal xref table and Map/Tree/Pdf[Dict/Array] objects are in the millions.)

For example, a single PDF might only be 33MB but it contains a single table with a million rows spanning 800 pages, and the bookkeeping inside of PdfDocument is blowing up to 400MB. Here's the sample code and heap dump:

public static void main(String[] args) throws Exception {

    // PDF file is 33MB on disk (one big table over 800 pages)
    File pdf = new File("big.pdf"); // Also tried InputStream

    PdfReader reader = new PdfReader(pdf); // 35MB heap

    PdfDocument document = new PdfDocument(reader); // 400MB+ heap

    // do stuff ... assuming we didn't get an OOM above
}

We added more memory to the JVM, but we don't know how big/complex some of these PDFs might be, so a long-term solution is needed, ideally one that lets us read contents in pieces or in an event-like callback manner (like XML+STAX/SAX).

Is there a more efficient way to either stream the PDF or break it up into sub PdfDocuments given a file or InputStream? We want to locate and extract objects like forms, tables, tooltips, etc.

Update: I got in contact with the IText team and IText7 doesn't allow partial readings of PDFs. So there isn't much I can do in this case except add more RAM or pre-parse the PDF mysql and look for "too much data" (a lot of work). I also checked PDFBox and it suffers from the same problem.

Body:
You can do the following for reading large files:

RandomAccessSourceFactory rasf = new RandomAccessSourceFactory();

RandomAccessSource ras = rasf.createBestSource(file);

RandomAccessFileOrArray rafoa = new RandomAccessFileOrArray(ras);

PdfReader pdfReader = new PdfReader(rafoa, null);


问:
Faster way to sort the array by finding the position of the first non-zero element in each row
I have a matrix in which I would like to sort this matrix based on the position of the first non-zero element in each row. For example, I would like to rearrange A in to B.

```<code>import numpy as np

A = np.array([[0, 0, 8, 7, 8],
              [0, 2, 2, 8, 9],
              [0, 0, 0, 6, 10],
              [5, 4, 4, 8, 10]])

B = np.array([[5, 4, 4, 8, 10],
              [0, 2, 2, 8, 9],
              [0, 0, 8, 7, 8],
              [0, 0, 0, 6, 10]])
</code>```

To do so, I first find the position of the first non-zero element in each row: I first define the function position and then rearrange A based the permutation position(A).

```<code>def position(A):
    num_rows = A.shape[0]
    num_cols = A.shape[1]
    B = np.zeros(num_rows)
    # Access each row
    for i in range(num_rows):
      # Find the position of the first non-zero element
      for j in range(num_cols):
        if A[i, j] != 0:
          break
      B[i] = j
    return B

position(A)

array([2., 1., 3., 0.])
</code>```

My matrix is of very large dimension and the procedure is repeated several times. My function position contains loops that I think could be replaced with more optimized code.

I would like to ask for a faster way to achieve my goal. Thank you so much!

答:
Not sure if this is fast, but sure is short:

```<code>B = np.array(sorted(A, key=lambda x: tuple(x!=0), reverse=True))
</code>```

Output:

```<code>array([[ 5,  4,  4,  8, 10],
       [ 0,  2,  2,  8,  9],
       [ 0,  0,  8,  7,  8],
       [ 0,  0,  0,  6, 10]])
</code>```

Body:
I have a matrix in which I would like to sort this matrix based on the position of the first non-zero element in each row. For example, I would like to rearrange A in to B.

import numpy as np

A = np.array([[0, 0, 8, 7, 8],
              [0, 2, 2, 8, 9],
              [0, 0, 0, 6, 10],
              [5, 4, 4, 8, 10]])

B = np.array([[5, 4, 4, 8, 10],
              [0, 2, 2, 8, 9],
              [0, 0, 8, 7, 8],
              [0, 0, 0, 6, 10]])

To do so, I first find the position of the first non-zero element in each row: I first define the function position and then rearrange A based the permutation position(A).

def position(A):
    num_rows = A.shape[0]
    num_cols = A.shape[1]
    B = np.zeros(num_rows)
    # Access each row
    for i in range(num_rows):
      # Find the position of the first non-zero element
      for j in range(num_cols):
        if A[i, j] != 0:
          break
      B[i] = j
    return B

position(A)

array([2., 1., 3., 0.])

My matrix is of very large dimension and the procedure is repeated several times. My function position contains loops that I think could be replaced with more optimized code.

I would like to ask for a faster way to achieve my goal. Thank you so much!

Body:
Not sure if this is fast, but sure is short:

B = np.array(sorted(A, key=lambda x: tuple(x!=0), reverse=True))

Output:

array([[ 5,  4,  4,  8, 10],
       [ 0,  2,  2,  8,  9],
       [ 0,  0,  8,  7,  8],
       [ 0,  0,  0,  6, 10]])


问:
Convert from Caml.List function to Base module
I am a total beginner in OCaml.

I need to convert an function from Caml module to the Base module.

I thought I could do it by removing the Caml. but it is not working as there is an type error.

This is my code

```<code>type 'a t = Node of 'a list * ('a arc list) [@@deriving show] and 'a arc = char * 'a t [@@deriving show]

let rec size (t1 : 'a t)=
  let aux (n : int)(x : 'a arc) = n + size (snd x) in
    match t1 with
    | Node([], [])     -> 0
    | Node(_ :: _, []) -> 1
    | Node([], l)      -> Caml.List.fold_left aux 0 l
    | Node(_ :: _, l)  -> Caml.List.fold_left aux 1 l ;;
</code>```

and I got this error by removing the Caml.

```<code>File "sort.ml", line 47, characters 41-44:
47 |     | Node([], l)      -> List.fold_left aux 0 l
                                              ^^^
Error: This expression has type int -> 'a arc -> int
       but an expression was expected of type 'b list
</code>```

Any suggestions ?

答:
The Base library provides the List.fold function, which you shall use as a general iterator1. It has a type that differs from the type of List.fold_left from the OCaml standard library and that means it shall be used differently. Namely, it uses labels to pass arguments to the function and the order of the arguments differ also (to conform to the Janestreet coding conventions). In your case, to make it work, you need to use labels, when you call this function, e.g.,

```<code>let rec size (t1 : 'a t)=
  let aux (n : int)(x : 'a arc) = n + size (snd x) in
  match t1 with
  | Node([], [])     -> 0
  | Node(_ :: _, []) -> 1
  | Node([], l)      -> List.fold ~f:aux ~init:0 l
  | Node(_ :: _, l)  -> List.fold ~f:aux ~init:1 l ;;
</code>```

1) You can use List.fold_left as an alias to List.fold but it is not recommended and the only difference is the name, the type is still the same.

Body:
I am a total beginner in OCaml.

I need to convert an function from Caml module to the Base module.

I thought I could do it by removing the Caml. but it is not working as there is an type error.

This is my code

type 'a t = Node of 'a list * ('a arc list) [@@deriving show] and 'a arc = char * 'a t [@@deriving show]

let rec size (t1 : 'a t)=
  let aux (n : int)(x : 'a arc) = n + size (snd x) in
    match t1 with
    | Node([], [])     -> 0
    | Node(_ :: _, []) -> 1
    | Node([], l)      -> Caml.List.fold_left aux 0 l
    | Node(_ :: _, l)  -> Caml.List.fold_left aux 1 l ;;

and I got this error by removing the Caml.

File "sort.ml", line 47, characters 41-44:
47 |     | Node([], l)      -> List.fold_left aux 0 l
                                              ^^^
Error: This expression has type int -> 'a arc -> int
       but an expression was expected of type 'b list

Any suggestions ?

Body:
The Base library provides the List.fold function, which you shall use as a general iterator1. It has a type that differs from the type of List.fold_left from the OCaml standard library and that means it shall be used differently. Namely, it uses labels to pass arguments to the function and the order of the arguments differ also (to conform to the Janestreet coding conventions). In your case, to make it work, you need to use labels, when you call this function, e.g.,

let rec size (t1 : 'a t)=
  let aux (n : int)(x : 'a arc) = n + size (snd x) in
  match t1 with
  | Node([], [])     -> 0
  | Node(_ :: _, []) -> 1
  | Node([], l)      -> List.fold ~f:aux ~init:0 l
  | Node(_ :: _, l)  -> List.fold ~f:aux ~init:1 l ;;

1) You can use List.fold_left as an alias to List.fold but it is not recommended and the only difference is the name, the type is still the same.


问:
Inserver distance calculation and Combining Neo4j queries
I have two queries which needs to be executed simultaneously on the neo4j server.
The first query needs to calculate the distance.
The Second Query needs to send the informations+ calculated distance in the JSON response
Pls suggest me How i could combine the  mentioned queries in Neo4j  ?

QUERY1:

=======

```<code>WITH point({ longitude:76.91859, latitude:8.487992, height: 100 }) AS p1, point({ latitude:8.495548 , longitude:76.93015, height: 100 }) AS p2 RETURN distance(p1,p2) AS dist
</code>```

QUERY2:

```<code>  MATCH (qperson:QuarantinedPersons)
    WHERE qperson.name = 'Raman'
    CREATE (thereturnrecord:theDetails{theid: qperson.id,thename:
    qperson.Name,thedetails:qperson.details,thelat:qperson.lat,thelong:qperson.long,thedistance:2000})
   RETURN thereturnrecord
</code>```

Expected Output,similar to:

```<code> [
      {
        "thereturnrecord": {
         "identity": 3,
         "labels": [
            "theDetails"
          ],
          "properties": {
        "thelong": "76.91859",
        "thelat": "8.487992",
        "thedetails": "XYZ",
        "thedistance": 2000(Obtained from the query),
        "theid": "1"
      }
    }
  }
</code>```

答:
[UPDATED]

Here is a combined query:

```<code>WITH
  point({ longitude:76.91859, latitude:8.487992, height: 100 }) AS p1,
  point({ latitude:8.495548 , longitude:76.93015, height: 100 }) AS p2
MATCH (q:QuarantinedPersons)
WHERE q.name = 'Raman'
CREATE (thereturnrecord:theDetails{
  theid: q.id,
  thename: q.Name,
  thedetails: q.details,
  thelat: q.lat,
  thelong: q.long,
  thedistance: distance(p1, p2)
})
RETURN thereturnrecord
</code>```

Of, if the arguments for the 2 points are passed as the parameters p1 and p2:

```<code>MATCH (q:QuarantinedPersons)
WHERE q.name = 'Raman'
CREATE (thereturnrecord:theDetails{
  theid: q.id,
  thename: q.Name,
  thedetails: q.details,
  thelat: q.lat,
  thelong: q.long,
  thedistance: distance(point($p1), point($p2))
})
RETURN thereturnrecord
</code>```

Body:
I have two queries which needs to be executed simultaneously on the neo4j server.
The first query needs to calculate the distance.
The Second Query needs to send the informations+ calculated distance in the JSON response
Pls suggest me How i could combine the  mentioned queries in Neo4j  ?

QUERY1:

=======

WITH point({ longitude:76.91859, latitude:8.487992, height: 100 }) AS p1, point({ latitude:8.495548 , longitude:76.93015, height: 100 }) AS p2 RETURN distance(p1,p2) AS dist

QUERY2:

  MATCH (qperson:QuarantinedPersons)
    WHERE qperson.name = 'Raman'
    CREATE (thereturnrecord:theDetails{theid: qperson.id,thename:
    qperson.Name,thedetails:qperson.details,thelat:qperson.lat,thelong:qperson.long,thedistance:2000})
   RETURN thereturnrecord

Expected Output,similar to:

 [
      {
        "thereturnrecord": {
         "identity": 3,
         "labels": [
            "theDetails"
          ],
          "properties": {
        "thelong": "76.91859",
        "thelat": "8.487992",
        "thedetails": "XYZ",
        "thedistance": 2000(Obtained from the query),
        "theid": "1"
      }
    }
  }

Body:
[UPDATED]

Here is a combined query:

WITH
  point({ longitude:76.91859, latitude:8.487992, height: 100 }) AS p1,
  point({ latitude:8.495548 , longitude:76.93015, height: 100 }) AS p2
MATCH (q:QuarantinedPersons)
WHERE q.name = 'Raman'
CREATE (thereturnrecord:theDetails{
  theid: q.id,
  thename: q.Name,
  thedetails: q.details,
  thelat: q.lat,
  thelong: q.long,
  thedistance: distance(p1, p2)
})
RETURN thereturnrecord

Of, if the arguments for the 2 points are passed as the parameters p1 and p2:

MATCH (q:QuarantinedPersons)
WHERE q.name = 'Raman'
CREATE (thereturnrecord:theDetails{
  theid: q.id,
  thename: q.Name,
  thedetails: q.details,
  thelat: q.lat,
  thelong: q.long,
  thedistance: distance(point($p1), point($p2))
})
RETURN thereturnrecord


问:
PostgreSQL table inheritance and moving rows with SQLAlchemy
In my app (python, postgres, sqlalchemy) I had one large table tasks. The app mostly works with recent 1k rows in tasks, frequently selecting and updating rows. Such frequent operations were too slow due to size of tasks so I decided to split this table into two tasks tasks_all, where table tasks are inheried from tasks_all (postgresql feature).

Thus the app can work with a small table very fast and when it to do something to old data, it can work with the large table, that includes all rows from self and from it's successor.

Here is simplified classes for my tables:

```<code>class TaskBase:
    def __init__(self, id, parent_id, data):
        self.id = id
        self.parent_id = parent_id
        self.data = data

    def __repr__(self):
        return '<Task: {} {}>'.format(self.id, self.data)

class Task(TaskBase, Base):
    __tablename__ = 'tasks'

    id = Column(INT, primary_key=True)
    parent_id = Column(INT, ForeignKey('tasks.id'))
    data = Column(TEXT)

    children = relationship("Task", backref=backref('parent', remote_side=[id]))

class TaskAll(TaskBase, Base):
    __tablename__ = 'tasks_all'

    id = Column(INT, primary_key=True)
    parent_id = Column(INT, ForeignKey('tasks_all.id'))
    data = Column(TEXT)

    children = relationship("TaskAll", backref=backref('parent', remote_side=[id]))
</code>```

To keep tasks table small, I need time to time move rows from tasks to tasks_all. And sometimes I will need to move them back. The following code is how I tried to implement moving.

```<code>def move_group(ids):
    query = session.query(TaskAll).filter(TaskAll.id in ids)
    db_session.s.execute(insert(Task).from_select((
        TaskAll.id,
        TaskAll.parent_id,
        TaskAll.data,
    ), query))
    print("insert from select is successful")
    query.delete()
    print("delete is successful")
</code>```

But this doesn't work because as table tasks_all is parent to tasks, delete from tasks_all also deletes from tasks. Resulting SQL query is:

```<code>DELETE FROM tasks_all WHERE tasks_all.id IN (...);
</code>```

But to perform the operation I need, the query shuld be

```<code>DELETE FROM ONLY tasks_all WHERE tasks_all.id IN (...);
</code>```

As far as I could find SQLAlchemy knows nothing about ONLY. Do I have to use raw SQL queries from sqla skipping ORM part, or maybe there is a better solution to move rows from one table to another?

答:
I found that SQLAlchemy has a hint mechanism that would help when doing operations in a table that was inherited.

```<code>def move_group(ids):
    query = session.query(TaskAll).filter(TaskAll.id in ids)
    db_session.s.execute(insert(Task).from_select((
        TaskAll.id,
        TaskAll.parent_id,
        TaskAll.data,
    ), query))
    print("insert from select is successful")
    query.delete().with_hint('ONLY', dialect_name='postgresql')
    print("delete is successful")
</code>```

I know that the question was made some years ago, but I hope that it could still help someone.

Body:
In my app (python, postgres, sqlalchemy) I had one large table tasks. The app mostly works with recent 1k rows in tasks, frequently selecting and updating rows. Such frequent operations were too slow due to size of tasks so I decided to split this table into two tasks tasks_all, where table tasks are inheried from tasks_all (postgresql feature).

Thus the app can work with a small table very fast and when it to do something to old data, it can work with the large table, that includes all rows from self and from it's successor.

Here is simplified classes for my tables:

class TaskBase:
    def __init__(self, id, parent_id, data):
        self.id = id
        self.parent_id = parent_id
        self.data = data

    def __repr__(self):
        return '<Task: {} {}>'.format(self.id, self.data)

class Task(TaskBase, Base):
    __tablename__ = 'tasks'

    id = Column(INT, primary_key=True)
    parent_id = Column(INT, ForeignKey('tasks.id'))
    data = Column(TEXT)

    children = relationship("Task", backref=backref('parent', remote_side=[id]))

class TaskAll(TaskBase, Base):
    __tablename__ = 'tasks_all'

    id = Column(INT, primary_key=True)
    parent_id = Column(INT, ForeignKey('tasks_all.id'))
    data = Column(TEXT)

    children = relationship("TaskAll", backref=backref('parent', remote_side=[id]))

To keep tasks table small, I need time to time move rows from tasks to tasks_all. And sometimes I will need to move them back. The following code is how I tried to implement moving.

def move_group(ids):
    query = session.query(TaskAll).filter(TaskAll.id in ids)
    db_session.s.execute(insert(Task).from_select((
        TaskAll.id,
        TaskAll.parent_id,
        TaskAll.data,
    ), query))
    print("insert from select is successful")
    query.delete()
    print("delete is successful")

But this doesn't work because as table tasks_all is parent to tasks, delete from tasks_all also deletes from tasks. Resulting SQL query is:

DELETE FROM tasks_all WHERE tasks_all.id IN (...);

But to perform the operation I need, the query shuld be

DELETE FROM ONLY tasks_all WHERE tasks_all.id IN (...);

As far as I could find SQLAlchemy knows nothing about ONLY. Do I have to use raw SQL queries from sqla skipping ORM part, or maybe there is a better solution to move rows from one table to another?

Body:
I found that SQLAlchemy has a hint mechanism that would help when doing operations in a table that was inherited.

def move_group(ids):
    query = session.query(TaskAll).filter(TaskAll.id in ids)
    db_session.s.execute(insert(Task).from_select((
        TaskAll.id,
        TaskAll.parent_id,
        TaskAll.data,
    ), query))
    print("insert from select is successful")
    query.delete().with_hint('ONLY', dialect_name='postgresql')
    print("delete is successful")

I know that the question was made some years ago, but I hope that it could still help someone.


问:
java reflection issue
I have this code:

```<code>public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }
</code>```

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

```<code>for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }
</code>```

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

答:
I am not sure if i got ur question right, but what i feel  u are asking wud be answered by following code:

```<code>// Class is whatever is the type u r using
Method mthd = Class.getMethod("get" + fieldName); //in case method don't have any parameters.
listSelectBox.add(mthd.invoke(currVo));
</code>```

otherwise ignore.

Title: java reflection issue

Body:
I have this code:

public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
            final Class<TypeVO> voClass, final String fieldName) {
        List<SelectItem> listSelectBox = null;
        final List<TypeVO> vosList = GenericEjbProxyFactory
                .getGenericTopValueObjectProxy(voClass)
                .getAllValueObjects(null);
        System.out.println("loaded vosList!!!!");
        if (vosList != null) {
            listSelectBox = new ArrayList<SelectItem>();
            for (final TypeVO currVo : vosList) {
                listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName()));
            }
        }
        return listSelectBox;
    }

As you see here, I'm using currVo.getName because always, currVo has a name property.

I want to be able to use also other fields from this currVo which has type as voClass, but not all currVo classes will contain this field so I have to use reflection to identify these getField method, something like:

for (final TypeVO currVo : vosList) {
                for (final Method m : voClass.getMethods()) {
                    if (m.getName().contains(fieldName)) {
                        listSelectBox.add(new SelectItem(
                                currVo.getInternalId(), currVo.m));
                    }
                }
            }

What I do not know is HOW I can use that specific method's value when I find it, exactly like currVo.getName (because, of course, currVo.m is wrong)?

Eg: If fieldName is "Age" I want to put in the list: currVo.getAge()... I am simply blocked here...

Body:
I am not sure if i got ur question right, but what i feel  u are asking wud be answered by following code:

// Class is whatever is the type u r using
Method mthd = Class.getMethod("get" + fieldName); //in case method don't have any parameters.
listSelectBox.add(mthd.invoke(currVo));

otherwise ignore.


问:
How to get active users from last X mins in Django
I have a website created in Django, How can I get a list of active users from last X mins. I want all not-logged in as well as logged-in users.</p>

答:
You should use Django Cache Framework plus using middlewares that you can find them here:
Django Cache Framework ,
Middlewares
and make a Online User Catcher for every time you want. that was the technical way to implement by yourself

and also the easy way - using third party packages :

django-online-users :
Github link

it's very easy and i'm using it too.


问:
React Hooks, Conditionally change state inside onClick function, updates on the next click
Hello I have a single list component which render some <Card> components that has a prop isSelected . Because alot of things happens when a <Card> Component has isSelected === true I added the state on the <List> component, and I want when someone clicks a card to check:

1) If there are no previously selected items ( state===null to add that item's id to state )

2) If someone clicks the same item or another item while there is already an item selected in state, to just unselected the active item.

```<code>import {Card} from "./Card";
import cloneDeep from 'lodash/cloneDeep';

const List = () => {
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.debug(selectedCard, id)
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if (newSelectedCard !== null || newSelectedCard === id) {
            setSelectedCard(null)
        } else {
            setSelectedCard(id)
        }
        console.debug(selectedCard, id)
    }

    return (
        <ul className="card-list">
            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}
        </ul>
    )
}

export const CardList = () => (
    <List/>
);
</code>```

The issue is that the 2 console.debugs print the same values which means that the state doesnt update imediately and Im experiencing some strange behaviours here and there. Am I missing something here?

答:
Basically you need to follow 3 condition as below

```<code>if(newSelectedCard === null){
        setSelectedCard(id)
    }
    else if(newSelectedCard === id){
        setSelectedCard(null);
    }
    else{
        setSelectedCard(id)
    }
</code>```

Here is the Complete example:

```<code>import cloneDeep from 'lodash/cloneDeep';
import React, {useState} from "react";

const List = () => {
    const [cardData, setCardData] = useState([
        {id: 1, title: 'First Card'},
        {id: 2, title: 'Second Card'},
        {id: 3, title: 'Third Card'},
        {id: 4, title: 'Fourth Card'},
    ]);
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.log(selectedCard, id);
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if(newSelectedCard === null){
            setSelectedCard(id)
        }
        else if(newSelectedCard === id){
            setSelectedCard(null);
        }
        else{
            setSelectedCard(id)
        }
        console.log(selectedCard, id)
    };

    return (
        <ul className="card-list">
            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}
        </ul>
    )
};

export const CardList = () => (
    <List/>
);

const Card = (props) => {
    const backColor = props.isSelected? '#F9740E' : '#3FB566';
    return (
        <div onClick={() => props.onClick()}>
            <div style={{backgroundColor: backColor, border: '1px solid darkgreen', color: 'white', padding: 10, marginBottom: 10}}>
                <h3>{props.id}</h3>
                <h4>{props.title}</h4>
            </div>
        </div>
    );
};
</code>```

Update
Here is Code SandBox

Body:
Hello I have a single list component which render some <Card> components that has a prop isSelected . Because alot of things happens when a <Card> Component has isSelected === true I added the state on the <List> component, and I want when someone clicks a card to check:

1) If there are no previously selected items ( state===null to add that item's id to state )

2) If someone clicks the same item or another item while there is already an item selected in state, to just unselected the active item.

import {Card} from "./Card";
import cloneDeep from 'lodash/cloneDeep';

const List = () => {
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.debug(selectedCard, id)
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if (newSelectedCard !== null || newSelectedCard === id) {
            setSelectedCard(null)
        } else {
            setSelectedCard(id)
        }
        console.debug(selectedCard, id)
    }

    return (

            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}

    )
}

export const CardList = () => (
    <List/>
);

The issue is that the 2 console.debugs print the same values which means that the state doesnt update imediately and Im experiencing some strange behaviours here and there. Am I missing something here?

Body:
Basically you need to follow 3 condition as below

if(newSelectedCard === null){
        setSelectedCard(id)
    }
    else if(newSelectedCard === id){
        setSelectedCard(null);
    }
    else{
        setSelectedCard(id)
    }

Here is the Complete example:

import cloneDeep from 'lodash/cloneDeep';
import React, {useState} from "react";

const List = () => {
    const [cardData, setCardData] = useState([
        {id: 1, title: 'First Card'},
        {id: 2, title: 'Second Card'},
        {id: 3, title: 'Third Card'},
        {id: 4, title: 'Fourth Card'},
    ]);
    const [selectedCard, setSelectedCard] = useState(null);

    const onCardClick = id => {
        console.log(selectedCard, id);
        const newSelectedCard = cloneDeep(selectedCard);
        // if he clicks another item while an item is active
        // or if he clicks the same item while active
        // should just make it inactive
        if(newSelectedCard === null){
            setSelectedCard(id)
        }
        else if(newSelectedCard === id){
            setSelectedCard(null);
        }
        else{
            setSelectedCard(id)
        }
        console.log(selectedCard, id)
    };

    return (
        <ul className="card-list">
            {cardData.map(card => (
                <Card
                    onClick={() => onCardClick(card.id)}
                    key={card.id}
                    isSelected={selectedCard === card.id}
                    {...card}
                />
            ))}
        </ul>
    )
};

export const CardList = () => (
    <List/>
);

const Card = (props) => {
    const backColor = props.isSelected? '#F9740E' : '#3FB566';
    return (
        <div onClick={() => props.onClick()}>
            <div style={{backgroundColor: backColor, border: '1px solid darkgreen', color: 'white', padding: 10, marginBottom: 10}}>
                <h3>{props.id}</h3>
                <h4>{props.title}</h4>
            </div>
        </div>
    );
};

Update
Here is Code SandBox


问:
TypeError: a bytes-like object is required, not 'str' in geolite2 function in python
I have a program that displays the country belongs to the Ip address.Its working fine in version python 2.7.The problem is when i try the same program in version python 3.5 ,it throws an error as mentioned below:

Code:

```<code>from geoip import geolite2

m = geolite2.lookup('17.0.0.1')
</code>```

Error:

```<code>TypeError: a bytes-like object is required, not 'str'
</code>```

How can i resolve the error?

Thanks in advance

答:
The answer above was correct to install the right package for Python3. To force installation for Python3 use:

python3 -m pip install python-geoip-python3

However, to benefit from the full functionality of geoip you may also consider downloading additionally geolite2 that also ships the IP database with it:

python3 -m pip install python-geoip-geolite2

To check if it works for you:

run python3 in interactive mode

run following:

```<code>>>> from geoip import geolite2
>>> geolite2.lookup('8.8.8.8')
</code>```

You should get something like this

```<code><IPInfo ip='8.8.8.8' country='US' continent='NA' subdivisions=frozenset({'CA'}) ...
</code>```

Body:
I have a program that displays the country belongs to the Ip address.Its working fine in version python 2.7.The problem is when i try the same program in version python 3.5 ,it throws an error as mentioned below:

Code:

from geoip import geolite2

m = geolite2.lookup('17.0.0.1')

Error:

TypeError: a bytes-like object is required, not 'str'

How can i resolve the error?

Thanks in advance

Body:
The answer above was correct to install the right package for Python3. To force installation for Python3 use:

python3 -m pip install python-geoip-python3

However, to benefit from the full functionality of geoip you may also consider downloading additionally geolite2 that also ships the IP database with it:

python3 -m pip install python-geoip-geolite2

To check if it works for you:

run python3 in interactive mode

run following:

>>> from geoip import geolite2
>>> geolite2.lookup('8.8.8.8')

You should get something like this

<IPInfo ip='8.8.8.8' country='US' continent='NA' subdivisions=frozenset({'CA'}) ...


问:
Conversion from signed int to signed char?
I'm following an example from Stroustrups C_++ 4th Ed. Page 143, where there is Errata.  -160, should be -140.

Specifically the conversion of a signed int to a signed char.

```<code>#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    signed char sc = -140;
    cout << "signed int = " <<
    int((signed int) (0b11111111111111111111111101110100))
          << endl; // -140, 4 bytes
    cout << "signed int & 0xFF = " << int((signed int) -140 & 0xFF)
          << endl; // 116, narrow 2 bytes
    unsigned char uc = sc; // 256 - 140 = 116
    return 0;
}
</code>```

I understand how the conversion is a narrowing of 4 bytes, to 2 bytes which result in -140 being converted to 116.  I am confused on the comment Stroustrup adds for the line unsigned char uc = sc where it is // 256 - 140 = 116.  I see it results in the correct answer 116, but am unsure how that conversion is done.  I'm aware that an unsigned char max limit completely full of 1's is 255 or 2^8 - 1.  Does anyone know why this math in the comment works?

UPDATE:
The solution is -140 mod 256 = 116.

Thanks

答:
Two byte int hasn't been common for a long time now; most int are 4 bytes.

Regardless, it's the top bit that matters for a signed number.  The expression -140 & 0xff results in 0b01110100  which is 116, because all those sign bits get chopped off.

To make it even simpler, let's look at the full bit patterns.

```<code>-140 = 0b11111111111111111111111101110100 (first sign bit is set)
0xff = 0b00000000000000000000000011111111 (bottom 8 bits set, all others zero)
&    : 0b00000000000000000000000001110100 = 116
</code>```

Body:
I'm following an example from Stroustrups C_++ 4th Ed. Page 143, where there is Errata.  -160, should be -140.

Specifically the conversion of a signed int to a signed char.

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    signed char sc = -140;
    cout << "signed int = " <<
    int((signed int) (0b11111111111111111111111101110100))
          << endl; // -140, 4 bytes
    cout << "signed int & 0xFF = " << int((signed int) -140 & 0xFF)
          << endl; // 116, narrow 2 bytes
    unsigned char uc = sc; // 256 - 140 = 116
    return 0;
}

I understand how the conversion is a narrowing of 4 bytes, to 2 bytes which result in -140 being converted to 116.  I am confused on the comment Stroustrup adds for the line unsigned char uc = sc where it is // 256 - 140 = 116.  I see it results in the correct answer 116, but am unsure how that conversion is done.  I'm aware that an unsigned char max limit completely full of 1's is 255 or 2^8 - 1.  Does anyone know why this math in the comment works?

UPDATE:
The solution is -140 mod 256 = 116.

Thanks

Body:
Two byte int hasn't been common for a long time now; most int are 4 bytes.

Regardless, it's the top bit that matters for a signed number.  The expression -140 & 0xff results in 0b01110100  which is 116, because all those sign bits get chopped off.

To make it even simpler, let's look at the full bit patterns.

-140 = 0b11111111111111111111111101110100 (first sign bit is set)
0xff = 0b00000000000000000000000011111111 (bottom 8 bits set, all others zero)
&    : 0b00000000000000000000000001110100 = 116


问:
Remove duplicate keys and combine unique values in JavaScript array
I have an array containing a customer ID, value of transaction, and transaction ID for each transaction performed by the customer.

I have 20,000 transactions performed by 9,000 customers.
I want one customer ID, an array of all the prices per that customer ID, and an array of all the transaction Ids per customer ID.

Currently looks like this:

```<code>var transactionArray =
{
  customerId: '1',
  price: [ 100 ],
  transactionID: ['00a13']
},
{
  customerId: '2',
  price: [ 200 ],
  transactionID: ['00a14']
},
{
  customerId: '1',
  price: [ 700 ],
  transactionID: ['00a15']
},
{
  customerId: '2',
  price: [ 1700 ],
  transactionID: ['00a16']
},

... 19996 more items
</code>```

and I'd like it to look like this:

```<code>var customerArray =

{
  customerId: '1',
  price: [ 100, 700 ],
  transactionID: ['00a13', '00a15']
},
{
  customerId: '2',
  price: [ 200, 1700 ],
  transactionID: ['00a14', '00a16']
},

...8998 more items
</code>```

答:
It's convenient that customerId's are integers. If that ever changes, then you will need to index them, then rebuild the object.

// create a separate array for holding order of customerIds
const customerIds = []

const result = transactionArray
  .reduce((acc, { customerId, price, transactionID }) => {
    const idIndex = customerIds.indexOf(customerId)
    // check if customerId exists in customerIds array
    if (idIndex < 0) {
      // if it doesn't, add it to the customerId's array
      customerIds.push(customerId)
      // then add the matching price and transactionID to the accumulator
      // of this reduce, spreading the contents of the array into 2 new arrays.
      acc.push([[...price], [...transactionID]])
    } else {
      // if the customerId is already accounted for, then
      // add the price and transactionID to that customer's bucket
      // at the same index where the customerId exists inside customerIds
      acc[idIndex][0].push(...price)
      acc[idIndex][1].push(...transactionID)
    }
    return acc
  }, [])
  // finally, convert the arrays back into objects
  .map((value, index) => {
    return ({
      customerId: customerIds[index],
      price: value[0],
      transactionID: value[1],
    })
  })

console.log(result)
```

<p>which logs:</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    customerId: '1',
    price: [ 100, 700 ],
    transactionID: [ '00a13', '00a15' ]
  },
  {
    customerId: '2',
    price: [ 200, 1700 ],
    transactionID: [ '00a14', '00a16' ]
  }
]
</code>```

If the customerIds were strings that didn't represent integers, this will still work -- for example, if your customer data looked like this:

const transactionArray = [
  {
    customerId: '324asdrea',
    price: [ 100 ],
    transactionID: ['00a13']
  },
  {
    customerId: '4hdffgi2',
    price: [ 200 ],
    transactionID: ['00a14']
  },
  {
    customerId: '324asdrea',
    price: [ 700 ],
    transactionID: ['00a15']
  },
  {
    customerId: '4hdffgi2',
    price: [ 1700 ],
    transactionID: ['00a16']
  }
]
```

<p>which results in:</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    customerId: '324asdrea',
    price: [ 100, 700 ],
    transactionID: [ '00a13', '00a15' ]
  },
  {
    customerId: '4hdffgi2',
    price: [ 200, 1700 ],
    transactionID: [ '00a14', '00a16' ]
  }
]
</code>```

Body:
I have an array containing a customer ID, value of transaction, and transaction ID for each transaction performed by the customer.

I have 20,000 transactions performed by 9,000 customers.
I want one customer ID, an array of all the prices per that customer ID, and an array of all the transaction Ids per customer ID.

Currently looks like this:

var transactionArray =
{
  customerId: '1',
  price: [ 100 ],
  transactionID: ['00a13']
},
{
  customerId: '2',
  price: [ 200 ],
  transactionID: ['00a14']
},
{
  customerId: '1',
  price: [ 700 ],
  transactionID: ['00a15']
},
{
  customerId: '2',
  price: [ 1700 ],
  transactionID: ['00a16']
},

... 19996 more items

and I'd like it to look like this:

var customerArray =

{
  customerId: '1',
  price: [ 100, 700 ],
  transactionID: ['00a13', '00a15']
},
{
  customerId: '2',
  price: [ 200, 1700 ],
  transactionID: ['00a14', '00a16']
},

...8998 more items

Body:
It's convenient that customerId's are integers. If that ever changes, then you will need to index them, then rebuild the object.

// create a separate array for holding order of customerIds
const customerIds = []

const result = transactionArray
  .reduce((acc, { customerId, price, transactionID }) => {
    const idIndex = customerIds.indexOf(customerId)
    // check if customerId exists in customerIds array
    if (idIndex < 0) {
      // if it doesn't, add it to the customerId's array
      customerIds.push(customerId)
      // then add the matching price and transactionID to the accumulator
      // of this reduce, spreading the contents of the array into 2 new arrays.
      acc.push([[...price], [...transactionID]])
    } else {
      // if the customerId is already accounted for, then
      // add the price and transactionID to that customer's bucket
      // at the same index where the customerId exists inside customerIds
      acc[idIndex][0].push(...price)
      acc[idIndex][1].push(...transactionID)
    }
    return acc
  }, [])
  // finally, convert the arrays back into objects
  .map((value, index) => {
    return ({
      customerId: customerIds[index],
      price: value[0],
      transactionID: value[1],
    })
  })

console.log(result)

which logs:

[
  {
    customerId: '1',
    price: [ 100, 700 ],
    transactionID: [ '00a13', '00a15' ]
  },
  {
    customerId: '2',
    price: [ 200, 1700 ],
    transactionID: [ '00a14', '00a16' ]
  }
]

If the customerIds were strings that didn't represent integers, this will still work -- for example, if your customer data looked like this:

const transactionArray = [
  {
    customerId: '324asdrea',
    price: [ 100 ],
    transactionID: ['00a13']
  },
  {
    customerId: '4hdffgi2',
    price: [ 200 ],
    transactionID: ['00a14']
  },
  {
    customerId: '324asdrea',
    price: [ 700 ],
    transactionID: ['00a15']
  },
  {
    customerId: '4hdffgi2',
    price: [ 1700 ],
    transactionID: ['00a16']
  }
]

which results in:

[
  {
    customerId: '324asdrea',
    price: [ 100, 700 ],
    transactionID: [ '00a13', '00a15' ]
  },
  {
    customerId: '4hdffgi2',
    price: [ 200, 1700 ],
    transactionID: [ '00a14', '00a16' ]
  }
]


问:
SQL Server is not importing all my data from a csv file
I begin by saying that I have installed SQL Server Express Advance 2014. I want to import data to SQL Server from a csv file. To do this, I select a database, select Tasks, select Import Data. Then, for the Data Source I select Flat File. For the destination I choose SQL Server Native Client 11.0. For the destination table I choose the one that is autogenerated by SQL Server Import and Export Wizard, i.e., I have not created the table prior to the importation of the data, it is created while I'm in this window. The import of data finishes with a message that says that the rows has been transferred: 43 157 rows have been transferred (the total number of rows in my csv file).

In a query, when I write 'select all from this table', in the Results, I effectively see a table that contains 43 157 rows. However, not all my data has been copied. I realized this because I compared the firsts and the lasts rows of my csv file with that of the table that appeared in the section of Results. There is no problem with the first rows, at least with the the first 100 rows. But the last row, the 43 157th row that appear in the table of SQL is the 40 475th row in the csv file. So, this table in SQL has the same number of rows that that of the origin source, it does not contain all the data, though.

I repeated this process of import data, to see whether, in another new table (also autogenerated) this time all the data would be copy. It didn't happen, but in this table appeared 826 rows more than in the previos one. I mean, the 43157th row in the SQL table now coincided with the 41 301th row in the csv file. I repeated the process and again it appeared 826 rows more than in the previous table. I had a pattern!, I thougth. So I continued in this way until all the data had been copied. In effect, in the nth attempt, the last row in the nth table in SQL coincided with the last row in the csv file. But until this point, I had  entirely focus my attention of what happen in the lasts rows, and what I had not noticed is that now my firsts rows were wrong! For example, the first row in my last table in SQL, was the 2479th row in my csv file. What's going on here?

As you can notice, I'm very new in SQL Server, so I hope the explanations would not be very aggressive for a beginner. Thanks in advance.

答:
I think you are relying too heavily on the following assumptions:

That SQL Server will insert rows exactly as they ordered in the CSV file

That SQL Server will return rows in the order they were inserted

In general, a table is an unordered bag of rows, and you should always think about it that way, regardless of how you populated those rows. Instead of trying to match "first" and "last" rows of a source file to the destination table, match on the actual data in those rows. If the last row in your CSV file contains an e-mail address foo@bar.com, don't check that foo@bar.com is in the "last" row resulting from SELECT * FROM dbo.table;, check that there exists a row where the e-mail address is foo@bar.com. That it isn't the "last" row in the table doesn't mean there is a problem.

Unless you can reliably ORDER BY something in the table that happens to match the order of data in the input file. But even then you should be matching on the data, not ordinal position.


问:
Import MySQL dump to PostgreSQL database
How can I import an "xxxx.sql" dump from MySQL to a PostgreSQL database?</p>

答: If you are using phpmyadmin you can export your data as CSV and then it will be easier to import in postgres.</p>


问:
Connecting MySQL installed on AWS EC2 instance with AWS Glue
I have installed MySQL 5.7.25 on my AWS EC2 instance running Ubuntu 18.04 AMI. I want to connect this MySQL instance with AWS Glue but I have been unable to do so. I have associated my EC2 instance with an elastic ip and tried connecting the MySQL instance by using a JDBC url with AWS Glue, but every time my connection is refused. Is there any way to connect the two?</p>

答:
Before using AWS Glue, you should first use DMS to migrate your database. If your target database has a different schema than the source database, that's what we call heterogeneous database migrations, you need AWS SCT.

One example of heterogeneous database migration is moving from an Oracle Database to PostgreSQL. As you see, the schema structure, data types, and database code of source databases are quite differents.


问:
Python regex discrepancy between compiled and uncompiled regex
I'm trying to understand what is the difference between using re.MULTILINE and not using it in Python.

Specifically, I'm seeing differences between how regexps work when using compiled patterns with flags. In this example, I'm using "blubber" as input string and "^blubber$" as a pattern to match. This should clearly match.

Trying different combinations I get back None in the case when I pass re.MULTILINE to a compiled regex object's match method. Why would that be?

A test script:

```<code>import re
import sys

print(sys.version)

input_string = "blubber"
matching_pattern = "^blubber$"

result_one = re.match(matching_pattern, input_string)
print("re.match:                            %r" % (result_one,))

result_two = re.match(matching_pattern, input_string, re.M)
print("re.match multiline:                  %r" % (result_two,))

compiled_re = re.compile(matching_pattern)
result_three = compiled_re.match(input_string)
print("compiled match:                      %r" % (result_three,))

compiled_re = re.compile(matching_pattern)
result_four = compiled_re.match(input_string, re.M)
print("compiled match multiline:            %r" % (result_four,))

compiled_re = re.compile(matching_pattern, re.M)
result_five = compiled_re.match(input_string)
print("compiled multiline match:            %r" % (result_five,))

compiled_re = re.compile(matching_pattern, re.M)
result_six = compiled_re.match(input_string, re.M)
print("compiled multiline match multiline:  %r" % (result_six,))
</code>```

Example run output:

```<code>$ python3.8 wat_the_re.py
3.8.3 (default, May 19 2020, 14:59:28)
[GCC 8.3.0]
re.match:                            <re.Match object; span=(0, 7), match='blubber'>
re.match multiline:                  <re.Match object; span=(0, 7), match='blubber'>
compiled match:                      <re.Match object; span=(0, 7), match='blubber'>
compiled match multiline:            None
compiled multiline match:            <re.Match object; span=(0, 7), match='blubber'>
compiled multiline match multiline:  None
</code>```

答:
The second named parameter of pattern.match() is not flags but the matching position. Since the value of re.M is 8, the pattern is matched starting from the ninth position. You should pass the flags by name:

```<code>result_six = compiled_re.match(input_string, flags=re.M)
</code>```

Moreover, you already compiled the pattern with that flag, there is no need to pass it again.

Body:
I'm trying to understand what is the difference between using re.MULTILINE and not using it in Python.

Specifically, I'm seeing differences between how regexps work when using compiled patterns with flags. In this example, I'm using "blubber" as input string and "^blubber$" as a pattern to match. This should clearly match.

Trying different combinations I get back None in the case when I pass re.MULTILINE to a compiled regex object's match method. Why would that be?

A test script:

import re
import sys

print(sys.version)

input_string = "blubber"
matching_pattern = "^blubber$"

result_one = re.match(matching_pattern, input_string)
print("re.match:                            %r" % (result_one,))

result_two = re.match(matching_pattern, input_string, re.M)
print("re.match multiline:                  %r" % (result_two,))

compiled_re = re.compile(matching_pattern)
result_three = compiled_re.match(input_string)
print("compiled match:                      %r" % (result_three,))

compiled_re = re.compile(matching_pattern)
result_four = compiled_re.match(input_string, re.M)
print("compiled match multiline:            %r" % (result_four,))

compiled_re = re.compile(matching_pattern, re.M)
result_five = compiled_re.match(input_string)
print("compiled multiline match:            %r" % (result_five,))

compiled_re = re.compile(matching_pattern, re.M)
result_six = compiled_re.match(input_string, re.M)
print("compiled multiline match multiline:  %r" % (result_six,))

Example run output:

$ python3.8 wat_the_re.py
3.8.3 (default, May 19 2020, 14:59:28)
[GCC 8.3.0]
re.match:                            <re.Match object; span=(0, 7), match='blubber'>
re.match multiline:                  <re.Match object; span=(0, 7), match='blubber'>
compiled match:                      <re.Match object; span=(0, 7), match='blubber'>
compiled match multiline:            None
compiled multiline match:            <re.Match object; span=(0, 7), match='blubber'>
compiled multiline match multiline:  None

Body:
The second named parameter of pattern.match() is not flags but the matching position. Since the value of re.M is 8, the pattern is matched starting from the ninth position. You should pass the flags by name:

result_six = compiled_re.match(input_string, flags=re.M)

Moreover, you already compiled the pattern with that flag, there is no need to pass it again.


问:
Wait after showing MDI child form - alternative to DoEvents
A co-worker made some improvements to my app, but at the same time, he changed the whole app to use MDI child forms. So where I used to be able to use ShowDialog() to make the subroutine wait until the new form closed to continue, now I can't. I adapted some old VB6 code to try and replicate the same functionality, but it uses DoEvents() and I've been told to avoid that at all costs.

At this point I can't help but feel like there's just a fundamental flaw in my methodology here, and that there is probably a far simpler way to accomplish the same task.

```<code>    Private Sub Label_EditNode_Click(sender As Object, e As EventArgs) Handles Label_EditNode.Click
        Dim Frm As New frmVariableEditor With {
            .Tag = "FrmVariableEditor",
            .MdiParent = FrmMDIMain,
            .Dock = DockStyle.Fill,
            .Location = Me.Location,
            .Size = Me.Size,
            .myFieldName = "NodeClick",
            .myResultText = txbNodeClick.Text
        }

        Frm.Show()
        Call WaitOnFormUnload()

        txbNodeClick.Text = Frm.myResultText
    End Sub

    Public Sub WaitOnFormUnload()
        Dim bIsLoaded As Boolean = True
        Dim FormName As String = Me.MdiParent.ActiveMdiChild.Name ' Form.ActiveForm.Name
        Do While bIsLoaded
            bIsLoaded = False

            For Each f As Form In Application.OpenForms
                If f.Name = FormName Then
                    bIsLoaded = True
                    Application.DoEvents()
                    Exit For ' breaks the for loop
                End If
            Next f
        Loop
    End Sub
</code>```

答:
Goes a something like this:

```<code>Private Sub Label_EditNode_Click(sender As Object, e As EventArgs) Handles Label_EditNode.Click
    Dim Frm As New frmVariableEditor With {
        .Tag = "FrmVariableEditor",
        .MdiParent = FrmMDIMain,
        .Dock = DockStyle.Fill,
        .Location = Me.Location,
        .Size = Me.Size,
        .myFieldName = "NodeClick",
        .myResultText = txbNodeClick.Text
    }

    AddHandler Frm.FormClosing, AddressOf RetrieveBlahData

    Frm.Show()

End Sub

Private Sub RetrieveBlahData(sender as Object, e as FormClosingEventArgs)
   txbNodeClick.Text = DirectCast(sender, frmVariableEditor).myResultText
End Sub
</code>```

Probably doesn't get more minimal than that, except for maybe sharing a single data object:

```<code>    Dim Frm As New frmVariableEditor With {
        .Tag = "FrmVariableEditor",
        .MdiParent = FrmMDIMain,
        .Dock = DockStyle.Fill,
        .Location = Me.Location,
        .Size = Me.Size,
        .myFieldName = "NodeClick",
        .DataSetToBindTo = Me.DataSetWhatever
    }
</code>```

You'll have to re-code your form so that it takes this passed in dataset (or other data container) and gets its data from it (databinding) .. then as the editor form is changing the data, it's actually changing the original dataset in the main form too, because they're the same thing

Body:
A co-worker made some improvements to my app, but at the same time, he changed the whole app to use MDI child forms. So where I used to be able to use ShowDialog() to make the subroutine wait until the new form closed to continue, now I can't. I adapted some old VB6 code to try and replicate the same functionality, but it uses DoEvents() and I've been told to avoid that at all costs.

At this point I can't help but feel like there's just a fundamental flaw in my methodology here, and that there is probably a far simpler way to accomplish the same task.

    Private Sub Label_EditNode_Click(sender As Object, e As EventArgs) Handles Label_EditNode.Click
        Dim Frm As New frmVariableEditor With {
            .Tag = "FrmVariableEditor",
            .MdiParent = FrmMDIMain,
            .Dock = DockStyle.Fill,
            .Location = Me.Location,
            .Size = Me.Size,
            .myFieldName = "NodeClick",
            .myResultText = txbNodeClick.Text
        }

        Frm.Show()
        Call WaitOnFormUnload()

        txbNodeClick.Text = Frm.myResultText
    End Sub

    Public Sub WaitOnFormUnload()
        Dim bIsLoaded As Boolean = True
        Dim FormName As String = Me.MdiParent.ActiveMdiChild.Name ' Form.ActiveForm.Name
        Do While bIsLoaded
            bIsLoaded = False

            For Each f As Form In Application.OpenForms
                If f.Name = FormName Then
                    bIsLoaded = True
                    Application.DoEvents()
                    Exit For ' breaks the for loop
                End If
            Next f
        Loop
    End Sub

Body:
Goes a something like this:

Private Sub Label_EditNode_Click(sender As Object, e As EventArgs) Handles Label_EditNode.Click
    Dim Frm As New frmVariableEditor With {
        .Tag = "FrmVariableEditor",
        .MdiParent = FrmMDIMain,
        .Dock = DockStyle.Fill,
        .Location = Me.Location,
        .Size = Me.Size,
        .myFieldName = "NodeClick",
        .myResultText = txbNodeClick.Text
    }

    AddHandler Frm.FormClosing, AddressOf RetrieveBlahData

    Frm.Show()

End Sub

Private Sub RetrieveBlahData(sender as Object, e as FormClosingEventArgs)
   txbNodeClick.Text = DirectCast(sender, frmVariableEditor).myResultText
End Sub

Probably doesn't get more minimal than that, except for maybe sharing a single data object:

    Dim Frm As New frmVariableEditor With {
        .Tag = "FrmVariableEditor",
        .MdiParent = FrmMDIMain,
        .Dock = DockStyle.Fill,
        .Location = Me.Location,
        .Size = Me.Size,
        .myFieldName = "NodeClick",
        .DataSetToBindTo = Me.DataSetWhatever
    }

You'll have to re-code your form so that it takes this passed in dataset (or other data container) and gets its data from it (databinding) .. then as the editor form is changing the data, it's actually changing the original dataset in the main form too, because they're the same thing