问:
'swizzle' is not a member of 'glm'
I am using the following code to implement the "zoom to mouse point" functionality in opengl in c++. Most of the code is from
OpenGL Google maps style 2D camera / zoom to mouse cursor but I had to change some include statements because of changes in the GLM (http://glm.g-truc.net/0.9.5/index.html) codebase.

```<code>#include <GL/freeglut.h>
#include <iostream>
using namespace std;
#define GLM_SWIZZLE_XYZW
#define GLM_FORCE_RADIANS

#include "glm/glm.hpp"
#include "glm/detail/setup.hpp"
#include "glm/detail/_swizzle.hpp"
#include "glm/detail/_swizzle_func.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
glm::dvec3 Unproject( const glm::dvec3& win )
{
glm::ivec4 view;
glm::dmat4 proj, model;
glGetDoublev( GL_MODELVIEW_MATRIX, glm::value_ptr( model ) );
glGetDoublev( GL_PROJECTION_MATRIX, glm::value_ptr( proj ) );
glGetIntegerv( GL_VIEWPORT, glm::value_ptr( view ) );
glm::dvec3 world = glm::unProject( win, model, proj, view );
return world;
}
// unprojects the given window point
// and finds the ray intersection with the Z=0 plane
glm::dvec2 PlaneUnproject( const glm::dvec2& win )
{
glm::dvec3 world1 = Unproject( glm::dvec3( win, 0.01 ) );
glm::dvec3 world2 = Unproject( glm::dvec3( win, 0.99 ) );
// u is a value such that:
// 0 = world1.z + u * ( world2.z - world1.z )
double u = -world1.z / ( world2.z - world1.z );
// clamp u to reasonable values
if( u < 0 ) u = 0;
if( u > 1 ) u = 1;
return glm::swizzle< glm::X, glm::Y >( world1 + u * ( world2 - world1 ) );
}
// pixels per unit
const double ppu = 80.0;
glm::dvec2 center( 0 );
double scale = 1.0;
void ApplyCamera()
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
const double w = glutGet( GLUT_WINDOW_WIDTH ) / ppu;
const double h = glutGet( GLUT_WINDOW_HEIGHT ) / ppu;
glOrtho( -w/2, w/2, -h/2, h/2, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glScaled( scale, scale, 1.0 );
glTranslated( -center[0], -center[1], 0 );
}
glm::dvec2 centerStart( 0 );
int btn = -1;
void mouse( int button, int state, int x, int y )
{
ApplyCamera();
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
btn = button;
if( GLUT_LEFT_BUTTON == btn && GLUT_DOWN == state )
{
centerStart = PlaneUnproject( glm::dvec2( x, y ) );
}
if( GLUT_LEFT_BUTTON == btn && GLUT_UP == state )
{
btn = -1;
}
glutPostRedisplay();
}
void motion( int x, int y )
{
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
if( GLUT_LEFT_BUTTON == btn )
{
ApplyCamera();
glm::dvec2 cur = PlaneUnproject( glm::dvec2( x, y ) );
center += ( centerStart - cur );
}
glutPostRedisplay();
}
void wheel( int wheel, int direction, int x, int y )
{
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
ApplyCamera();
glm::dvec2 beforeZoom = PlaneUnproject( glm::dvec2( x, y ) );
const double scaleFactor = 0.90;
if( direction == -1 ) scale *= scaleFactor;
if( direction == 1 ) scale /= scaleFactor;
ApplyCamera();
glm::dvec2 afterZoom = PlaneUnproject( glm::dvec2( x, y ) );
center += ( beforeZoom - afterZoom );
glutPostRedisplay();
}
void display()
{
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
ApplyCamera();
glBegin( GL_QUADS );
glVertex2i( -1, -1 );
glVertex2i( 1, -1 );
glVertex2i( 1, 1 );
glVertex2i( -1, 1 );
glEnd();
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glutMouseFunc( mouse );
glutMotionFunc( motion );
glutMouseWheelFunc( wheel );
glutDisplayFunc( display );
glutMainLoop();
return 0;
}
</code>```

The errors

```<code>error: 'swizzle' is not a member of 'glm'
error: 'X' is not a member of 'glm'
error: 'Y' is not a member of 'glm'
</code>```

are in line

```<code>return glm::swizzle< glm::X, glm::Y >( world1 + u * ( world2 - world1 ) );
</code>```

I know that glm::swizzle is obviously wrong but glm::detail::_swizzle requires 8 parameters compared to 2 earlier by glm::swizzle. What would be the new parameters be? Also, I don't know how to correct glm::X and glm::Y. Can someone please help?

答:
In newer version of glm if you want swizzle operator you need to define GLM_FORCE_SWIZZLE before including glm. GLM_SWIZZLE is deprecated.

```<code>#define GLM_FORCE_SWIZZLE
#include "glm/glm.hpp"
</code>```

Then you can use it like this:

```<code>return world1.yx();
</code>```

And on some compiler you can also do it like this:

```<code>return world1.yx;
</code>```

Warning: Just be aware that there is a huge performance impact if you enable it.
On Visual Studio 2013 I measure around x150 speed difference in runtime matrix multiplication.

With swizzle operations:   450 000 multiplications per second.

Without swizzle operations: 65 000 000 multiplications per second.

Title: 'swizzle' is not a member of 'glm'

Body:
I am using the following code to implement the "zoom to mouse point" functionality in opengl in c++. Most of the code is from
OpenGL Google maps style 2D camera / zoom to mouse cursor but I had to change some include statements because of changes in the GLM (http://glm.g-truc.net/0.9.5/index.html) codebase.

#include <GL/freeglut.h>
#include <iostream>
using namespace std;
#define GLM_SWIZZLE_XYZW
#define GLM_FORCE_RADIANS

#include "glm/glm.hpp"
#include "glm/detail/setup.hpp"
#include "glm/detail/_swizzle.hpp"
#include "glm/detail/_swizzle_func.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
glm::dvec3 Unproject( const glm::dvec3& win )
{
glm::ivec4 view;
glm::dmat4 proj, model;
glGetDoublev( GL_MODELVIEW_MATRIX, glm::value_ptr( model ) );
glGetDoublev( GL_PROJECTION_MATRIX, glm::value_ptr( proj ) );
glGetIntegerv( GL_VIEWPORT, glm::value_ptr( view ) );
glm::dvec3 world = glm::unProject( win, model, proj, view );
return world;
}
// unprojects the given window point
// and finds the ray intersection with the Z=0 plane
glm::dvec2 PlaneUnproject( const glm::dvec2& win )
{
glm::dvec3 world1 = Unproject( glm::dvec3( win, 0.01 ) );
glm::dvec3 world2 = Unproject( glm::dvec3( win, 0.99 ) );
// u is a value such that:
// 0 = world1.z + u * ( world2.z - world1.z )
double u = -world1.z / ( world2.z - world1.z );
// clamp u to reasonable values
if( u < 0 ) u = 0;
if( u > 1 ) u = 1;
return glm::swizzle< glm::X, glm::Y >( world1 + u * ( world2 - world1 ) );
}
// pixels per unit
const double ppu = 80.0;
glm::dvec2 center( 0 );
double scale = 1.0;
void ApplyCamera()
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
const double w = glutGet( GLUT_WINDOW_WIDTH ) / ppu;
const double h = glutGet( GLUT_WINDOW_HEIGHT ) / ppu;
glOrtho( -w/2, w/2, -h/2, h/2, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glScaled( scale, scale, 1.0 );
glTranslated( -center[0], -center[1], 0 );
}
glm::dvec2 centerStart( 0 );
int btn = -1;
void mouse( int button, int state, int x, int y )
{
ApplyCamera();
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
btn = button;
if( GLUT_LEFT_BUTTON == btn && GLUT_DOWN == state )
{
centerStart = PlaneUnproject( glm::dvec2( x, y ) );
}
if( GLUT_LEFT_BUTTON == btn && GLUT_UP == state )
{
btn = -1;
}
glutPostRedisplay();
}
void motion( int x, int y )
{
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
if( GLUT_LEFT_BUTTON == btn )
{
ApplyCamera();
glm::dvec2 cur = PlaneUnproject( glm::dvec2( x, y ) );
center += ( centerStart - cur );
}
glutPostRedisplay();
}
void wheel( int wheel, int direction, int x, int y )
{
y = glutGet( GLUT_WINDOW_HEIGHT ) - y;
ApplyCamera();
glm::dvec2 beforeZoom = PlaneUnproject( glm::dvec2( x, y ) );
const double scaleFactor = 0.90;
if( direction == -1 ) scale *= scaleFactor;
if( direction == 1 ) scale /= scaleFactor;
ApplyCamera();
glm::dvec2 afterZoom = PlaneUnproject( glm::dvec2( x, y ) );
center += ( beforeZoom - afterZoom );
glutPostRedisplay();
}
void display()
{
glClearColor( 0, 0, 0, 1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
ApplyCamera();
glBegin( GL_QUADS );
glVertex2i( -1, -1 );
glVertex2i( 1, -1 );
glVertex2i( 1, 1 );
glVertex2i( -1, 1 );
glEnd();
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glutMouseFunc( mouse );
glutMotionFunc( motion );
glutMouseWheelFunc( wheel );
glutDisplayFunc( display );
glutMainLoop();
return 0;
}

The errors

error: 'swizzle' is not a member of 'glm'
error: 'X' is not a member of 'glm'
error: 'Y' is not a member of 'glm'

are in line

return glm::swizzle< glm::X, glm::Y >( world1 + u * ( world2 - world1 ) );

I know that glm::swizzle is obviously wrong but glm::detail::_swizzle requires 8 parameters compared to 2 earlier by glm::swizzle. What would be the new parameters be? Also, I don't know how to correct glm::X and glm::Y. Can someone please help?

Body:
In newer version of glm if you want swizzle operator you need to define GLM_FORCE_SWIZZLE before including glm. GLM_SWIZZLE is deprecated.

#define GLM_FORCE_SWIZZLE
#include "glm/glm.hpp"

Then you can use it like this:

return world1.yx();

And on some compiler you can also do it like this:

return world1.yx;

Warning: Just be aware that there is a huge performance impact if you enable it.
On Visual Studio 2013 I measure around x150 speed difference in runtime matrix multiplication.

With swizzle operations:   450 000 multiplications per second.

Without swizzle operations: 65 000 000 multiplications per second.


来源: stackexchange

问:
iPad:Lock UIView orientation into Landscape mode only
This requirement is for iPad.
I have an UIView which used as Camera overlay view when launching video recording. It set in UIImagePickerController as below.

```<code>[self presentModalViewController:pickerController animated:NO];
pickerController.cameraOverlayView =myOwnOverlay;
</code>```

This is my requirement that i have to provide my own overlay in UIImagePickerController when calling camera for video recording.
I want to lock my own camera overlay UIView into LANDSCAPE mode only, so that allow user can record video in Landscape mode only and not in Portrait mode, this is also my project requirement.
I know about shouldAutorotateToInterfaceOrientation which is used for UIViewController. I used "[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];" it, it locks to Landscape mode when i launch this camera own overlay UIView, but when i rotate the device, UIView also rotates to Portrait. I don't want Portrait mode at all. I tried to handle this issue like below, but its not working for UIView. Then i saw this is possible in UIviewController, but not in UIView. But i must to have UIView for this camera launch operation.

```<code>-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{

return (interfaceOrientation==UIInterfaceOrientationLandscapeRight || interfaceOrientation==UIInterfaceOrientationLandscapeLeft);
}
</code>```

Please suggest me how can i provide solution for orientation lock for my UIView?

Thank you!

答:
Doubt over allowing from APPLE but If you want the UIImagePickerController to start(and stay) in Landscape orientation use following code.

```<code>//Initialize picker

UIImagePickerController * picker = [[UIImagePickerController alloc] init];
   picker.delegate = self;

//set Device to Landscape. This will give you a warning. I ignored it.
//warning: 'UIDevice' may not respond to '-setOrientation:'

[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

//Set Notifications so that when user rotates phone, the orientation is reset to landscape.
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

//Refer to the method didRotate:
[[NSNotificationCenter defaultCenter] addObserver:self
              selector:@selector(didRotate:)
               name:@"UIDeviceOrientationDidChangeNotification" object:nil];

//Set the picker source as the camera
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

//Bring in the picker view
[self presentModalViewController:picker animated:YES];
</code>```

The method didRotate:

```<code>- (void) didRotate:(NSNotification *)notification

{
      //Maintain the camera in Landscape orientation
 [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

}
</code>```

Credit for This code belongs to UIImagePickerController in Landscape

ContentLicense: CC BY-SA 3.0

Body:
This requirement is for iPad.
I have an UIView which used as Camera overlay view when launching video recording. It set in UIImagePickerController as below.

[self presentModalViewController:pickerController animated:NO];
pickerController.cameraOverlayView =myOwnOverlay;

This is my requirement that i have to provide my own overlay in UIImagePickerController when calling camera for video recording.
I want to lock my own camera overlay UIView into LANDSCAPE mode only, so that allow user can record video in Landscape mode only and not in Portrait mode, this is also my project requirement.
I know about shouldAutorotateToInterfaceOrientation which is used for UIViewController. I used "[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];" it, it locks to Landscape mode when i launch this camera own overlay UIView, but when i rotate the device, UIView also rotates to Portrait. I don't want Portrait mode at all. I tried to handle this issue like below, but its not working for UIView. Then i saw this is possible in UIviewController, but not in UIView. But i must to have UIView for this camera launch operation.

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{

return (interfaceOrientation==UIInterfaceOrientationLandscapeRight || interfaceOrientation==UIInterfaceOrientationLandscapeLeft);
}

Please suggest me how can i provide solution for orientation lock for my UIView?

Thank you!

Body:
Doubt over allowing from APPLE but If you want the UIImagePickerController to start(and stay) in Landscape orientation use following code.

//Initialize picker

UIImagePickerController * picker = [[UIImagePickerController alloc] init];
   picker.delegate = self;

//set Device to Landscape. This will give you a warning. I ignored it.
//warning: 'UIDevice' may not respond to '-setOrientation:'

[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

//Set Notifications so that when user rotates phone, the orientation is reset to landscape.
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

//Refer to the method didRotate:
[[NSNotificationCenter defaultCenter] addObserver:self
              selector:@selector(didRotate:)
               name:@"UIDeviceOrientationDidChangeNotification" object:nil];

//Set the picker source as the camera
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

//Bring in the picker view
[self presentModalViewController:picker animated:YES];

The method didRotate:

- (void) didRotate:(NSNotification *)notification

{
      //Maintain the camera in Landscape orientation
 [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];

}

Credit for This code belongs to UIImagePickerController in Landscape


问:
Resize eventListener Edge
I've currently encountered this issue on Microsoft Edge 44.18362.449.0 which I do not know how to solve.

I applied an event listener on the window in order to perform some resizing actions. This works perfectly on Chromium-based browsers and IE11. For some reason on Edge when I try printing out the window.innerWidth in the resize function it stops at 562px. This means the event listener does not trigger when the window size goes under 562px.

Did anyone encounter this issue before?

答:
I try to test the below code with the MS Edge legacy browser 44.18362.449.0, IE 11 browser, and Google Chrome browser.

<!DOCTYPE html>

<meta charset="utf-8">
<title>Test</title>

 ```

Output:

Based on my test result, I noticed that the MS Edge legacy browser can minimum show the 562 px of window width but user can still decrease the size by resizing the window width but the MS Edge legacy browser will keep displaying the width 562 px.

Generally, the browsers stop resizing at some point and it shows that value as a height or width. Here, the issue is that the MS Edge legacy browser shows the minimum 562 px of width but the user can still decrease the window width.

I suggest you press ALT + J key in the MS Edge legacy browser window and it will launch the Feedback hub. You can try to provide feedback regarding this issue.

ContentLicense: CC BY-SA 4.0

Title: Resize eventListener Edge

Body:
I try to test the below code with the MS Edge legacy browser 44.18362.449.0, IE 11 browser, and Google Chrome browser.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
    <div id="result"></div>
    <script>
    function displayWindowSize()
    {
        var w = window.innerWidth;
        var h = window.innerHeight;
        document.getElementById("result").innerHTML = "Width: " + w + ", " + "Height: " + h;
    }
    window.addEventListener("resize", displayWindowSize);
    displayWindowSize();
    </script>
</body>
</html>

Output:

Based on my test result, I noticed that the MS Edge legacy browser can minimum show the 562 px of window width but user can still decrease the size by resizing the window width but the MS Edge legacy browser will keep displaying the width 562 px.

Generally, the browsers stop resizing at some point and it shows that value as a height or width. Here, the issue is that the MS Edge legacy browser shows the minimum 562 px of width but the user can still decrease the window width.

I suggest you press ALT + J key in the MS Edge legacy browser window and it will launch the Feedback hub. You can try to provide feedback regarding this issue.


问:
Apache cordova Build failed on implementing firebase : Dependency failing
this is the Error

[ What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[19.0.
    1]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown.

Dependency failing: com.google.firebase:firebase-messaging:19.0.1 -> com.google.firebase:firebase-iid@[19.0.1], but fire
  base-iid version was 20.0.2.

The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art
  ifact with the issue.]Here is the command prompt picture---view

答:
I resolved it using

```<code>  "cordova-plugin-fcm-with-dependecy-updated": {
    "FCM_CORE_VERSION": "16.0.9",
    "FCM_VERSION": "20.1.+",
    "GRADLE_TOOLS_VERSION": "3.5.0",
    "GOOGLE_SERVICES_VERSION": "4.2.0",
    "ANDROID_DEFAULT_NOTIFICATION_ICON": "@mipmap/ic_launcher"
  },
</code>```

and

```<code>"cordova-plugin-firebase-analytics": {
    "FIREBASE_ANALYTICS_COLLECTION_ENABLED": "true",
    "FIREBASE_ANALYTICS_VERSION": "17.4.+"
  }
</code>```

in package.json

Body:
I resolved it using

  "cordova-plugin-fcm-with-dependecy-updated": {
    "FCM_CORE_VERSION": "16.0.9",
    "FCM_VERSION": "20.1.+",
    "GRADLE_TOOLS_VERSION": "3.5.0",
    "GOOGLE_SERVICES_VERSION": "4.2.0",
    "ANDROID_DEFAULT_NOTIFICATION_ICON": "@mipmap/ic_launcher"
  },

and

"cordova-plugin-firebase-analytics": {
    "FIREBASE_ANALYTICS_COLLECTION_ENABLED": "true",
    "FIREBASE_ANALYTICS_VERSION": "17.4.+"
  }

in package.json


问:
SAS-Append data to a table and increment a flag on the resultant table
I have two tables on SAS "Table_A" and "Table_A_Archive", as part my ETL process "Table_A" is created on a daily basis and the data should be archived on "Table_A_Archive". When the data is archived on "Table_A_Archive" a a flag will be created/updated "DT_FLAG".

On the first day this is how the table would look like

```<code> "Table_A"
 | ID  | Load_Date
 ------ -------------
 | 100 | 01JUN2020:12:13:56

 "Table_A_Archive"
  | ID  | Load_Date           | DT_FLAG
  ------ --------------------- ---------
  | 100 | 01JUN2020:12:13:56  | 1
</code>```

On Day 2

```<code> "Table_A"
 | ID  | Load_Date
 ------ ------------
 | 101 | 02JUN2020:12:13:56

 "Table_A_Archive"
 | ID  | Load_Date           | DT_FLAG
 ------ --------------------- ---------
 | 100 | 01JUN2020:12:13:56  | 2
 | 101 | 02JUN2020:12:13:56  | 1
</code>```

The new data should be loaded with the DT_FLAG of 1 and old records DT_FLAG should be incremented by 1. Load_Date is the pivotal point. I have written a SAS code but it seems a bit messy, can someone please help me with a SAS Datastep

```<code> %macro Cntl_archive(table_name=,arch_table_name=);
 %GLOBAL WRK;

 %if %sysfunc(exist(&arch_table_name.))  %then %do;

 proc append base=&arch_table_name. data=&table_name. force;
 run;

 proc sql;
 Create table TEMP as
 Select distinct Load_Date,Load_Date as WRK from &arch_table_name.
 order by Load_Date desc
 ;quit;

 proc rank data=TEMP descending out=TEMP;
 var WRK;
 ranks count;
 run;

 data &arch_table_name. (drop=DT_FLAG);
 set    &arch_table_name.;
 run;

 proc sql;
 Create table &arch_table_name. as
 Select T0.*,T1.count as DT_FLAG from &arch_table_name. T0
 inner join TEMP T1 on T0.Load_Date=T1.Load_Date
 ;quit
 %end;
 %else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;
</code>```

答:
I think do the same thing by a merge statement:

```<code>%if %sysfunc(exist(Table_A_Archive)) = 0 %then %do;
  data Table_A_Archive;
    set Table_A;
  run;
%end;

data Table_A_Archive;
  merge Table_A_Archive(in=ALL) Table_A;
  by ID;

  if ALL then DT_FLAG = sum(DT_FLAG,1);
  else DT_FLAG = 1;
run;
</code>```

Consider of you may want this daily work be as quick as possibly, I suggest to use update or modify statement to replace merge:

```<code>%if %sysfunc(exist(Table_A_Archive)) = 0 %then %do;
  data Table_A_Archive;
    set Table_A;
  run;
%end;

data Table_A_Archive;
  update Table_A_Archive Table_A;
  by ID;

  if _iorc_ = %sysrc(_sok) then DT_FLAG = sum(DT_FLAG,1);
run;
</code>```

It is more efficient because it can update(or modify) data without creating a copy of the data set.

Body:
I have two tables on SAS "Table_A" and "Table_A_Archive", as part my ETL process "Table_A" is created on a daily basis and the data should be archived on "Table_A_Archive". When the data is archived on "Table_A_Archive" a a flag will be created/updated "DT_FLAG".

On the first day this is how the table would look like

 "Table_A"
 | ID  | Load_Date
 ------ -------------
 | 100 | 01JUN2020:12:13:56

 "Table_A_Archive"
  | ID  | Load_Date           | DT_FLAG
  ------ --------------------- ---------
  | 100 | 01JUN2020:12:13:56  | 1

On Day 2

 "Table_A"
 | ID  | Load_Date
 ------ ------------
 | 101 | 02JUN2020:12:13:56

 "Table_A_Archive"
 | ID  | Load_Date           | DT_FLAG
 ------ --------------------- ---------
 | 100 | 01JUN2020:12:13:56  | 2
 | 101 | 02JUN2020:12:13:56  | 1

The new data should be loaded with the DT_FLAG of 1 and old records DT_FLAG should be incremented by 1. Load_Date is the pivotal point. I have written a SAS code but it seems a bit messy, can someone please help me with a SAS Datastep

 %macro Cntl_archive(table_name=,arch_table_name=);
 %GLOBAL WRK;

 %if %sysfunc(exist(&arch_table_name.))  %then %do;

 proc append base=&arch_table_name. data=&table_name. force;
 run;

 proc sql;
 Create table TEMP as
 Select distinct Load_Date,Load_Date as WRK from &arch_table_name.
 order by Load_Date desc
 ;quit;

 proc rank data=TEMP descending out=TEMP;
 var WRK;
 ranks count;
 run;

 data &arch_table_name. (drop=DT_FLAG);
 set    &arch_table_name.;
 run;

 proc sql;
 Create table &arch_table_name. as
 Select T0.*,T1.count as DT_FLAG from &arch_table_name. T0
 inner join TEMP T1 on T0.Load_Date=T1.Load_Date
 ;quit
 %end;
 %else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;

Body:
I think do the same thing by a merge statement:

%if %sysfunc(exist(Table_A_Archive)) = 0 %then %do;
  data Table_A_Archive;
    set Table_A;
  run;
%end;

data Table_A_Archive;
  merge Table_A_Archive(in=ALL) Table_A;
  by ID;

  if ALL then DT_FLAG = sum(DT_FLAG,1);
  else DT_FLAG = 1;
run;

Consider of you may want this daily work be as quick as possibly, I suggest to use update or modify statement to replace merge:

%if %sysfunc(exist(Table_A_Archive)) = 0 %then %do;
  data Table_A_Archive;
    set Table_A;
  run;
%end;

data Table_A_Archive;
  update Table_A_Archive Table_A;
  by ID;

  if _iorc_ = %sysrc(_sok) then DT_FLAG = sum(DT_FLAG,1);
run;

It is more efficient because it can update(or modify) data without creating a copy of the data set.


问:
Best model to predict failure using time series from sensors
I'm working with a company on a project to develop ML models for predictive maintenance. The data we have is a collection of log files. In each log file we have time series from sensors (Temperature, Pressure, MototSpeed,...) and a variable in which we record the faults occurred. The aim here is to build a model that will use the log files as its input (the time series) and to predict whether there will be a failure or not. For this I have some questions:
1) What is the best model capable of doing this?
2) What is the solution to deal with imbalanced data? In fact, for some kind of failures we don't have enough data.
I tried to construct an RNN classifier using LSTM after transforming the time series to sub time series of a fixed length. The targets were 1 if there was a fault and 0 if not. The number of ones compared to the number of zeros is negligible. As a result, the model always predicted 0. What is the solution?</p>

答:
Mohamed, for this problem you could actually start with traditional ML models (random forest, lightGBM, or anything of this nature). I recommend you focus on your features. For example you mentioned Pressure, MototSpeed. Look at some window of time going back. Calculate moving averages, min/max values in that same window, st.dev. To tackle this problem you will need to have a set of healthy features. Take a look at featuretools package. You can either use it or get some ideas what features can be created using time series data. Back to your questions.

1) What is the best model capable of doing this? Traditional ML methods as mentioned above. You could also use deep learning models, but I would first start with easy models. Also if you do not have a lot of data I probably would not touch RNN models.

2) What is the solution to deal with imbalanced data? You may want to oversample or undersample your data. For oversampling look at the SMOTE package.

Good luck


问:
How do I select a mat-radio-button in Angular Material with "selected" property of mat-radio-group?
I have these lines of code

```<code><mat-radio-group color="primary"
                       (change)="systemChange($event)">
        <mat-radio-button *ngFor="let system of systems"
                          [value]="system">{{system}}</mat-radio-button>
</code>```

When I look at the page none of the buttons are selected by default and I want to make 1 of them selected. In AngularMaterial docs there is a

```<code>@Input()
 selected: MatRadioButton
</code>```

and I cannot understand how to use it with *ngFor cycle or is there another way of solving this problem with *ngFor.

答:
You can add a [value]="systems[0]" to your code:

```<code><mat-radio-group color="primary"
                 [value]="sys"
                 (change)="systemChange($event)">
</code>```

with   sys = 'whatever' in your controller;

In this example the second radio is selected:

```<code><mat-radio-group [value]="val" aria-label="Select an option">
    <mat-radio-button value="a">Option 1</mat-radio-button>
    <mat-radio-button value="b">Option 2</mat-radio-button>
    <mat-radio-button value="c">Option 3</mat-radio-button>
    <mat-radio-button value="d">Option 4</mat-radio-button>
</mat-radio-group>
</code>```

and

```<code>export class RadioOverviewExample {
  val = 'b';
}
</code>```

Body:
I have these lines of code

<mat-radio-group color="primary"
                       (change)="systemChange($event)">
        <mat-radio-button *ngFor="let system of systems"
                          [value]="system">{{system}}</mat-radio-button>

When I look at the page none of the buttons are selected by default and I want to make 1 of them selected. In AngularMaterial docs there is a

@Input()
 selected: MatRadioButton

and I cannot understand how to use it with *ngFor cycle or is there another way of solving this problem with *ngFor.

Body:
You can add a [value]="systems[0]" to your code:

<mat-radio-group color="primary"
                 [value]="sys"
                 (change)="systemChange($event)">

with   sys = 'whatever' in your controller;

In this example the second radio is selected:

<mat-radio-group [value]="val" aria-label="Select an option">
    <mat-radio-button value="a">Option 1</mat-radio-button>
    <mat-radio-button value="b">Option 2</mat-radio-button>
    <mat-radio-button value="c">Option 3</mat-radio-button>
    <mat-radio-button value="d">Option 4</mat-radio-button>
</mat-radio-group>

and

export class RadioOverviewExample {
  val = 'b';
}


问:
How to read contents from a file and store it in a hash-map in clojure?
I got a small problem in clojure. I am new to this programming environment and need a little help. I have got a text file in this format :

```<code>1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533
</code>```

I want to parse each line in file and want to store data in hashmap in this way :

```<code>{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }
</code>```

Here is my code till now but I have not got any success.

```<code>(defn readcustfile[]
  (def cust-file (clojure.string/split-lines (slurp "cust.txt")))

  (doseq [line cust-file]
    (def cust-id (nth (clojure.string/split line #"\|") 0))
    (def cust-name (str (nth (clojure.string/split line #"\|") 1)))
    (def cust-add (str (nth (clojure.string/split line #"\|") 2)))
    (def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
    (def cust-data (str cust-name "," cust-add "," cust-phone))
    (def cust (map (fn [[id name add phone]]
                     (list (Integer/parseInt cust-id)
                           (hash-map :name cust-name
                                     :add cust-add
                                     :phone cust-phone))
    )
  )
(readcustfile)
</code>```

答:
what i would propose, is to read file line by line transducing it into resulting map in one pass:

```<code>(require '[clojure.java.io :refer [reader]]
         '[clojure.string :as cs]
         '[clojure.edn :as edn])

(with-open [rdr (reader "data.csv")]
  (into {}
        (map (comp (juxt (comp edn/read-string first) rest)
                   #(cs/split % #"\|")))
        (line-seq rdr)))

;;=> {1 ("John Smith" "123 Here Street" "456-4567"),
;;    2 ("Sue Jones" "43 Rose Court Street" "345-7867"),
;;    3 ("Fan Yuhong" "165 Happy Lane" "345-4533")}
</code>```

notice, you don't have to read the whole file into memory, rather you use with-open reader + line seq.

notice also, the form of into + map (the transducer) is used instead of simple map then into {} or for, to avoid intermediate collection creation.

Body:
I got a small problem in clojure. I am new to this programming environment and need a little help. I have got a text file in this format :

1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533

I want to parse each line in file and want to store data in hashmap in this way :

{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }

Here is my code till now but I have not got any success.

(defn readcustfile[]
  (def cust-file (clojure.string/split-lines (slurp "cust.txt")))

  (doseq [line cust-file]
    (def cust-id (nth (clojure.string/split line #"\|") 0))
    (def cust-name (str (nth (clojure.string/split line #"\|") 1)))
    (def cust-add (str (nth (clojure.string/split line #"\|") 2)))
    (def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
    (def cust-data (str cust-name "," cust-add "," cust-phone))
    (def cust (map (fn [[id name add phone]]
                     (list (Integer/parseInt cust-id)
                           (hash-map :name cust-name
                                     :add cust-add
                                     :phone cust-phone))
    )
  )
(readcustfile)

Body:
what i would propose, is to read file line by line transducing it into resulting map in one pass:

(require '[clojure.java.io :refer [reader]]
         '[clojure.string :as cs]
         '[clojure.edn :as edn])

(with-open [rdr (reader "data.csv")]
  (into {}
        (map (comp (juxt (comp edn/read-string first) rest)
                   #(cs/split % #"\|")))
        (line-seq rdr)))

;;=> {1 ("John Smith" "123 Here Street" "456-4567"),
;;    2 ("Sue Jones" "43 Rose Court Street" "345-7867"),
;;    3 ("Fan Yuhong" "165 Happy Lane" "345-4533")}

notice, you don't have to read the whole file into memory, rather you use with-open reader + line seq.

notice also, the form of into + map (the transducer) is used instead of simple map then into {} or for, to avoid intermediate collection creation.


问:
Path parameter in URL for http outbound gateway
I hava xml that include this :

```<code><channel id="myDataChannel"></channel>
<http:outbound-gateway
    request-channel="myDataChannel"
    url="{url}/myApi/getData/{id}"
    expected-response-type="com.api.dto.Data"
    http-method="GET"
    rest-template="myRestTemplate">
    <http:uri-variable name="url" expression="headers.url" />
</http:outbound-gateway>
</code>```

and in java code like this :

```<code>    MessagingTemplate myTemplate = new MessagingTemplate();
    Message<?> getDataReply = null;
    Data dataDto = null;

    Message<?> requestMsg = MessageBuilder.withPayload(requestDto)
            .build();

    getDataReply = template.sendAndReceive(myDataChannel, requestMsg);
    return dataDto = (Data) getDataReply.getPayload();
</code>```

here is my question how to path id in URL with payload in java code and there is an additional tag should I add to XML in out-bound-gateway ?

答:
Your question is not clear but you need something like

```<code>Message<?> requestMsg = MessageBuilder.withPayload(requestDto)
        .setHeader("url", ...)
        .setHeader("id", ...)
        .build();
</code>```

and

```<code><http:uri-variable name="id" expression="headers.id" />
</code>```

Or, if the id is a property of the payload

```<code>Message<?> requestMsg = MessageBuilder.withPayload(requestDto)
        .setHeader("url", ...)
        .build();
</code>```

and

```<code><http:uri-variable name="id" expression="payload.id" />
</code>```

Body:
I hava xml that include this :

<channel id="myDataChannel"></channel>
<http:outbound-gateway
    request-channel="myDataChannel"
    url="{url}/myApi/getData/{id}"
    expected-response-type="com.api.dto.Data"
    http-method="GET"
    rest-template="myRestTemplate">
    <http:uri-variable name="url" expression="headers.url" />
</http:outbound-gateway>

and in java code like this :

    MessagingTemplate myTemplate = new MessagingTemplate();
    Message<?> getDataReply = null;
    Data dataDto = null;

    Message<?> requestMsg = MessageBuilder.withPayload(requestDto)
            .build();

    getDataReply = template.sendAndReceive(myDataChannel, requestMsg);
    return dataDto = (Data) getDataReply.getPayload();

here is my question how to path id in URL with payload in java code and there is an additional tag should I add to XML in out-bound-gateway ?

Body:
Your question is not clear but you need something like

Message<?> requestMsg = MessageBuilder.withPayload(requestDto)
        .setHeader("url", ...)
        .setHeader("id", ...)
        .build();

and

<http:uri-variable name="id" expression="headers.id" />

Or, if the id is a property of the payload

Message<?> requestMsg = MessageBuilder.withPayload(requestDto)
        .setHeader("url", ...)
        .build();

and

<http:uri-variable name="id" expression="payload.id" />


问:
Semantic Diff Utilities
I'm trying to find some good examples of semantic diff/merge utilities.  The traditional paradigm of comparing source code files works by comparing lines and characters.. but are there any utilities out there (for any language) that actually consider the structure of code when comparing files?

For example, existing diff programs will report "difference found at character 2 of line 125. File x contains v-o-i-d, where file y contains b-o-o-l".  A specialized tool should be able to report "Return type of method doSomething() changed from void to bool".

I would argue that this type of semantic information is actually what the user is looking for when comparing code, and should be the goal of next-generation progamming tools.  Are there any examples of this in available tools?

答:
What you're groping for is a "tree diff". It turns out that this is much harder to do well than a simple line-oriented textual diff, which is really just the comparison of two flat sequences.

"A Fine-Grained XML Structural Comparison Approach" concludes, in part with:

Our theoretical study as well as our experimental evaluation
  showed that the proposed method yields improved structural similarity results with
  respect to existing alternatives, while having the same time complexity (O(N^2))

(emphasis mine)

Indeed, if you're looking for more examples of tree differencing I suggest focusing on XML since that's been driving practical developments in that area.

ContentLicense: CC BY-SA 2.5

Title: Semantic Diff Utilities

OwnerDisplayName: bendin


问:
how do I pass information from one class to another
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

```<code>File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }
</code>```

This code is in my customer class how do I get this information in my append class??

答:
Your question is not entirely clear to me, but here's a problems you might run into based on your description:

What is getName() supposed to return, the name of the file, or the name of the person? If it's supposed to return the file name, then use getFileName() instead - it's clearer!

I don't really understand why you'd need an Append class. Personally, I'd handle appending additional info inside the Customer class. I'd do it so that every time a value is added or changed, the info is saved back into the file like:

```<code>class Customer {
    public void setForename(String forename) {
        this.forename = forename;
        save();
    }
    public void setSurname(String surname) {
        this.surname = surname;
        save();
    }
    public void save() {
        // clear file
        // add new content
        String fileContents = "forename="+forname+"&surname="+surname;
        // save to file
    }
</code>```

Maybe I'm not understanding your needs correctly though...

Body:
I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I  can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.

File FName = fileChooser.getSelectedFile();
      String name = FName.getName();

 public String getname() { return name; }

This code is in my customer class how do I get this information in my append class??

Body:
Your question is not entirely clear to me, but here's a problems you might run into based on your description:

What is getName() supposed to return, the name of the file, or the name of the person? If it's supposed to return the file name, then use getFileName() instead - it's clearer!

I don't really understand why you'd need an Append class. Personally, I'd handle appending additional info inside the Customer class. I'd do it so that every time a value is added or changed, the info is saved back into the file like:

class Customer {
    public void setForename(String forename) {
        this.forename = forename;
        save();
    }
    public void setSurname(String surname) {
        this.surname = surname;
        save();
    }
    public void save() {
        // clear file
        // add new content
        String fileContents = "forename="+forname+"&surname="+surname;
        // save to file
    }

Maybe I'm not understanding your needs correctly though...


问:
How to control the for loop with a if condition in it not to give output till the loop completes
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

```<code>public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}
</code>```

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

答:
For these cases you can use a "run" variable. Declare the output variable before entering the for loop (set it to null) and then set the result based on your conditions. This way you can make sure you loop over every input and if no condition is met, your variable is still null:

```<code>public static String matching(String input){

  String result = null;  // we declare the result here and return it in the end

    HashMap<String, String> hm =  new HashMap<String, String>();

    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            result = input;           // the input is the result if it meats the condition
            break;                    // the return at this point would make the break obsolete
        }
    }
    return result;                    // if (and only if) the condition is met your result variable has a value - otherwise it will be null
}
</code>```

EDIT here is a more type-safe solution:

```<code>public static String matching(String input){

    String result = null;  // we declare the result here and return it in the end

    HashMap<String, String> hm =  new HashMap<String, String>();

    for (String key : hm.keySet()) {  // personally I find it easier to read and to follow
        String value = hm.get(key);   // here the value will still be a String
        if(input.equals(condition)){  // FYI for more precise conditions you can also use input.equalsIgnoreCase(condition)
            result = input;           // the input is the result if it meets the condition
            break;                    // the return at this point would make the break obsolete
        }
    }
    return result;                    // if (and only if) the condition is met your result variable has a value - otherwise it will be null
}
</code>```

Body:
I have a method which is having a Map with a set of rules which I am trying to apply on input with an if condition.

When the condition is matched then the if will break the loop and return the matched value. If none of the conditions is matched, I need to return a null output that the input didn't satisfy any given condition.

My current code as below

public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            return input;
            break;
        }
    }
    return null;
}

Let's say the map has 5 entries and the condition which will satisfy the current input is present at the 5th position. The first four tests return null and when the condition at 5th position is matched it will return that matched condition. But I want to return the output only after evaluating all conditions in the map.
I tried putting else if after the if in the loop with a continue;, but it's giving the same result.

Please, how can I solve the issue ?

Body:
For these cases you can use a "run" variable. Declare the output variable before entering the for loop (set it to null) and then set the result based on your conditions. This way you can make sure you loop over every input and if no condition is met, your variable is still null:

public static String matching(String input){

  String result = null;  // we declare the result here and return it in the end

    HashMap<String, String> hm =  new HashMap<String, String>();

    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            result = input;           // the input is the result if it meats the condition
            break;                    // the return at this point would make the break obsolete
        }
    }
    return result;                    // if (and only if) the condition is met your result variable has a value - otherwise it will be null
}

EDIT here is a more type-safe solution:

public static String matching(String input){

    String result = null;  // we declare the result here and return it in the end

    HashMap<String, String> hm =  new HashMap<String, String>();

    for (String key : hm.keySet()) {  // personally I find it easier to read and to follow
        String value = hm.get(key);   // here the value will still be a String
        if(input.equals(condition)){  // FYI for more precise conditions you can also use input.equalsIgnoreCase(condition)
            result = input;           // the input is the result if it meets the condition
            break;                    // the return at this point would make the break obsolete
        }
    }
    return result;                    // if (and only if) the condition is met your result variable has a value - otherwise it will be null
}


答:
You can return only once from your method, if you need to store the value of unsuccessful matches then you better use a data store like List or Array.
Try something like this.</p>

```<code>public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();
    List<String> strList = new ArrayList<>(hm.size()); //same size as the map.

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            strList.add(input);
            break;
        }else{
            strList.add(null);
        }
    }
    return strList;
}
</code>```

Title: How to control the for loop with a if condition in it not to give output till the loop completes

Body:
You can return only once from your method, if you need to store the value of unsuccessful matches then you better use a data store like List or Array.
Try something like this.

public static String matching(String input){

    HashMap<String, String> hm =  new HashMap<String, String>();
    List<String> strList = new ArrayList<>(hm.size()); //same size as the map.

    //Key,Value pair in Hashmap represents Name of condition(Key) and Condition(value)
    for (Map.Entry mapElement : hm.entrySet()) {
        String value = mapElement.getValue();
        if(input.equals(condition)){
            strList.add(input);
            break;
        }else{
            strList.add(null);
        }
    }
    return strList;
}


问:
Is it possible to upgrade directly from Datastage 7.5.3 to 11.7.1?
We are migrating from Datastage 7.5.3 to 11.7.1. I was wondering whether we need to upgrade to an intermediate version of Datastage? Is there any conversion tool available? Any inputs from people who have experience in a similar upgrade are appreciated. Thanks </p>

答:
There is no option for in-place upgrade from DataStage v7 directly to Information Server v11.

You will need to install Information Server 11.7.1 (either to same machine in side-by-side config if machine has enough resources for both environments, or to a new server).   You can then export all of your existing DataStage jobs in v7 environment to dsx file that you can then import into the new environment.

More information on migration steps can be found here:
https://www.ibm.com/support/knowledgecenter/SSZJPZ_11.7.0/com.ibm.swg.im.iis.productization.iisinfsv.migrate.doc/topics/top_of_map.html

Though this document does not list specific steps for DataStage v7.5, the steps for DataStage v8 are equivalent as long as you export jobs as dsx files since istool did not exist in DataStage v7.


问:
PostgreSQL 9.2 JDBC driver uses client time zone?
I've run into an interesting challenge using a PostgreSQL database with the PostgreSQL JDBC driver. It seems that the latest version of the driver, 9.2, uses the client time zone when performing date/time matches.

This becomes a problem when the server (JasperReports Server) is set to UTC and the database server is set to US/Eastern.

If I run the following query from a client set to the UTC time zone I get different results using the 9.0 JDBC driver and the 9.2 JDBC driver.

```<code>select now(), extract(timezone FROM now()), current_setting('TIMEZONE'), now()-interval '1 hour' as "1HourAgo"
</code>```

Results using 9.0 JDBC driver:

```<code>now                         date_part   current_setting     1HourAgo
2013-08-26 15:33:57.590089  -14,400     US/Eastern          2013-08-26 14:33:57.590089
</code>```

Results using 9.2 JDBC driver:

```<code>now                         date_part   current_setting     1HourAgo
2013-08-26 15:41:49.067903  0           UTC                 2013-08-26 14:41:49.067903
</code>```

This is causing a WHERE statement in a query to return incorrect results. For example,

```<code>WHERE end_time between now() - interval '1 hour' and now()
</code>```

works as expected using the 9,0 driver but returns no results using the 9,2 driver as the driver appears to be offsetting the value of end_time to match UTC (the client's time zone). The following is a workaround, but an ugly one:

```<code>WHERE end_time at time zone 'EDT' between now() - interval '1 hour' and now()
</code>```

Questions:

Has anyone else run across this before?

Is there an explanation for this change in behavior? I haven't been able to find anything in the JDBC release notes

Any advice on how to work around this other than rolling back the driver to an older version?

Thanks!

答:
Short version try:

```<code>TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
</code>```

Hi we ran across this issue with client and server timezone miss match We needed our unit tests to be run using "UTC". By looking at the source code for postgres jdbc driver (and this being test code) we "fixed" it by changing the TZ inside of the jvm before obtaining a connection.

Body:
I've run into an interesting challenge using a PostgreSQL database with the PostgreSQL JDBC driver. It seems that the latest version of the driver, 9.2, uses the client time zone when performing date/time matches.

This becomes a problem when the server (JasperReports Server) is set to UTC and the database server is set to US/Eastern.

If I run the following query from a client set to the UTC time zone I get different results using the 9.0 JDBC driver and the 9.2 JDBC driver.

select now(), extract(timezone FROM now()), current_setting('TIMEZONE'), now()-interval '1 hour' as "1HourAgo"

Results using 9.0 JDBC driver:

now                         date_part   current_setting     1HourAgo
2013-08-26 15:33:57.590089  -14,400     US/Eastern          2013-08-26 14:33:57.590089

Results using 9.2 JDBC driver:

now                         date_part   current_setting     1HourAgo
2013-08-26 15:41:49.067903  0           UTC                 2013-08-26 14:41:49.067903

This is causing a WHERE statement in a query to return incorrect results. For example,

WHERE end_time between now() - interval '1 hour' and now()

works as expected using the 9,0 driver but returns no results using the 9,2 driver as the driver appears to be offsetting the value of end_time to match UTC (the client's time zone). The following is a workaround, but an ugly one:

WHERE end_time at time zone 'EDT' between now() - interval '1 hour' and now()

Questions:

Has anyone else run across this before?

Is there an explanation for this change in behavior? I haven't been able to find anything in the JDBC release notes

Any advice on how to work around this other than rolling back the driver to an older version?

Thanks!

Body:
Short version try:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

Hi we ran across this issue with client and server timezone miss match We needed our unit tests to be run using "UTC". By looking at the source code for postgres jdbc driver (and this being test code) we "fixed" it by changing the TZ inside of the jvm before obtaining a connection.


问:
RegEx to find value in JSON
I need to write a RegEx on a JSON to match everything that starts with {$ and ends with }

I tried with /{(.*?)}/g and it seemingly works fine but if you see the image below it also matches the other text so how do I explicitly write a RegEx for my requirement

The reason for the ask is I need to find values with {$*} and replace them with a string

Below is my JSON

```<code>{
    "name": "{$StubName}",
    "request": {
        "method": "POST",
        "url": "/marks/{$Name}",
        "bodyPatterns": [
            {
                "equalToJson": "{\n    \"name\": \"{$RequestName}\",\n    \"job\": \"{$Role}\"\n}"
            }
        ]
    },
    "response": {
        "status": "201",
        "headers": {
            "Content-Type": "application/json"
        },
        "body": "{\n    \"name\": \"{$RequestName}\",\n    \"job\": \"{$Role}\",\n    \"id\": \"{$id}\",\n    \"createdAt\": \"{$Time}\"\n}"
    }
}
</code>```

答:
You can use \{\$\w*\}

Regex demo

Title: RegEx to find value in JSON

Body:
I need to write a RegEx on a JSON to match everything that starts with {$ and ends with }

I tried with /{(.*?)}/g and it seemingly works fine but if you see the image below it also matches the other text so how do I explicitly write a RegEx for my requirement

The reason for the ask is I need to find values with {$*} and replace them with a string

Below is my JSON

{
    "name": "{$StubName}",
    "request": {
        "method": "POST",
        "url": "/marks/{$Name}",
        "bodyPatterns": [
            {
                "equalToJson": "{\n    \"name\": \"{$RequestName}\",\n    \"job\": \"{$Role}\"\n}"
            }
        ]
    },
    "response": {
        "status": "201",
        "headers": {
            "Content-Type": "application/json"
        },
        "body": "{\n    \"name\": \"{$RequestName}\",\n    \"job\": \"{$Role}\",\n    \"id\": \"{$id}\",\n    \"createdAt\": \"{$Time}\"\n}"
    }
}

Body:
You can use \{\$\w*\}

Regex demo


问:
Image vertically aligned in div
I'm trying to center this image vertically inside a div. As you can see I've accomplished that, however, it's still pushed slightly towards the bottom of the div. I can't find any reasons why this would be and I've even tried a different image.

HTML:

```<code><div class="site-header">
            <img class="logo" src="CGLOGO.png" alt="logo">
</div>
</code>```

My CSS:

```<code>html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
}
.logo {
    max-height: 75%;
    vertical-align: middle;
  }
</code>```

Result:

答:
Just replace your .site-header class with the following

```<code>.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
    display: flex;
    align-items: center; /* For vertical alignment*/
    // justify-content: center; /* For horizontal alignment*/
}
</code>```

Title: Image vertically aligned in div

Body:
I'm trying to center this image vertically inside a div. As you can see I've accomplished that, however, it's still pushed slightly towards the bottom of the div. I can't find any reasons why this would be and I've even tried a different image.

HTML:

My CSS:

html, body {
    margin: 0;
    background: #F7B267;
}
.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
}
.logo {
    max-height: 75%;
    vertical-align: middle;
  }

Result:

Body:
Just replace your .site-header class with the following

.site-header {
    background: #eee;
    color: #555;
    height: 3.125em;
    line-height: 3.125em;
    margin-bottom: 1rem;
    display: flex;
    align-items: center; /* For vertical alignment*/
    // justify-content: center; /* For horizontal alignment*/
}


问:
Generate all possible correct sentences from a set of words
I have a set of 276 different words, I want to generate all possible correct sentences from them. It can be composed of two words only or more.

I used NLTK tagger to give every word a class. For instance, ('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN') but this technique has drowbacks when the words are independent from each other (An array of 276 words in my case).

If anyone has an idea of how I could do it, it would really help me. Thanks!

答:
You need to put correct grammar rules for making the correct required sentence.

For more info you can go through the following link:

https://www.nltk.org/book/ch08.html


问:
How to unit test email sending?
I would like to test my email sending functionality using .NET (C#) framework or any compatible library, any suggestion how to do it?</p>

答:
A quick and dirty solution I'm using for my integration tests is simply implement an email manager that stores the email in memory - which you can then access in your test assertions - instead of actually sending it. The maximum number of emails sent per test is currently two so I guess that's why it suffices in this case.

Of course you have to clean up this in-memory list of sent emails after every test.

Title: How to unit test email sending?


问:
Converting Spark UDF written in SCALA to JAVA
Below is my spark UD, can anyone help me to convert this into java?</p>

```<code>val customUDF = udf((array: Seq[String]) => {
    val newts = array.filter(_.nonEmpty)
    if  (newts.size == 0) null
    else newts.head
})
</code>```

答:
Something like:

UDF2 my_udf = new UDF2<WrappedArray<String>, String>() {
  public String call(WrappedArray<String> arr) throws Exception {
    String[] newts = arr.filter(_.nonEmpty)
    if (newts.length == 0) {
      return null
    } else { newts[0] }
  }
};

spark.udf().register("my_udf", my_udf, DataTypes.StringType);
```

Body:
Below is my spark UD, can anyone help me to convert this into java?

val customUDF = udf((array: Seq[String]) => {
    val newts = array.filter(_.nonEmpty)
    if  (newts.size == 0) null
    else newts.head
})


问:
Visual basic handle decimal comma
I'm trying to save variables into text files and the Czech typographic rules drives me crazy.
The program I'm tuning is dedicated to work on Czech localized computers where decimal comma is used but the VB is working with normal, standard decimal dot.

When loading files "US" decimals are loaded correctly and showed as Czech decimals. In TextBoxes "Czech" decimals are required. My problem is that program generates Czech decimals and require the "US" ones.

How can I force VB program to read comma as decimal sign instead of delimiter or how to export data with dots instead of commas?

Yes I can load 123,456 as a=123 and b=456 and then return value as a + b/1000 but is there more elegant solution?

答: Your trouble might be due to use of the Val function; that isn't international. The help text recommends the use of CDbl when converting from strings to numbers.

Title: Visual basic handle decimal comma


问:
Programmatically Recomputing Precise Part Volume From Third-Party Files Using Forge APIs
I'm looking for best practices and performance-guided recommendations for recomputing a model's volume when it's missing from the source file. This is in the context of a web application I am working to build that enables:

Uploading 3D models in a variety of file formats

Interacting with these models using the AutoDesk Viewer

Displaying mass properties, eg volume and surface area, alongside the viewer (subject of this post)

Background

Some file formats have very reliable volume information that is computed and written to the file by the authoring application. For these files, we can access volume as a property via AutoDesk Viewer.

Other formats, however, do not carry volume information - at least not in a manner that is openly accessible using tools other than the authoring application (prime example here is SolidWorks). This leaves us with a giant gap to fill - we need to recompute the model's volume using what's in the file.

Known Workarounds and Options

AutoDesk published a blog post detailing an approach for approximating model volume using triangles of the model inside the viewer. I think it's an ideal solution for use cases that can afford to trade accuracy for a bump in performance - and it centers everything in the viewer  making development and subsequent maintenance simpler. This application, however, cannot rely on such approximations. I'm left reviewing options for leveraging the AutoDesk Design Automation API to:

Spin up an instance of Inventor

Load the model file

Rely on iLogic to trigger a re-computation of the model's part properties (perhaps like this?)

Push that data back to my web application

Where I Need Help

My understanding is that an AppBundle and Activity are defined ahead of time and then every uploaded model would be submitted as a work item.

I am hoping for guidance in:

whether this is the only approach or whether there are other options worth considering

how best to orchestrate the end-to-end process from an order of operations/workflow standpoint to maximize performance

Current Thinking

For example, I'm thinking that my first step after the source file is uploaded is to immediately initialize two parallel processes: the first to translate the source file for the viewer, the second to spin up Inventor and trigger the related downstream process to get volume.

The other option I'm considering is handling all of the work in Inventor - and pushing out an SVF file to the viewer that's enriched with volume data. The advantage of this approach is that my frontend will have only one source for volume data, (it will be in the enriched SVF no matter whether it was supplied in the original file or not).

In an ideal world I'd be able to only invoke the Design Automation API when volume data is missing from the source file - but I'd only know that after translating the file and bringing it back to the viewer. Given that many of our files are created in SolidWorks and other high-end proprietary CAD platforms, my working hypothesis is that we'll be needing to fill in volume gaps more often than not.

答:
Your understanding is correct:

appbundle is simply a collection of files (binaries, data) encapsulating a specific Inventor/Revit/3dsMax/AutoCad plugin

activity is a kind of a job template specifying which application should be invoked, which appbundle should be loaded into the application, what inputs will be provided to the job, and what outputs will be generated

work item is then a specific instance of a job, binding the activity inputs and outputs to specific URLs

There is currently no other way to access the Design Automation functionality other then using these 3 types of entities.

I would suggest the following:

wherever possible, use the Design Automation for Inventor to compute the precise areas/volumes

for file formats that cannot be imported into Inventor or any other Design Automation engine, you could use tools like https://github.com/petrbroz/forge-convert-utils to parse the SVF and compute (a very rough estimate of) the area/surface from the triangular meshes; however, this will be quite computationally expensive, and imprecise


问:
How to avoid unnecessary re-rendering of RecyclerView when using Flowable (RxJava)?
Trying to implement MVVM with room flowable @ rxjava + retrofit2.

When the activity starts, I request a list of items from the repository. The repository retrieves them from the database (room) and returns Flowable to the ViewModel. At the same moment, the repository requests the current list from the API, and as soon as the result is returned, I delete the existing entries in the database and insert what arrived from the API.

The observer in activity, of course, updates recyclerview three times. Because of this, ui "blinks" when updating the list:
the list is not empty -> the list is empty -> the list is not empty.

After receiving the flowable from Room for the first time, the observer then receives an empty list (when deleting entries in the database) and then a new list after inserting it into the database from API.

How to avoid this behavior of RecyclerView? Is there any well-established best practice, true way, etc.?

PaymentRepository method for retrieving payment list:

```<code>private Flowable<List<Payment>> getPayments(Long accountId) {
    // requesting actual data from API
    paymentService.getPayments().flatMapCompletable(payments -> paymentDao
            .deleteAllByAccountId(accountId)
            .andThen(paymentDao.insert(payments))
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
    ).subscribe();

    // and return cached list from db
    return paymentDao.findPaidByAccountId(accountId)
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
</code>```

ViewModel

```<code>private CompositeDisposable disposable = new CompositeDisposable();
public MutableLiveData<Resource<List<Payment>>> result = new MutableLiveData<>(Resource.loading());

public PaymentListViewModel() {
    disposable.add(
            paymentRepository.getPayments().subscribe(
                    payments -> result.setValue(Resource.success(payments)),
                    throwable -> result.setValue(paymentService.parseError(throwable).toResource())
            )
    );
}
</code>```

Observer in Activity

```<code>viewModel.result.observe(this, resource -> {
    switch (resource.status) {
        case SUCCESS:
            adapter.setItems(resource.data);
            binding.preloader.setVisibility(View.GONE);
            break;
        case ERROR:
            Toast.makeText(this, resource.message, Toast.LENGTH_LONG).show();
            binding.preloader.setVisibility(View.GONE);
            break;
        case LOADING:
            binding.preloader.setVisibility(View.VISIBLE);
            break;
    }
});
</code>```

答:
I'm not a Room expert, maybe there is so RX-way to update values without emitting it into listeners.
But here is the way that doesn't request it:

```<code>private Flowable<List<Payment>> getPayments(Long accountId) {
    // requesting actual data from API
    Flowable<List<Payment>> request = paymentService.getPayments()
            .flatMapCompletable(payments -> paymentDao
                .deleteAllByAccountId(accountId)
                .andThen(paymentDao.insert(payments))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    );

    return paymentDao.findPaidByAccountId(accountId)
            .take(1)
            .switchMap(dbList -> request.startWith(dbList))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .distinctUntilChanged();
}
</code>```

in this scenario you take only first value from DB (take(1)) and then wait for the values from API.

switchMap (also could be flatMap here, no diff in this case) guaranty you that DB value will be first and only after that "listen" for API.

The only problem here if you suppose to update DB values somewhere else, while this Activity is running. In that case this updates will not be displayed.

Body:
Trying to implement MVVM with room flowable @ rxjava + retrofit2.

When the activity starts, I request a list of items from the repository. The repository retrieves them from the database (room) and returns Flowable to the ViewModel. At the same moment, the repository requests the current list from the API, and as soon as the result is returned, I delete the existing entries in the database and insert what arrived from the API.

The observer in activity, of course, updates recyclerview three times. Because of this, ui "blinks" when updating the list:
the list is not empty -> the list is empty -> the list is not empty.

After receiving the flowable from Room for the first time, the observer then receives an empty list (when deleting entries in the database) and then a new list after inserting it into the database from API.

How to avoid this behavior of RecyclerView? Is there any well-established best practice, true way, etc.?

PaymentRepository method for retrieving payment list:

private Flowable<List<Payment>> getPayments(Long accountId) {
    // requesting actual data from API
    paymentService.getPayments().flatMapCompletable(payments -> paymentDao
            .deleteAllByAccountId(accountId)
            .andThen(paymentDao.insert(payments))
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
    ).subscribe();

    // and return cached list from db
    return paymentDao.findPaidByAccountId(accountId)
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

ViewModel

private CompositeDisposable disposable = new CompositeDisposable();
public MutableLiveData<Resource<List<Payment>>> result = new MutableLiveData<>(Resource.loading());

public PaymentListViewModel() {
    disposable.add(
            paymentRepository.getPayments().subscribe(
                    payments -> result.setValue(Resource.success(payments)),
                    throwable -> result.setValue(paymentService.parseError(throwable).toResource())
            )
    );
}

Observer in Activity

viewModel.result.observe(this, resource -> {
    switch (resource.status) {
        case SUCCESS:
            adapter.setItems(resource.data);
            binding.preloader.setVisibility(View.GONE);
            break;
        case ERROR:
            Toast.makeText(this, resource.message, Toast.LENGTH_LONG).show();
            binding.preloader.setVisibility(View.GONE);
            break;
        case LOADING:
            binding.preloader.setVisibility(View.VISIBLE);
            break;
    }
});

Body:
I'm not a Room expert, maybe there is so RX-way to update values without emitting it into listeners.
But here is the way that doesn't request it:

private Flowable<List<Payment>> getPayments(Long accountId) {
    // requesting actual data from API
    Flowable<List<Payment>> request = paymentService.getPayments()
            .flatMapCompletable(payments -> paymentDao
                .deleteAllByAccountId(accountId)
                .andThen(paymentDao.insert(payments))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
    );

    return paymentDao.findPaidByAccountId(accountId)
            .take(1)
            .switchMap(dbList -> request.startWith(dbList))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .distinctUntilChanged();
}

in this scenario you take only first value from DB (take(1)) and then wait for the values from API.

switchMap (also could be flatMap here, no diff in this case) guaranty you that DB value will be first and only after that "listen" for API.

The only problem here if you suppose to update DB values somewhere else, while this Activity is running. In that case this updates will not be displayed.


问:
How to remove an item from an array in Vue.js
I am new to vue.js (2) and I am currently working on a simple event app. I've managed to add events but now I would like to delete events based on clicking on a button.

HTML

```<code>    <div class="list-group">

        <div class="list-group-item" v-for="event in events">
            <h4 class="list-group-item-heading">
                {{ event.name }}
            </h4>

            <h5>
                {{ event.date }}
            </h5>

            <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>
        </div>

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

JS(Vue)

```<code>new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

        deleteEvent: function(event) {
                this.events.splice(this.event);
        },

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});
</code>```

I've tried to pass the event to the function and than delete that one with the slice function, I thought it was that code for deleting some data from the array. What is the best en cleanest way to delete data from the array with a simpleb button and onclick event?

答:
Splice is the best to remove element from specific index. The given
  example is tested on console.

```<code>card = [1, 2, 3, 4];
card.splice(1,1);  // [2]
card   // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)
</code>```

startingIndex start from 0.

Body:
I am new to vue.js (2) and I am currently working on a simple event app. I've managed to add events but now I would like to delete events based on clicking on a button.

HTML

                {{ event.name }}

                {{ event.date }}

{{ event.description }}

            <button class="btn btn-xs btn-danger" @click="deleteEvent(event)">Delete</button>

JS(Vue)

new Vue ({
    el: '#app',

    data: {
        events: [
            {
                id: 1,
                name: 'Event 1',
                description: 'Just some lorem ipsum',
                date: '2015-09-10'
            },
            {
                id: 2,
                name: 'Event 2',
                description: 'Just another lorem ipsum',
                date: '2015-10-02'
            }
        ],

        event: { name: '', description: '', date: '' }
    },

    ready: function() {

    },

    methods: {

        deleteEvent: function(event) {
                this.events.splice(this.event);
        },

        // Adds an event to the existing events array
        addEvent: function() {
            if(this.event.name) {
                this.events.push(this.event);
                this.event = { name: '', description: '', date: '' };
            }
        }

    } // end of methods

});

I've tried to pass the event to the function and than delete that one with the slice function, I thought it was that code for deleting some data from the array. What is the best en cleanest way to delete data from the array with a simpleb button and onclick event?

Body:
Splice is the best to remove element from specific index. The given
  example is tested on console.

card = [1, 2, 3, 4];
card.splice(1,1);  // [2]
card   // (3) [1, 3, 4]
splice(startingIndex, totalNumberOfElements)

startingIndex start from 0.


问:
Read cookies inside a static method [ ASP MVC ]
I work on a ASP.NET MVC project, I create a Controller named AuthenticationController, this controller contains a static method called User_Access_Validation.

This method check some cookies values.

So that is method code :

```<code>public void User_Access_Validation()
{
 if (Request.Cookies["X_8"] == null || Request.Cookies["X_5"] == null || Request.Cookies["X_T"] == null)
   {
     Response.Redirect("/Login");
   }
}
</code>```

Everythings works good at now, but when I change this method to a static method I got these four errors in ErrorList in Visual Studio

```<code>Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property
</code>```

So please I need this method to be a static method, and fix this error

答:
As Scott Hannen Montionned in his answer, you should use Response and Request objects as parameters if you need to work with static method, but I think your code should have like this :

```<code>public static void User_Access_Validation(HttpRequestBase request, HttpResponseBase response)
{
 if (request.Cookies["X_8"] == null || request.Cookies["X_5"] == null || request.Cookies["X_T"] == null)
   {
     response.Redirect("/Login");
   }
}
</code>```

Whats new here ? is the parameters should base, HttpRequestBase and HttpResponseBase

I wish this help.

Body:
I work on a ASP.NET MVC project, I create a Controller named AuthenticationController, this controller contains a static method called User_Access_Validation.

This method check some cookies values.

So that is method code :

public void User_Access_Validation()
{
 if (Request.Cookies["X_8"] == null || Request.Cookies["X_5"] == null || Request.Cookies["X_T"] == null)
   {
     Response.Redirect("/Login");
   }
}

Everythings works good at now, but when I change this method to a static method I got these four errors in ErrorList in Visual Studio

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

Error   CS0120  An object reference is required for the non-static field, method, or property

So please I need this method to be a static method, and fix this error

Body:
As Scott Hannen Montionned in his answer, you should use Response and Request objects as parameters if you need to work with static method, but I think your code should have like this :

public static void User_Access_Validation(HttpRequestBase request, HttpResponseBase response)
{
 if (request.Cookies["X_8"] == null || request.Cookies["X_5"] == null || request.Cookies["X_T"] == null)
   {
     response.Redirect("/Login");
   }
}

Whats new here ? is the parameters should base, HttpRequestBase and HttpResponseBase

I wish this help.


答:
You can replace the body with this code:

```<code>    for (String value : hm.values()) {
        if (input.equals(value)) {
            return input;
        }
    }
    return null;
</code>```

you can't have code after return statement

.entrySet() returns Map.Entry and if you are not using <> operator getValue() returns Object instead of String

Body:
You can replace the body with this code:

    for (String value : hm.values()) {
        if (input.equals(value)) {
            return input;
        }
    }
    return null;

you can't have code after return statement

.entrySet() returns Map.Entry and if you are not using <> operator getValue() returns Object instead of String


问:
Sign extension from 16 to 32 bits in C
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

```<code>int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}
</code>```

The instruction (instr) is 32 bits and inside it I have a 16bit number.

答:
Try:</p>

```<code>int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    if (mask & instr) {
        value += 0xFFFF0000;
    }
    return value;
}
</code>```

Title: Sign extension from 16 to 32 bits in C

Body:
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}

The instruction (instr) is 32 bits and inside it I have a 16bit number.

Body:
Try:

int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    if (mask & instr) {
        value += 0xFFFF0000;
    }
    return value;
}


问:
Remove object from an array?
remove an object from an array is not working properly ,but it add object perfectly

```<code>const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
  let index = data.indexOf(selected);
  console.log(index);
  if (index !== -1) {
    data.splice(index, 1);
    setSelectedItems(data);
  } else {
    data.push(selected);
  }
} else {
  data.push(selected);
}
console.log("selected", selectedItems);

setSelectedItems(data);
}
</code>```

render button function add or remove on click it

```<code><div className="file-list">
  <MappedElement
   data={[{ _id: 1 }, { _id: 2 }]}
   renderElement={(value, index, arr) => {
   let check=selectedItems.some((obj) => obj._id === value._id);
   console.log("check", check);
   return (
    <DocumentCard key={index} className={file-list-item ${check ?
       "active" : ""}}
    onClick={() => addItem(value, arr, index)} /> ); }} />
 </div>
</code>```

答:
For a selectedItems array that looks like:

```<code>const selectedItems = [
    { _id: 1, /* other fields */ },
    { _id: 2, /* other fields */ },
    { _id: 3, /* other fields */ },
    /* other objects */
];
</code>```

And a selected object that looks like:

```<code>const selected = { _id: 1 };
</code>```

In order to perform the desired behavior, which is: if the element exists, remove it, else, add it, you can write the following:

```<code>// copy selected items with a fail-safe empty array
const data = selectedItems ? [...selectedItems] : [];
// find index of selected element
const removalIndex = data.findIndex(({ _id }) => (_id === selected._id));
// if selected element exists in data array, remove it
if (removalIndex !== -1) {
    data.splice(removalIndex, 1);
}
// if selected element doesn't exist in data array, add it
else {
    data.push(selected);
}
// update selected elements
setSelectedItems(data);
</code>```

NOTE: if your array of selected items contains duplicates, meaning multiple objects that contain the same value for _id, then this approach will be removing only the first instance of those. If you want to remove all of them, you'll have to use a loop or recursivity.

Title: Remove object from an array?

Body:
remove an object from an array is not working properly ,but it add object perfectly

const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
  let index = data.indexOf(selected);
  console.log(index);
  if (index !== -1) {
    data.splice(index, 1);
    setSelectedItems(data);
  } else {
    data.push(selected);
  }
} else {
  data.push(selected);
}
console.log("selected", selectedItems);

setSelectedItems(data);
}

render button function add or remove on click it

  <MappedElement
   data={[{ _id: 1 }, { _id: 2 }]}
   renderElement={(value, index, arr) => {
   let check=selectedItems.some((obj) => obj._id === value._id);
   console.log("check", check);
   return (
    <DocumentCard key={index} className={file-list-item ${check ?
       "active" : ""}}
    onClick={() => addItem(value, arr, index)} /> ); }} />

Body:
For a selectedItems array that looks like:

const selectedItems = [
    { _id: 1, /* other fields */ },
    { _id: 2, /* other fields */ },
    { _id: 3, /* other fields */ },
    /* other objects */
];

And a selected object that looks like:

const selected = { _id: 1 };

In order to perform the desired behavior, which is: if the element exists, remove it, else, add it, you can write the following:

// copy selected items with a fail-safe empty array
const data = selectedItems ? [...selectedItems] : [];
// find index of selected element
const removalIndex = data.findIndex(({ _id }) => (_id === selected._id));
// if selected element exists in data array, remove it
if (removalIndex !== -1) {
    data.splice(removalIndex, 1);
}
// if selected element doesn't exist in data array, add it
else {
    data.push(selected);
}
// update selected elements
setSelectedItems(data);

NOTE: if your array of selected items contains duplicates, meaning multiple objects that contain the same value for _id, then this approach will be removing only the first instance of those. If you want to remove all of them, you'll have to use a loop or recursivity.


问:
How to evaluate a DCG parser/generator in Prolog?
I'm having trouble understanding the syntax and use of DCG in Prolog. The code I'm working with is a type of parser for a grammar of the kind "a=1*2+(3-4)/5", here's a selection of it:

```<code>factor(factor(N)) --> int(N).

int(N):- number(N), N > 0, N < 10.
</code>```

When running it, it looks like this

```<code>| ?- int(8).

yes

| ?- factor(8).

! Existence error in user:factor/1

! procedure user:factor/1 does not exist

! goal:  user:factor(8)

| ?- factor([],[],[]).

no
</code>```

So factor wants 3 arguments. However, I cannot understand what these arguments are meant to represent, nor what I need to put in to make the query say 'yes'?

答:
To run a DCG parser you will need to use either phrase/2 or phrase/3:

```<code>phrase(factor(8), Text).
phrase(factor(N), "123", Rest).
</code>```

Third argument of phrase is the unconsumed rest of the input (or possible complement of the output considering DCG's generative skills).

Body:
I'm having trouble understanding the syntax and use of DCG in Prolog. The code I'm working with is a type of parser for a grammar of the kind "a=1*2+(3-4)/5", here's a selection of it:

factor(factor(N)) --> int(N).

int(N):- number(N), N > 0, N < 10.

When running it, it looks like this

| ?- int(8).

yes

| ?- factor(8).

! Existence error in user:factor/1

! procedure user:factor/1 does not exist

! goal:  user:factor(8)

| ?- factor([],[],[]).

no

So factor wants 3 arguments. However, I cannot understand what these arguments are meant to represent, nor what I need to put in to make the query say 'yes'?

Body:
To run a DCG parser you will need to use either phrase/2 or phrase/3:

phrase(factor(8), Text).
phrase(factor(N), "123", Rest).

Third argument of phrase is the unconsumed rest of the input (or possible complement of the output considering DCG's generative skills).


问:
"No rule to make target" error in cmake when linking to shared library
In Ubuntu, I have downloaded a third-party shared library, mylibrary.so, which I have placed in the directory /home/karnivaurus/Libraries. I have also placed the associated header file, myheader.h, in the directory /home/karnivaurus/Headers. I now want to link to this library in my C++ code, using CMake. Here is my CMakeLists.txt file:

```<code>cmake_minimum_required(VERSION 2.0.0)

project(DemoProject)

include_directories(/home/karnivaurus/Headers)

add_executable(demo demo.cpp)

target_link_libraries(demo /home/karnivaurus/Libraries/mylibrary)
</code>```

However, this gives me the error message:

```<code>:-1: error: No rule to make target `/home/karnivaurus/Libraries/mylibrary', needed by `demo'.  Stop.
</code>```

What's going on?

答:
While the other answer posted here is valid, it is out-dated. CMake now provides better solutions for using a pre-built external library in your code. In fact, CMake itself even discourages the use of link_directories() in its documentation.

The target_link_libraries() command takes very specific syntax for linking to an external library. A more modern solution is to create an IMPORTED CMake target for your external library:

```<code>add_library(MyExternalLib SHARED IMPORTED)

# Provide the full path to the library, so CMake knows where to find it.
set_target_properties(MyExternalLib PROPERTIES IMPORTED_LOCATION /home/karnivaurus/Libraries/mylibrary.so)
</code>```

You can then use this imported CMake target later on in your code, and link it to your other targets:

```<code>target_link_libraries(demo PRIVATE MyExternalLib)
</code>```

For other ways to use an external third-party library in your CMake code, see the responses here.

Body:
In Ubuntu, I have downloaded a third-party shared library, mylibrary.so, which I have placed in the directory /home/karnivaurus/Libraries. I have also placed the associated header file, myheader.h, in the directory /home/karnivaurus/Headers. I now want to link to this library in my C++ code, using CMake. Here is my CMakeLists.txt file:

cmake_minimum_required(VERSION 2.0.0)

project(DemoProject)

include_directories(/home/karnivaurus/Headers)

add_executable(demo demo.cpp)

target_link_libraries(demo /home/karnivaurus/Libraries/mylibrary)

However, this gives me the error message:

:-1: error: No rule to make target `/home/karnivaurus/Libraries/mylibrary', needed by `demo'.  Stop.

What's going on?

Body:
While the other answer posted here is valid, it is out-dated. CMake now provides better solutions for using a pre-built external library in your code. In fact, CMake itself even discourages the use of link_directories() in its documentation.

The target_link_libraries() command takes very specific syntax for linking to an external library. A more modern solution is to create an IMPORTED CMake target for your external library:

add_library(MyExternalLib SHARED IMPORTED)

# Provide the full path to the library, so CMake knows where to find it.
set_target_properties(MyExternalLib PROPERTIES IMPORTED_LOCATION /home/karnivaurus/Libraries/mylibrary.so)

You can then use this imported CMake target later on in your code, and link it to your other targets:

target_link_libraries(demo PRIVATE MyExternalLib)

For other ways to use an external third-party library in your CMake code, see the responses here.


问:
How to join two CSV files by a temporary common column in awk?
I have two CSV files in the form of

file1

```<code>A,44
A,21
B,65
C,79
</code>```

file2

```<code>A,7
B,4
C,11
</code>```

I used awk as

```<code>awk -F, 'NR==FNR{a[$1]=$0;next} ($1 in a){print a[$1]","$2 }' file1.csv file2.csv
</code>```

producing

```<code>A,44,7
A,21,7
B,65,4
C,79,11
</code>```

a[$1] prints the entire line from file1. How can I omit the first columns in both files (the first column is only used to match the second columns) to produce:

```<code>44,7
21,7
65,4
79,11
</code>```

In other words, how can I pass the columns from the first file to the print block, as $2 does for the second file?

答:
Could you please try following, tested and written on shown samples only.

```<code>awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1]=$2;next} ($1 in a){print $2,a[$1]}' file2 file1
</code>```

Explanation: Adding detailed explanation for above.

```<code>awk '                     ##Starting awk program from here.
BEGIN{                    ##Starting BEGIN section from here.
  FS=OFS=","              ##Setting field and output field separator as comma here.
}
FNR==NR{                  ##Checking condition FNR==NR which will be TRUE when file2 is being read.
  a[$1]=$2                ##Creating array a with index $1 and value is $2 from current line.
  next                    ##next will skip all further statement from here.
}
($1 in a){                ##Statements from here will be executed when file1 is being read and it's checking if $1 is present in array a then do following.
  print $2,a[$1]          ##Printing 2nd field and value of array a with index $1 here.
}
' file2 file1             ##Mentioning Input_file names here.
</code>```

Output will be as follows for shown samples.

```<code>44,7
21,7
65,4
79,11
</code>```

2nd solution: More Generic solution, where considering that your both Input_files could have duplicates in that case it will print 1st value of A in Input_file1 to first value of Input_file2 and so on.

```<code>awk '
BEGIN{
  FS=OFS=","
}
FNR==NR{
  a[$1]
  b[$1,++c[$1]]=$2
  next
}
($1 in a){
  print $2,b[$1,++d[$1]]
}
' file2 file1
</code>```

Body:
I have two CSV files in the form of

file1

A,44
A,21
B,65
C,79

file2

A,7
B,4
C,11

I used awk as

awk -F, 'NR==FNR{a[$1]=$0;next} ($1 in a){print a[$1]","$2 }' file1.csv file2.csv

producing

A,44,7
A,21,7
B,65,4
C,79,11

a[$1] prints the entire line from file1. How can I omit the first columns in both files (the first column is only used to match the second columns) to produce:

44,7
21,7
65,4
79,11

In other words, how can I pass the columns from the first file to the print block, as $2 does for the second file?

Body:
Could you please try following, tested and written on shown samples only.

awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1]=$2;next} ($1 in a){print $2,a[$1]}' file2 file1

Explanation: Adding detailed explanation for above.

awk '                     ##Starting awk program from here.
BEGIN{                    ##Starting BEGIN section from here.
  FS=OFS=","              ##Setting field and output field separator as comma here.
}
FNR==NR{                  ##Checking condition FNR==NR which will be TRUE when file2 is being read.
  a[$1]=$2                ##Creating array a with index $1 and value is $2 from current line.
  next                    ##next will skip all further statement from here.
}
($1 in a){                ##Statements from here will be executed when file1 is being read and it's checking if $1 is present in array a then do following.
  print $2,a[$1]          ##Printing 2nd field and value of array a with index $1 here.
}
' file2 file1             ##Mentioning Input_file names here.

Output will be as follows for shown samples.

44,7
21,7
65,4
79,11

2nd solution: More Generic solution, where considering that your both Input_files could have duplicates in that case it will print 1st value of A in Input_file1 to first value of Input_file2 and so on.

awk '
BEGIN{
  FS=OFS=","
}
FNR==NR{
  a[$1]
  b[$1,++c[$1]]=$2
  next
}
($1 in a){
  print $2,b[$1,++d[$1]]
}
' file2 file1


问:
How can i install google cloud sdk(gcloud cli) on docker container using pip?
How can i install google cloud sdk(gcloud cli) on docker container using pip ? Is it possible ?
I want to install gcloud sdk on Google Cloud Run docker container.

For example like this ⬇ :

```<code>awscli==any version
gcloud-sdk???
</code>```

requirement.txt

答:
Not with pip, but here is the recipe from https://cloud.google.com/sdk/docs/downloads-apt-get

```<code>echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

apt-get install apt-transport-https ca-certificates gnupg curl -y

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -

apt-get update && apt-get install google-cloud-sdk -y
</code>```

Depending on your use case you might then need to activate the service account key like:

```<code>gcloud auth activate-service-account --key-file=my-service-account-key.json
</code>```

Body:
How can i install google cloud sdk(gcloud cli) on docker container using pip ? Is it possible ?
I want to install gcloud sdk on Google Cloud Run docker container.

For example like this ⬇ :

awscli==any version
gcloud-sdk???

requirement.txt

Body:
Not with pip, but here is the recipe from https://cloud.google.com/sdk/docs/downloads-apt-get

echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

apt-get install apt-transport-https ca-certificates gnupg curl -y

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -

apt-get update && apt-get install google-cloud-sdk -y

Depending on your use case you might then need to activate the service account key like:

gcloud auth activate-service-account --key-file=my-service-account-key.json