问:
How can I get coordinates of an SVG by clicking on some point?
I am new to SVG and I am trying to generate an event in order to get the coordinates of the click when I click on the SVG. I have multiple questions:

I am using angular and I am not sure if this is possible keeping my function in the TS file or I have to create a  or something. I have also seen that some people use jQuery, but I am not sure what this technology is. It is possible to it in angular?

I have tried using the OnClick attribute, from the SVG components, but I would like to know if there is possible to cover al the SVG space (in case this is not possible I may create a rectangle from all the viewbox dimensions with opacity 0?)

This is what I have tried as I have done before with click events from other components:

```<code><rect [attr.x]="esquina_cuadriculaX" [attr.y]="esquina_cuadriculaY" [attr.width] = "ancho_cuadricula"
[attr.height] = "alto_cuadricula" fill="none"
stroke="black" stroke-width="350" [attr.onclick]="clicked($event)" />
</code>```

And on the TypeScript file I have the function itself:

```<code>  clicked($event :any){
    console.log("x: "+$event.clientX+" y:"+$event.clientY);
}
</code>```

But I get the error "Property '$event' does not exist on type 'GraficaComponent'." where GraficaComponent is of course my component.

Any help is appreciated.

答:
try binding your event-handler like this (use round parathesis an correct event name 'click'):</p>
```<code><rect [attr.x]="esquina_cuadriculaX" [attr.y]="esquina_cuadriculaY" [width] = "ancho_cuadricula"
[height] = "alto_cuadricula" fill="none"
stroke="black" stroke-width="350" (click)="clicked($event)" />
</code>```

Body:
I am new to SVG and I am trying to generate an event in order to get the coordinates of the click when I click on the SVG. I have multiple questions:

I am using angular and I am not sure if this is possible keeping my function in the TS file or I have to create a  or something. I have also seen that some people use jQuery, but I am not sure what this technology is. It is possible to it in angular?

I have tried using the OnClick attribute, from the SVG components, but I would like to know if there is possible to cover al the SVG space (in case this is not possible I may create a rectangle from all the viewbox dimensions with opacity 0?)

This is what I have tried as I have done before with click events from other components:

<rect [attr.x]="esquina_cuadriculaX" [attr.y]="esquina_cuadriculaY" [attr.width] = "ancho_cuadricula"
[attr.height] = "alto_cuadricula" fill="none"
stroke="black" stroke-width="350" [attr.onclick]="clicked($event)" />

And on the TypeScript file I have the function itself:

  clicked($event :any){
    console.log("x: "+$event.clientX+" y:"+$event.clientY);
}

But I get the error "Property '$event' does not exist on type 'GraficaComponent'." where GraficaComponent is of course my component.

Any help is appreciated.

Body:
try binding your event-handler like this (use round parathesis an correct event name 'click'):

<rect [attr.x]="esquina_cuadriculaX" [attr.y]="esquina_cuadriculaY" [width] = "ancho_cuadricula"
[height] = "alto_cuadricula" fill="none"
stroke="black" stroke-width="350" (click)="clicked($event)" />


来源: stackexchange

问:
How do I make a String inside annotation depend on active profile?
I have an entity that needs to be mapped to a DynamoDBTable. We have two tables, one for dev environment and one for production. How can I change the string within an annotation depending on my current active profile?

In the dev enviroment I want the entity to start with this:

```<code>@DynamoDBTable(tableName = "my-dynamodbtable-dev")
public class MyEntity{
</code>```

In the prod enviroment, I want it to start with this:

```<code>@DynamoDBTable(tableName = "my-dynamodbtable-prod")
public class MyEntity{
</code>```

答:
Looks like you are creating separate table for DEV and PROD in same server. Ideally separate servers should be used for DEV and PROD.

Follow below steps to achieve your requirement in same server with different table for DEV and PROD:

Create an environment configuration as below:

```<code>(DEV)
    spring:
      profiles: DEV
    myEntity:
      tableName: my-dynamodbtable-dev

(PROD)
    spring:
      profiles: PROD
    myEntity:
      tableName: my-dynamodbtable-prod
</code>```

Configure table as below to take table name at run time:

```<code>@DynamoDBTable(tableName = "${myEntity.tableName}")
public class MyEntity{
...
}
</code>```

Provide default name as well like below to avoid statup issue in case config myEntity.table not available.

```<code>@DynamoDBTable(tableName = "${myEntity.tableName:my-dynamodbtable-dev}")
public class MyEntity{
...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an entity that needs to be mapped to a DynamoDBTable. We have two tables, one for dev environment and one for production. How can I change the string within an annotation depending on my current active profile?

In the dev enviroment I want the entity to start with this:

@DynamoDBTable(tableName = "my-dynamodbtable-dev")
public class MyEntity{

In the prod enviroment, I want it to start with this:

@DynamoDBTable(tableName = "my-dynamodbtable-prod")
public class MyEntity{

Body:
Looks like you are creating separate table for DEV and PROD in same server. Ideally separate servers should be used for DEV and PROD.

Follow below steps to achieve your requirement in same server with different table for DEV and PROD:

Create an environment configuration as below:

(DEV)
    spring:
      profiles: DEV
    myEntity:
      tableName: my-dynamodbtable-dev

(PROD)
    spring:
      profiles: PROD
    myEntity:
      tableName: my-dynamodbtable-prod

Configure table as below to take table name at run time:

@DynamoDBTable(tableName = "${myEntity.tableName}")
public class MyEntity{
...
}

Provide default name as well like below to avoid statup issue in case config myEntity.table not available.

@DynamoDBTable(tableName = "${myEntity.tableName:my-dynamodbtable-dev}")
public class MyEntity{
...
}


问:
adding entries to NSMutableDictionary
I'm having trouble with adding dictionary's to a nsmutabledictionary. Can anyone see what I'm doing wrong?</p>

```<code>@interface viewMap : UIViewController<MKMapViewDelegate> {

     NSMutableDictionary *onclickDic;

}

@property (nonatomic, retain) NSMutableDictionary *onclickDic;
@end

@implementation viewMap
@synthesize onclickDic;

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    NSString *pushLat   = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude];
    NSString *pushLng   = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude];

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]];

    NSDictionary *toPush    = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];

    NSLog(@"toPush is %@", toPush); // this one is correct and works

    [self.onclickDic addEntriesFromDictionary:toPush];

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null)
}
@end
</code>```

答:
It looks like you don't ever create the onclickDic.  You also never release it.

Try adding these methods:

```<code>- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
    self = [super initWithNibName:nibName bundle:nibBundle];
    if (self)
    {
        onclickDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [onclickDict release];

    [super dealloc];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: adding entries to NSMutableDictionary

Body:
I'm having trouble with adding dictionary's to a nsmutabledictionary. Can anyone see what I'm doing wrong?

@interface viewMap : UIViewController<MKMapViewDelegate> {

     NSMutableDictionary *onclickDic;

}

@property (nonatomic, retain) NSMutableDictionary *onclickDic;
@end

@implementation viewMap
@synthesize onclickDic;

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    NSString *pushLat   = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude];
    NSString *pushLng   = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude];

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]];

    NSDictionary *toPush    = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];

    NSLog(@"toPush is %@", toPush); // this one is correct and works

    [self.onclickDic addEntriesFromDictionary:toPush];

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null)
}
@end

Body:
It looks like you don't ever create the onclickDic.  You also never release it.

Try adding these methods:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
    self = [super initWithNibName:nibName bundle:nibBundle];
    if (self)
    {
        onclickDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [onclickDict release];

    [super dealloc];
}


问:
Parse a string between 2 delimiters
I added the following line but I am getting an error "Invalid length parameter passed to the LEFT or SUBSTRING function":

```<code>substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
</code>```

It will work if I remove the ">", so i am at a lost of my next step

```<code>SELECT *
from RawAnalog RA
CROSS APPLY (
            VALUES(
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2)),
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3)),
                substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
                )
            )
                V(TYPE,POINT,SITE )
Where
          V.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlvCmd','SaStP', 'SaCFM')
          and ra.UTCDateTime = '2021-01-01 00:15:00.000'
ORDER by V.POINT asc
</code>```

Desired output would be except for site I would just want "Skyline":
output

答:
Use STUFF and CHARINDEX to remove the leading characters, and the LEFT and CHARINDEX to remove the trailing characters:

SELECT LEFT(S.YourString,ISNULL(NULLIF(CHARINDEX('-',S.YourString),0)-1,LEN(S.YourString))) AS NewString
FROM (VALUES('XRDCWPDBSADX02:SKYLINE-NAE04/FC-1.041020FE.ChwVlvCmd.#85'))V(YourString)
     CROSS APPLY (VALUES(STUFF(V.YourString,1,CHARINDEX(':',V.YourString),'')))S(YourString);
```

Title: Parse a string between 2 delimiters

Body:
I added the following line but I am getting an error "Invalid length parameter passed to the LEFT or SUBSTRING function":

substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)

It will work if I remove the ">", so i am at a lost of my next step

SELECT *
from RawAnalog RA
CROSS APPLY (
            VALUES(
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),2)),
                reverse(PARSENAME(REPLACE(REVERSE(pointname),'.','.'),3)),
                substring(PointName, CHARINDEX(':',PointName)+1, CHARINDEX('-',PointName)-CHARINDEX(':',PointName)-1)
                )
            )
                V(TYPE,POINT,SITE )
Where
          V.Point IN ('MaTmp', 'OaTmp', 'SaTmp', 'ChwVlvCmd','SaStP', 'SaCFM')
          and ra.UTCDateTime = '2021-01-01 00:15:00.000'
ORDER by V.POINT asc

Desired output would be except for site I would just want "Skyline":
output


问:
FindOneAndUpdate overriding and updating only the first id
I am simply trying to update the content according to the id, but whichever id I am using, it updates only the first id by overriding it.
The flow goes as routes => controller => repository
Following is the code:
Routes =>

```<code>router.post("/:pageId/content", async (req, res, next) => {
  try {
    const pageId = req.params;
    const pageContent = req.body;
    if (!pageId || !pageContent) {
      throw {
        statusCode: 200,
        customMessage: "All parameters are required"
      };
    }
    const result: any = await webpageController.createContent(
      pageId,
      pageContent
    );
    if (result.isError) {
      throw result.error;
    }
    res.status(200).json(result.data);
  } catch (error) {
    next(error);
  }
});
</code>```

Controller =>

```<code>const createContent = async (pageId: any, pageContent: any) => {
  try {
    // calls repository to create content
    const result = await webpageRepository.createContent(pageId, pageContent);
    // if result is not success, throw error
    if (!result.success) {
      throw {
        statusCode: 400,
        customMessage: "Unable to create web page content"
      };
    }

    return {
      isError: false,
      data: result.data
    };
</code>```

Repository =>

```<code>export const createContent = async (pageId: any, content: any) => {
  try {
    const result = await webpage.findOneAndUpdate(pageId, { content });
    return {
      data: result,
      success: true
    };
  } catch (error) {
    logger.error(
      `at:"repositories/webpage/createContent" => ${JSON.stringify(error)}`
    );
    return {
      success: false
    };
  }
};
</code>```

Here it can be seen that the id I have used in the route and the id getting updated is different.
What am I doing wrong here?

Following is the schema:

```<code>const mongoose = require('mongoose');
const { Schema } = mongoose;

const webpage = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      maxlength: 25,
    },
    slug: {
      type: String,
    //   required: true,
    },
    url: {
      type: String,
      required: true,
      unique: true
    },
    content: Object,
  },
  {
    timestamps: true,
  },
);

export default mongoose.model('webpages', webpage);
</code>```

答:
This worked for me</p>
```<code>const result = await webpage.findOneAndUpdate(   {_id:pageId.pageId} , { content });
</code>```

Body:
I am simply trying to update the content according to the id, but whichever id I am using, it updates only the first id by overriding it.
The flow goes as routes => controller => repository
Following is the code:
Routes =>

router.post("/:pageId/content", async (req, res, next) => {
  try {
    const pageId = req.params;
    const pageContent = req.body;
    if (!pageId || !pageContent) {
      throw {
        statusCode: 200,
        customMessage: "All parameters are required"
      };
    }
    const result: any = await webpageController.createContent(
      pageId,
      pageContent
    );
    if (result.isError) {
      throw result.error;
    }
    res.status(200).json(result.data);
  } catch (error) {
    next(error);
  }
});

Controller =>

const createContent = async (pageId: any, pageContent: any) => {
  try {
    // calls repository to create content
    const result = await webpageRepository.createContent(pageId, pageContent);
    // if result is not success, throw error
    if (!result.success) {
      throw {
        statusCode: 400,
        customMessage: "Unable to create web page content"
      };
    }

    return {
      isError: false,
      data: result.data
    };

Repository =>

export const createContent = async (pageId: any, content: any) => {
  try {
    const result = await webpage.findOneAndUpdate(pageId, { content });
    return {
      data: result,
      success: true
    };
  } catch (error) {
    logger.error(
      `at:"repositories/webpage/createContent" => ${JSON.stringify(error)}`
    );
    return {
      success: false
    };
  }
};

Here it can be seen that the id I have used in the route and the id getting updated is different.
What am I doing wrong here?

Following is the schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const webpage = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      maxlength: 25,
    },
    slug: {
      type: String,
    //   required: true,
    },
    url: {
      type: String,
      required: true,
      unique: true
    },
    content: Object,
  },
  {
    timestamps: true,
  },
);

export default mongoose.model('webpages', webpage);

Body:
This worked for me

const result = await webpage.findOneAndUpdate(   {_id:pageId.pageId} , { content });


问:
PL/SQL: iterator value from FOR loop as a variable not working
I don't understand behaviour of my code.
Why when I have
 select min(i.column_name) into value_min from EMPLOYEES;  in my code (see belowe) I get error but if i put in this palce string with correct name of table I get result
 select min(SALARY) into value_min from EMPLOYEES;

```<code>
declare
    cursor c_column_name is select column_name, data_type from USER_TAB_COLUMNS where table_name = 'EMPLOYEES';
/***************************
(...)
SALARY          NUMBER
(...)
***************************/
    value_name_col varchar2(100);
    value_min number;
    value_max number;
    value_result number;
    type t_rekord is table of EMPLOYEES%ROWTYPE INDEX BY BINARY_INTEGER;

begin
    for i IN c_column_name loop
    --DBMS_OUTPUT.PUT_LINE(i.column_name);
        if i.data_type = 'NUMBER' and i.column_name = 'SALARY' then

--        coment line get ERROR
--        select min(i.column_name) into value_min from EMPLOYEES;
--        select max(i.column_name) into value_max from EMPLOYEES;

--      code below get results
        select min(SALARY) into value_min from EMPLOYEES;
        select max(SALARY) into value_max from EMPLOYEES;

        select round(dbms_random.value(value_min,value_max),2) into value_result from dual;
        DBMS_OUTPUT.PUT_LINE(i.column_name || ' = ' || value_result);
        end if;
    end loop;
end;

</code>```

Error which I get:

```<code>ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 27
06502. 00000 -  "PL/SQL: numeric or value error%s"
</code>```

I prepare this for show you how my problem look like, i'ts not exactly what I do.

答:
If you want to specify table or column names using a variable, you need dynamic SQL (e.g. with execute immediate) as Jeff Holt commented.

Try this instead:

```<code>execute immediate 'select min(' || i.column_name
  || '), max(' || i.column_name
  || ') from EMPLOYEES' into value_min, value_max;
</code>```

You're getting a "numeric or value error" because it's doing select min('SALARY') and then it tries to save the output (the string 'SALARY') into value_min, which is a NUMBER data type.

Body:
I don't understand behaviour of my code.
Why when I have
 select min(i.column_name) into value_min from EMPLOYEES;  in my code (see belowe) I get error but if i put in this palce string with correct name of table I get result
 select min(SALARY) into value_min from EMPLOYEES;

declare
    cursor c_column_name is select column_name, data_type from USER_TAB_COLUMNS where table_name = 'EMPLOYEES';
/***************************
(...)
SALARY          NUMBER
(...)
***************************/
    value_name_col varchar2(100);
    value_min number;
    value_max number;
    value_result number;
    type t_rekord is table of EMPLOYEES%ROWTYPE INDEX BY BINARY_INTEGER;

begin
    for i IN c_column_name loop
    --DBMS_OUTPUT.PUT_LINE(i.column_name);
        if i.data_type = 'NUMBER' and i.column_name = 'SALARY' then

--        coment line get ERROR
--        select min(i.column_name) into value_min from EMPLOYEES;
--        select max(i.column_name) into value_max from EMPLOYEES;

--      code below get results
        select min(SALARY) into value_min from EMPLOYEES;
        select max(SALARY) into value_max from EMPLOYEES;

        select round(dbms_random.value(value_min,value_max),2) into value_result from dual;
        DBMS_OUTPUT.PUT_LINE(i.column_name || ' = ' || value_result);
        end if;
    end loop;
end;

Error which I get:

ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 27
06502. 00000 -  "PL/SQL: numeric or value error%s"

I prepare this for show you how my problem look like, i'ts not exactly what I do.

Body:
If you want to specify table or column names using a variable, you need dynamic SQL (e.g. with execute immediate) as Jeff Holt commented.

Try this instead:

execute immediate 'select min(' || i.column_name
  || '), max(' || i.column_name
  || ') from EMPLOYEES' into value_min, value_max;

You're getting a "numeric or value error" because it's doing select min('SALARY') and then it tries to save the output (the string 'SALARY') into value_min, which is a NUMBER data type.


问:
Submitting HTML in Pardot form
We are starting to leverage the Pardot API by submitting our custom, in-house forms to a Pardot form handler.  From our form we want to send a small chunk of HTML in a hidden field and have it end up in a Pardot field - and have that HTML display rendered in the Pardot backend.  Is this possible?

Thanks

答: Hidden Fields (on Pardot Forms, or via javascript on a Form Handler) can be pass information from the form front end to the Pardot database.  However,the Pardot backed does not support rich text / html as a data type.</p>

Title: Submitting HTML in Pardot form


问:
How to remove LOST.DIR folder from USB Mass Storage in Android programmatically
I copy files from Android internal storage to USB drive, folder LOST.DIR always is created by system.
How can I remove this folder programmatically

I use library libaums to handle communicate with USB
I tried to delete this folder after copy but USB get error

    private fun exportOnlyFilesToUsb(fileSystem: FileSystem, file: File) {
        val root = fileSystem.rootDirectory
        if (!file.isDirectory) {
            root.search(file.name)?.delete()
            val targetFile = root.createFile(file.name)
            copyFile(file, targetFile)
            return
        }
        file.listFiles()?.forEach {
            exportOnlyFilesToUsb(fileSystem, it)
        }
    }

    private fun copyFile(file: File, usbFile: UsbFile) {
        if (file.isDirectory || usbFile.isDirectory) return
        FileInputStream(file).use { input ->
            UsbFileOutputStream(usbFile).use { output ->
                input.copyTo(output)
            }
        }
    }

// Then I delete
root.search(LOST_DIR)?.delete()
```

答:
First check if you have write access with File.canWrite().

I think you have no write access to removable media since Android KitKat.

You would need SAF and let the user select the directory with ACTION_OPEN_DOCUMENT_TREE.

Yes it is a nuisance as the medium will be used in other devices which sometimes dont like that directory.

The same counts for an Android directory that is often created.

Yes remove all. Nobody asked for it.


问:
RTCClient : You have to be logged in in order to use Chat API
Calling below code to start video call using QuickBlox, But getting 'You have to be logged in in order to use Chat API' error even after calling login API.</p>
```<code>        //Authorise user/Create session
    QBRequest.logIn(withUserLogin: userDef.value(forKey: "userID") as! String, password: ConstantObjectFile.quickBloxPassWord, successBlock: { [self] (response, user) in
        print(response)
        print(user)

        //Initiate call
        let idd = "125914156"//self.contactListArray[sender.tag].following_user_id
        let myNumber = Int(idd)!
        let opponentsIDs = [myNumber]
        let newSession = QBRTCClient.instance().createNewSession(withOpponents: opponentsIDs as [NSNumber], with: .video)
        // userInfo - the custom user information dictionary for the call. May be nil.

        let userInfo = ["key":"value"] // optional
        newSession.startCall(userInfo)

    }, errorBlock: { (response) in
        print(response)
    })
</code>```

答:
You have to be connected to chat before creating a call session. Here is the guide - https://docs.quickblox.com/docs/ios-chat-connection#connect-to-chat-server

QuickBlox WebRTC signaling goes over XMPP protocol (that's why you have to be connected to chat first)

Body:
Calling below code to start video call using QuickBlox, But getting 'You have to be logged in in order to use Chat API' error even after calling login API.

        //Authorise user/Create session
    QBRequest.logIn(withUserLogin: userDef.value(forKey: "userID") as! String, password: ConstantObjectFile.quickBloxPassWord, successBlock: { [self] (response, user) in
        print(response)
        print(user)

        //Initiate call
        let idd = "125914156"//self.contactListArray[sender.tag].following_user_id
        let myNumber = Int(idd)!
        let opponentsIDs = [myNumber]
        let newSession = QBRTCClient.instance().createNewSession(withOpponents: opponentsIDs as [NSNumber], with: .video)
        // userInfo - the custom user information dictionary for the call. May be nil.

        let userInfo = ["key":"value"] // optional
        newSession.startCall(userInfo)

    }, errorBlock: { (response) in
        print(response)
    })


问:
How to report a bug in the LinkedIn API?
I've been searching and searching, but I can't find out how to report a bug in the LinkedIn API.

LinkedIn's Developer site is completely devoid of any mention of bugs.  Even Googling "How to report a bug in the LinkedIn API" yields nothing.

LinkedIn's Developer Support page says that "[engineers] collaborate on questions tagged "linkedin" at Stack Overflow."  There are two problems with using SO for reporting this bug:

StackOverflow is not a bug reporting platform.

The bug report requires authentication to demonstrate.  We cannot publicly disclose this information.

How do I report a non-security-related LinkedIn API bug?

答: https://linkedin.zendesk.com/hc/en-us Use this link for reporting any bug or issue in LinkedIn website.</p>


问:
A minimal reproducible example to show asynchronous behavior using callbacks in Python
Background: To me it seems clear, that the conecpt of callbacks is flexible, but I also thought, it makes code much faster. However, the following example works, but it cannot show that time can be saved using a callback Ref1:

```<code>import time
from time import sleep

def callbackFunc(delay):
  time.sleep(delay)
  print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
  print("saysomething: message 2 delay " + str(delay))
  callback(delay) # hier muss ich schon wissen, dass nur "delay" benötigt wird...
  time.sleep(2)

if __name__ == '__main__':
  t0 = time.time()
  print("main:         message 1.")
  saysomething(2, callbackFunc)
  print("main:         message 4.")
  print("\ntime: ",time.time() - t0)
</code>```

Output

```<code>main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  4.01
</code>```

So how can I achive something like this

```<code>main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  2  !!!!!!!!!!!!!
</code>```

Perhaps it was even possible to switch the order of messages 3 & 4? Or do I get anything wrong?

Perhaps, these answers here and here and the following code from here which does not use callbacks but shows asynchronous behavior help?

答:
Re-establishing the premise

Before we start, let's clarify the statement in your post:

A callback does not make the code itself faster. The program does end earlier because the function that accepts the callback does not block.

Also, callbacks are generally executed synchronously in the function that accepts the callback, so your example would still take 4 seconds. A more reasonable starting point would be:

import time

def callbackFunc(delay):
    # time.sleep(delay)  # -
    print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
    print("saysomething: message 2 delay " + str(delay))
    time.sleep(2)    # +
    callback(delay)
    # time.sleep(2)  # -

if __name__ == '__main__':
    t0 = time.time()
    print("main:         message 1.")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")  # +
    saysomething(2, callbackFunc)              # +
    print("\ntime: ", time.time() - t0, "\n")  # +
    print("main:         message 4.")
    print("\ntime: ", time.time() - t0)
```
<p>Output:</p>
```main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2

time:  2.00

saysomething: message 2 delay 2
callback:     message 3 delay 2

time:  4.00

main:         message 4.

time:  4.00
```
<h1>Why the example doesn't work</h1>
<p><code>sleep()</code> suspends execution of the calling thread, so you can't call it on the main thread if you want to show asynchronous behaviour.</p>
<p>You can use threads or an event loop to show asynchronous behaviour.</p>
<h1>An example using an event loop</h1>
<p>Here's an example using the built-in event loop:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio  # +
import time

def callbackFunc(delay):
    print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
    print("saysomething: message 2 delay " + str(delay))
    # time.sleep(2)                                          # -
    # callback(delay)                                        # -
    asyncio.get_event_loop().call_later(2, callback, delay)  # +

def wait_for_callbacks():  # +
    def run_until_complete(loop):
        loop.call_soon(lambda: run_until_complete(loop) if loop._scheduled else loop.stop())
    loop = asyncio.get_event_loop()
    run_until_complete(loop)
    loop.run_forever()

if __name__ == '__main__':
    t0 = time.time()
    print("main:         message 1.")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    print("main:         message 4.")
    wait_for_callbacks()  # +
    print("\ntime: ", time.time() - t0)
</code>```

Output:

```<code>main:         message 1.
saysomething: message 2 delay 2

time:  0.000

saysomething: message 2 delay 2

time:  0.000

main:         message 4.
callback:     message 3 delay 2
callback:     message 3 delay 2

time:  2.000
</code>```

An example using threads

Here's an example using the built-in OS threads:

import threading  # +
import time

def threadify(func):  # +
    def _func(*args, **kwargs):
        thread = threading.Thread(target=func, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return _func

def callbackFunc(delay):
    print("callback:     message 3 delay " + str(delay))

@threadify  # +
def saysomething(delay, callback):
    print("saysomething: message 2 delay " + str(delay))
    time.sleep(2)
    callback(delay)

def wait_for_callbacks():  # +
    for thread in threading.enumerate():
        if thread is not threading.current_thread():
            thread.join()

if __name__ == '__main__':
    t0 = time.time()
    print("main:         message 1.")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    print("main:         message 4.")
    wait_for_callbacks()  # +
    print("\ntime: ", time.time() - t0)
```
<p>Output: (marginally slower than using the built-in event loop due to overhead of OS threads)</p>
<pre class="lang-py prettyprint-override"><code>main:         message 1.
saysomething: message 2 delay 2

time:  0.000

saysomething: message 2 delay 2

time:  0.000

main:         message 4.
callback:     message 3 delay 2
callback:     message 3 delay 2

time:  2.00
</code>```

Body:
Background: To me it seems clear, that the conecpt of callbacks is flexible, but I also thought, it makes code much faster. However, the following example works, but it cannot show that time can be saved using a callback Ref1:

import time
from time import sleep

def callbackFunc(delay):
  time.sleep(delay)
  print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
  print("saysomething: message 2 delay " + str(delay))
  callback(delay) # hier muss ich schon wissen, dass nur "delay" benötigt wird...
  time.sleep(2)

if __name__ == '__main__':
  t0 = time.time()
  print("main:         message 1.")
  saysomething(2, callbackFunc)
  print("main:         message 4.")
  print("\ntime: ",time.time() - t0)

Output

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  4.01

So how can I achive something like this

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2
main:         message 4.
time:  2  !!!!!!!!!!!!!

Perhaps it was even possible to switch the order of messages 3 & 4? Or do I get anything wrong?

Perhaps, these answers here and here and the following code from here which does not use callbacks but shows asynchronous behavior help?

Body:
Re-establishing the premise

Before we start, let's clarify the statement in your post:

A callback does not make the code itself faster. The program does end earlier because the function that accepts the callback does not block.

Also, callbacks are generally executed synchronously in the function that accepts the callback, so your example would still take 4 seconds. A more reasonable starting point would be:

import time

def callbackFunc(delay):
    # time.sleep(delay)  # -
    print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
    print("saysomething: message 2 delay " + str(delay))
    time.sleep(2)    # +
    callback(delay)
    # time.sleep(2)  # -

if __name__ == '__main__':
    t0 = time.time()
    print("main:         message 1.")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")  # +
    saysomething(2, callbackFunc)              # +
    print("\ntime: ", time.time() - t0, "\n")  # +
    print("main:         message 4.")
    print("\ntime: ", time.time() - t0)

Output:

main:         message 1.
saysomething: message 2 delay 2
callback:     message 3 delay 2

time:  2.00

saysomething: message 2 delay 2
callback:     message 3 delay 2

time:  4.00

main:         message 4.

time:  4.00

Why the example doesn't work

sleep() suspends execution of the calling thread, so you can't call it on the main thread if you want to show asynchronous behaviour.

You can use threads or an event loop to show asynchronous behaviour.

An example using an event loop

Here's an example using the built-in event loop:

import asyncio  # +
import time

def callbackFunc(delay):
    print("callback:     message 3 delay " + str(delay))

def saysomething(delay, callback):
    print("saysomething: message 2 delay " + str(delay))
    # time.sleep(2)                                          # -
    # callback(delay)                                        # -
    asyncio.get_event_loop().call_later(2, callback, delay)  # +

def wait_for_callbacks():  # +
    def run_until_complete(loop):
        loop.call_soon(lambda: run_until_complete(loop) if loop._scheduled else loop.stop())
    loop = asyncio.get_event_loop()
    run_until_complete(loop)
    loop.run_forever()

if __name__ == '__main__':
    t0 = time.time()
    print("main:         message 1.")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    print("main:         message 4.")
    wait_for_callbacks()  # +
    print("\ntime: ", time.time() - t0)

Output:

main:         message 1.
saysomething: message 2 delay 2

time:  0.000

saysomething: message 2 delay 2

time:  0.000

main:         message 4.
callback:     message 3 delay 2
callback:     message 3 delay 2

time:  2.000

An example using threads

Here's an example using the built-in OS threads:

import threading  # +
import time

def threadify(func):  # +
    def _func(*args, **kwargs):
        thread = threading.Thread(target=func, args=args, kwargs=kwargs)
        thread.start()
        return thread
    return _func

def callbackFunc(delay):
    print("callback:     message 3 delay " + str(delay))

@threadify  # +
def saysomething(delay, callback):
    print("saysomething: message 2 delay " + str(delay))
    time.sleep(2)
    callback(delay)

def wait_for_callbacks():  # +
    for thread in threading.enumerate():
        if thread is not threading.current_thread():
            thread.join()

if __name__ == '__main__':
    t0 = time.time()
    print("main:         message 1.")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    saysomething(2, callbackFunc)
    print("\ntime: ", time.time() - t0, "\n")
    print("main:         message 4.")
    wait_for_callbacks()  # +
    print("\ntime: ", time.time() - t0)

Output: (marginally slower than using the built-in event loop due to overhead of OS threads)

main:         message 1.
saysomething: message 2 delay 2

time:  0.000

saysomething: message 2 delay 2

time:  0.000

main:         message 4.
callback:     message 3 delay 2
callback:     message 3 delay 2

time:  2.00


问:
Recursive function without return statement
I have some data that is inserted into a nested dictionary. The data are created and could theoretically be endlessly deep. It could e.g. looks like this:

```<code>data = {'leaves': {'dark': {}, 'green': {'light': {}}, 'without': {'veins': {'blue': {}}}, '5': {}}}
</code>```

For some clarification: In this small sample, it means that a certain plant has 'leaves', the 'leaves' are 'dark', 'green' and 'without'. The 'green' is 'light' in this example etc.

I want to unnest this dictionary and store every key, value combination into a tuple. That could for example look like this:

```<code>[('leaves', 'dark'), ('leaves', 'green'), ('green', 'light'), ('without', 'veins'), ('leaves', '5'), ('veines', 'blue')]
</code>```

Note: order is not important. For those interested, these tuples are further manipulated and will end up in a knowledge graph.

I thought a recursive function would do the trick here, but my function works best without the restatement, a function without a return statement is just a simple loop. However, I cannot make it work with a simple loop.

edit: the doubles variable is a global list.

The function I wrote:

```<code>def undict(d):
    for key in d.keys():
        if isinstance(d[key], dict):
            doubles += [(key, k) for k in d[key].keys()]
        undict(d[key]) # Normally: return undict(d[key])
</code>```

Maybe can anyone offer some insights on how to make it truly recursive or use a simple loop? I am lost at this point.

答:
Your approach is pretty good!

However, note that you're using a global variable, doubles, rather than a local variable and a return statement, which would be cleaner.

To avoid issues with .append or .extend or += with lists, a very pythonic approach is to use a generator function, using keyword yield instead of keyword return.

data = {'leaves': {'dark': {}, 'green': {'light': {}}, 'without': {'veins': {'blue': {}}}, '5': {}}}

def undict_to_pairs(d):
    for k,v in d.items():
        if isinstance(v, dict):  # always true with your example data
            for subk in v:
                yield (k, subk)
            yield from undict_to_pairs(v)
        else:
            yield (k,v)          # this statement is never reached with your example data

print(list(undict_to_pairs(data)))
# [('leaves', 'dark'), ('leaves', 'green'), ('leaves', 'without'), ('leaves', '5'), ('green', 'light'), ('without', 'veins'), ('veins', 'blue')]
```
<p>Note that with your example data, <code>isinstance(v,dict)</code> is always true. The <code>else</code> branch is never reached. So this shorter version would work too:</p>
<pre class="lang-py prettyprint-override"><code>def undict_to_pairs(d):
    for k,v in d.items():
        for subk in v:
            yield (k, subk)
        yield from undict_to_pairs(v)

print(list(undict_to_pairs(data)))
# [('leaves', 'dark'), ('leaves', 'green'), ('leaves', 'without'), ('leaves', '5'), ('green', 'light'), ('without', 'veins'), ('veins', 'blue')]
</code>```

Let me also suggest a different version, which is not what you asked for but looks more logical to me in regards to your data: generating long tuples instead of pairs. I removed isinstance(v, dict) from that version, since it appears the values in your data are always dicts.

def undict_to_tuples(d, acc = ()):
    if d == {}:
        yield acc
    else:
        for k,v in d.items():
            yield from undict_to_tuples(v, acc + (k,))

print(list(undict_to_tuples(data)))
# [('leaves', 'dark'), ('leaves', 'green', 'light'), ('leaves', 'without', 'veins', 'blue'), ('leaves', '5')]
```

Body:
I have some data that is inserted into a nested dictionary. The data are created and could theoretically be endlessly deep. It could e.g. looks like this:

data = {'leaves': {'dark': {}, 'green': {'light': {}}, 'without': {'veins': {'blue': {}}}, '5': {}}}

For some clarification: In this small sample, it means that a certain plant has 'leaves', the 'leaves' are 'dark', 'green' and 'without'. The 'green' is 'light' in this example etc.

I want to unnest this dictionary and store every key, value combination into a tuple. That could for example look like this:

[('leaves', 'dark'), ('leaves', 'green'), ('green', 'light'), ('without', 'veins'), ('leaves', '5'), ('veines', 'blue')]

Note: order is not important. For those interested, these tuples are further manipulated and will end up in a knowledge graph.

I thought a recursive function would do the trick here, but my function works best without the restatement, a function without a return statement is just a simple loop. However, I cannot make it work with a simple loop.

edit: the doubles variable is a global list.

The function I wrote:

def undict(d):
    for key in d.keys():
        if isinstance(d[key], dict):
            doubles += [(key, k) for k in d[key].keys()]
        undict(d[key]) # Normally: return undict(d[key])

Maybe can anyone offer some insights on how to make it truly recursive or use a simple loop? I am lost at this point.

Body:
Your approach is pretty good!

However, note that you're using a global variable, doubles, rather than a local variable and a return statement, which would be cleaner.

To avoid issues with .append or .extend or += with lists, a very pythonic approach is to use a generator function, using keyword yield instead of keyword return.

data = {'leaves': {'dark': {}, 'green': {'light': {}}, 'without': {'veins': {'blue': {}}}, '5': {}}}

def undict_to_pairs(d):
    for k,v in d.items():
        if isinstance(v, dict):  # always true with your example data
            for subk in v:
                yield (k, subk)
            yield from undict_to_pairs(v)
        else:
            yield (k,v)          # this statement is never reached with your example data

print(list(undict_to_pairs(data)))
# [('leaves', 'dark'), ('leaves', 'green'), ('leaves', 'without'), ('leaves', '5'), ('green', 'light'), ('without', 'veins'), ('veins', 'blue')]

Note that with your example data, isinstance(v,dict) is always true. The else branch is never reached. So this shorter version would work too:

def undict_to_pairs(d):
    for k,v in d.items():
        for subk in v:
            yield (k, subk)
        yield from undict_to_pairs(v)

print(list(undict_to_pairs(data)))
# [('leaves', 'dark'), ('leaves', 'green'), ('leaves', 'without'), ('leaves', '5'), ('green', 'light'), ('without', 'veins'), ('veins', 'blue')]

Let me also suggest a different version, which is not what you asked for but looks more logical to me in regards to your data: generating long tuples instead of pairs. I removed isinstance(v, dict) from that version, since it appears the values in your data are always dicts.

def undict_to_tuples(d, acc = ()):
    if d == {}:
        yield acc
    else:
        for k,v in d.items():
            yield from undict_to_tuples(v, acc + (k,))

print(list(undict_to_tuples(data)))
# [('leaves', 'dark'), ('leaves', 'green', 'light'), ('leaves', 'without', 'veins', 'blue'), ('leaves', '5')]


答:
Assuming you have a pattern where colon (':') appears only once right before word you want to extract. And right after the word you have a dash ('-'), but you also can have dashes before it:

```<code>declare @str nvarchar(max) = 'XRDCWPDBSADX02:SKYLINE-NAE04/FC-1.041020FE.ChwVlvCmd.#85'
select substring( @str, charindex(':', @str, 0) + 1, charindex('-', @str, charindex(':', @str, 0)) - charindex(':', @str, 0) - 1)
</code>```

The third argument in this part : charindex('-', @str, charindex(':', @str, 0)) is a starting position to search, which is an index of colon, in case we have some additional dashes before it.

Title: Parse a string between 2 delimiters

Body:
Assuming you have a pattern where colon (':') appears only once right before word you want to extract. And right after the word you have a dash ('-'), but you also can have dashes before it:

declare @str nvarchar(max) = 'XRDCWPDBSADX02:SKYLINE-NAE04/FC-1.041020FE.ChwVlvCmd.#85'
select substring( @str, charindex(':', @str, 0) + 1, charindex('-', @str, charindex(':', @str, 0)) - charindex(':', @str, 0) - 1)

The third argument in this part : charindex('-', @str, charindex(':', @str, 0)) is a starting position to search, which is an index of colon, in case we have some additional dashes before it.


问:
Difference between object reference declaration and object construction?
Consider a class named Calculator with the following code:

```<code>class Calc extends Calculator {

    Calculator calculator;                    // [Style 1]

    Calculator calculator = new Calculator(); // [Style 2]
}
</code>```

To my knowledge, no memory has been allocated in [1], but in statement [2] a new Calculator object is created.

Are there any other differences beyond that?

答: In the first case, no object Calculator is created, and the value of the variable is null.

Body:
Consider a class named Calculator with the following code:

class Calc extends Calculator {

    Calculator calculator;                    // [Style 1]

    Calculator calculator = new Calculator(); // [Style 2]
}

To my knowledge, no memory has been allocated in [1], but in statement [2] a new Calculator object is created.

Are there any other differences beyond that?


问:
Left join only selected columns in R with the merge() function
I am trying to LEFT Join 2 data frames but I do not want join all the variables from the second data set:

As an example, I have dataset 1 (DF1):

```<code>  Cl    Q   Sales  Date
   A    2   30     01/01/2014
   A    3   24     02/01/2014
   A    1   10     03/01/2014
   B    4   10     01/01/2014
   B    1   20     02/01/2014
   B    3   30     03/01/2014
</code>```

And I would like to left join dataset 2 (DF2):

```<code>Client  LO  CON
   A    12  CA
   B    11  US
   C    12  UK
   D    10  CA
   E    15  AUS
   F    91  DD
</code>```

I am able to left join with the following code:

merge(x = DF1, y = DF2, by = "Client", all.x=TRUE) :

```<code>   Client Q    Sales   Date             LO      CON
   A      2    30      01/01/2014       12      CA
   A      3    24      02/01/2014       12      CA
   A      1    10      03/01/2014       12      CA
   B      4    10      01/01/2014       11      US
   B      1    20      02/01/2014       11      US
   B      3    30      03/01/2014       11      US
</code>```

However, it merges both column LO and CON. I would only like to merge the column LO.

```<code>   Client Q    Sales   Date             LO
   A      2    30      01/01/2014       12
   A      3    24      02/01/2014       12
   A      1    10      03/01/2014       12
   B      4    10      01/01/2014       11
   B      1    20      02/01/2014       11
   B      3    30      03/01/2014       11
</code>```

答:
For Client column in both tables:

```<code>DF_joined <- DF1 %>% left_join(DF2 %>% select(Client,CON))
</code>```

Body:
I am trying to LEFT Join 2 data frames but I do not want join all the variables from the second data set:

As an example, I have dataset 1 (DF1):

  Cl    Q   Sales  Date
   A    2   30     01/01/2014
   A    3   24     02/01/2014
   A    1   10     03/01/2014
   B    4   10     01/01/2014
   B    1   20     02/01/2014
   B    3   30     03/01/2014

And I would like to left join dataset 2 (DF2):

Client  LO  CON
   A    12  CA
   B    11  US
   C    12  UK
   D    10  CA
   E    15  AUS
   F    91  DD

I am able to left join with the following code:

merge(x = DF1, y = DF2, by = "Client", all.x=TRUE) :

   Client Q    Sales   Date             LO      CON
   A      2    30      01/01/2014       12      CA
   A      3    24      02/01/2014       12      CA
   A      1    10      03/01/2014       12      CA
   B      4    10      01/01/2014       11      US
   B      1    20      02/01/2014       11      US
   B      3    30      03/01/2014       11      US

However, it merges both column LO and CON. I would only like to merge the column LO.

   Client Q    Sales   Date             LO
   A      2    30      01/01/2014       12
   A      3    24      02/01/2014       12
   A      1    10      03/01/2014       12
   B      4    10      01/01/2014       11
   B      1    20      02/01/2014       11
   B      3    30      03/01/2014       11

Body:
For Client column in both tables:

DF_joined <- DF1 %>% left_join(DF2 %>% select(Client,CON))


问:
How can I add an already generated SSH key to git bash?
I have an SSH key saved in D:/keys folder. I want to add it to my git bash. All the tutorials I found is how to generate SSH key using gitbash and load it to github/gitlab. I generated my SSH key using puttygen. Now I want to add it to my git bash so that I can clone a repository from remote. How can I do that?

答: I was able to get it so the passphrase is only prompted for on the first window that's opened after booting using the script at Auto-launching ssh-agent on Git for Windows. I did find, however, it didn't work when I added it add it to either ~/.profile or ~/.bashrc. I needed to add it to ~/.bash_profile for it to get picked up and used by Git Bash on Windows.


问:
Get channel message history and mark views with WTelegramClient
How can I:

Get a public channel message history [Text, Photo, Video ...]

Mark these messages as a viewed

With Telethon (python), we can use this method:

```<code>for message in client.get_messages(channel, limit=int(count)):
                result = client(functions.messages.GetMessagesViewsRequest(peer=channel,id=[message.id],increment=True))
</code>```

I want a method like this on WTelegramClient in c#

答:
If I understand correctly, you want to get a list of messages (history) from a channel and increment the views counter for each.

⚠ From the official documentation:
If you use the Telegram API for flooding, spamming, faking subscribers, and view counters of channels, you will be banned forever.

The equivalent of your code with WTelegramClient would be something like this:

var msgs = await client.Messages_GetHistory(channel, limit: count);
foreach (var message in msgs.Messages)
    await client.Messages_GetMessagesViews(channel, new[] { message.ID }, true);

// possible alternate way (single API call):
await client.Messages_GetMessagesViews(channel, msgs.Messages.Select(m => m.ID).ToArray(), true);
```

See EXAMPLES.md for detailed examples of fetching chat history.

Body:
How can I:

Get a public channel message history [Text, Photo, Video ...]

Mark these messages as a viewed

With Telethon (python), we can use this method:

for message in client.get_messages(channel, limit=int(count)):
                result = client(functions.messages.GetMessagesViewsRequest(peer=channel,id=[message.id],increment=True))

I want a method like this on WTelegramClient in c#

Body:
If I understand correctly, you want to get a list of messages (history) from a channel and increment the views counter for each.

⚠ From the official documentation:
If you use the Telegram API for flooding, spamming, faking subscribers, and view counters of channels, you will be banned forever.

The equivalent of your code with WTelegramClient would be something like this:

var msgs = await client.Messages_GetHistory(channel, limit: count);
foreach (var message in msgs.Messages)
    await client.Messages_GetMessagesViews(channel, new[] { message.ID }, true);

// possible alternate way (single API call):
await client.Messages_GetMessagesViews(channel, msgs.Messages.Select(m => m.ID).ToArray(), true);

See EXAMPLES.md for detailed examples of fetching chat history.


问:
Is there a way to filter information from a view and display them in the same view?
two months ago i asked this Question: How do i write more complex code in Lotus Notes views.
My View now looks like this:

Year
Month
Device
Counter
Times(Minutes)
Times(Hours)

2021

January

Test 01

270
4,5

Test 02

210
3,5

Test 01

60
1

Test 01

90
1,5

February

Test 01

30
0,5

Test 02

180
3

Test 01

60
1

The Database sets a new Document every time a Device is lend out. What i want to do now is to read trough every document and combine  "Times(Minutes)" and "Times(Hours)" inside an variable, and also save each device name one time.When a device name is scanned more then once, the counter will go up by one. In my Lotus script program i did this using a Multi-Dimensional Array.

I Want to do this because i want to display each Device only One Time. Then each device has the combined values inside the "Times" Columns, and a counter to show how often the Device has been lend out in the chosen month. It should look like this:

Year
Month
Device
Counter
Times(Minutes)
Times(Hours)

2021

January

Test 01
3
420
7

Test 02
1
210
3,5

Feburary

Test 01
2
90
1,5

Test 02
1
180
3

答: If you set the device column to be categorised, and set totals on the Times columns properties, this will give you what you want.  It will have the benefit that you can also see the total times across the month for all devices before you drill down</p>


问:
Matching a number against a comma-separated sequence of ranges
I'm writing a bash script which takes a number, and also a comma-separated sequence of values and strings, e.g.: 3,15,4-7,19-20. I want to check whether the number is contained in the set corresponding to the sequence. For simplicity, assume no comma-separated elements intersect, and that the elements are sorted in ascending order.

Is there a simple way to do this in bash other than the brute-force naive way? Some shell utility which does something like that for me, maybe something related to lpr which already knows how to process page range sequences etc.

答:
Another awk idea using two input (-v) variables:

```<code># use of function wrapper is optional but cleaner for the follow-on test run

in_range() {

awk -v value="$1" -v r="$2" '
BEGIN { n=split(r,ranges,",")
        for (i=1;i<=n;i++) {
            low=high=ranges[i]
            if (ranges[i] ~ "-") {
               split(ranges[i],x,"-")
               low=x[1]
               high=x[2]
            }
            if (value >= low && value <= high) {
               print value,"found in the range:",ranges[i]
               exit
            }
        }
      }'
}
</code>```

NOTE: the exit assumes no overlapping ranges, ie, value will not be found in more than one 'range'

Take for a test spin:

```<code>ranges='3,15,4-7,19-20'

for value in 1 6 15 32
do
    echo "########### value = ${value}"
    in_range "${value}" "${ranges}"
done
</code>```

This generates:

```<code>########### value = 1
########### value = 6
6 found in the range: 4-7
########### value = 15
15 found in the range: 15
########### value = 32
</code>```

NOTES:

OP did not mention what to generate as output if no range match is found; code could be modified to output a 'not found' message as needed

in a comment OP mentioned possibly running the search for a number of values; code could be modified to support such a requirement but would need more input (eg, format of list of values, desired output and how to be used/captured by calling process, etc)

Body:
Another awk idea using two input (-v) variables:

# use of function wrapper is optional but cleaner for the follow-on test run

in_range() {

awk -v value="$1" -v r="$2" '
BEGIN { n=split(r,ranges,",")
        for (i=1;i<=n;i++) {
            low=high=ranges[i]
            if (ranges[i] ~ "-") {
               split(ranges[i],x,"-")
               low=x[1]
               high=x[2]
            }
            if (value >= low && value <= high) {
               print value,"found in the range:",ranges[i]
               exit
            }
        }
      }'
}

NOTE: the exit assumes no overlapping ranges, ie, value will not be found in more than one 'range'

Take for a test spin:

ranges='3,15,4-7,19-20'

for value in 1 6 15 32
do
    echo "########### value = ${value}"
    in_range "${value}" "${ranges}"
done

This generates:

########### value = 1
########### value = 6
6 found in the range: 4-7
########### value = 15
15 found in the range: 15
########### value = 32

NOTES:

OP did not mention what to generate as output if no range match is found; code could be modified to output a 'not found' message as needed

in a comment OP mentioned possibly running the search for a number of values; code could be modified to support such a requirement but would need more input (eg, format of list of values, desired output and how to be used/captured by calling process, etc)


问:
How to invoke an AIR native installer app (EXE,DMG, etc) from browser
I'm looking at this Howto:

http://livedocs.adobe.com/flex/3/html/help.html?content=distributing_apps_3.html#1036176

But I cannot get it to work with a Native installer application. These are .EXE/.DMG AIR apps that are downloaded and installed, NOT .air apps installed by badge.swf. I need to be able to do a browser invocation with a few additional flashvars set.

I already tried to modify the badge.swf file by got many compile errors in FlashBuilder 4.5

Is there an online example of how to do this?

答:
The AIR installer badge is intended to be used in the situation where the user has Flash installed, but may not have AIR installed. When the user clicks on the badge to install the AIR application, the AIR runtime is first downloaded and installed if necessary, and then the application is installed.

There is no reason to use the badge with a packaged native installer because the installer will download and install the AIR runtime if necessary before installing the application.

You can create a SWF which looks like a badge and downloads the native installer using a FileReference. There is however no way to execute the installer automatically after it has downloaded as doing so would present serious security risks.

The best course of action is to present clear instructions to the user on how to download and install the application using the native installer.


问:
How to change content when button is selected
Good day everyone, I have a form that has three select buttons of which "Distribute" is pre-selected when the page loads that has information in the content which is the full name, password, and location. How do I use JS to create a click effect that when any button is selected the pre-selected, deselects, and the content changes. For more clarity, here are some images to explain further

When page loads:

What should happen when I select "Buy" :

Here's my code:

* {
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  padding: 0;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  display: flex;
  font-size: 16px;
  user-select: none;
}

/* APPLICATION */

.applicant {
  width: 60%;
  margin: auto;
  text-align: left;
  margin: 90px auto;
  padding-top: 100px;
  padding-bottom: 100px;
}

.login-center {
  height: 100%;
  flex-basis: 41%;
  background: #ffffff;
  padding: 35px 5px 0px 5px;
  box-sizing: border-box;
  box-shadow: 0 0 50px 0px #e1e1e1;
}

.text h2 {
  text-align: center;
  font-size: 35px;
  font-weight: 600;
  color: #000;
}

.links {
  text-align: center;
  margin-left: -20px;
  margin-right: -20px;
  margin: 0 auto;
  padding-top: 50px;
}

.app-button {
  color: #c4c4c4;
  background-color: #ffffff;
  border: 1px solid #000;
  font-weight: bold;
  font-size: 17px;
  width: 200px;
  margin: 0 20px;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

.app-button:hover {
  background: #c4c4c4;
  color: #000000;
  transition: 0.5s;
}

/* ACTIVE STATE */

.links .active,
.app-button:hover {
  border: 1px solid #c4c4c4;
  background-color: #c4c4c4;
  color: #000;
}

/* FORM */

.form input::placeholder {
  font-size: 14px;
  color: #000;
}

.form label {
  color: #000;
  margin: 20px 0;
  font-size: 17px;
}

.form-u {
  margin: 70px 0;
  padding: 0px 100px;
}

.form input {
  width: 100%;
  padding: 20px;
  margin: 20px 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  background: #ffffff;
  border: 1.7px solid #e1e1e1;
}

.form input:focus {
  border-color: #c4c4c4;
  box-shadow: 0 0 15px 0px #e1e1e1;
}

.button-u {
  color: #c4c4c4;
  background-color: #000;
  border: 1px solid rg#c4c4c4;
  font-weight: bold;
  font-size: 17px;
  width: 100%;
  margin: 40px 0;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

/* DROPDOWN FOR LOCATION*/

.form input {
  font-size: 15px;
  color: #000;
}

.selector {
  width: 100%;
  padding-top: 20px;
  margin-bottom: 25px;
  position: relative;
}

#selectField p {
  font-size: 15px;
}

#selectField {
  width: 100%;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
  padding: 20px 20px;
  color: #000;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--Form-->
<section class="applicant">
  <div class="login-center">
    <div class="text">
      <h2>CREATE</h2>
    </div>
    <div class="links">
      <button type="button" class="app-button active">Distribute</button>
      <button type="button" class="app-button">Buy</button>
      <button type="button" class="app-button">Sell</button>

    </div>
    <div class="form-u">
      <form action="" class="form">

        <label for="uname"><b>Full Name:</b></label>
        <input type="text" name="name=" Enter full name "required">

        <label for="psw "><b>Password:</b></label>
        <input type="password " name="password " placeholder="Enter password " required>

        <label for="sem "><b>Location:</b></label>
        <div class="selector ">
          <div id="selectField ">
            <p id="selectText ">Select a Location</p>
            <img src="logo/arrow_down.png " alt=" " id="arrowIcon ">
          </div>
        </div>

        <button type="submit " class="button-u ">SUBMIT</button>

      </form>

    </div>

  </div>

</section></code>```

In summary, I want to be able to click all buttons and each button clicked should have different content as seen from the images. Hope I was clear enough. Thank you

答: Place each forms inside seperate div elements and show only the first one as default. Then assign an id to each button and reference IDs to div elements containing forms. Then upon clicking each button, show the respective div elements and hide all the sibling div elements</p>

Body:
Good day everyone, I have a form that has three select buttons of which "Distribute" is pre-selected when the page loads that has information in the content which is the full name, password, and location. How do I use JS to create a click effect that when any button is selected the pre-selected, deselects, and the content changes. For more clarity, here are some images to explain further

When page loads:

What should happen when I select "Buy" :

Here's my code:

* {
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  padding: 0;
  margin: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  display: flex;
  font-size: 16px;
  user-select: none;
}

/* APPLICATION */

.applicant {
  width: 60%;
  margin: auto;
  text-align: left;
  margin: 90px auto;
  padding-top: 100px;
  padding-bottom: 100px;
}

.login-center {
  height: 100%;
  flex-basis: 41%;
  background: #ffffff;
  padding: 35px 5px 0px 5px;
  box-sizing: border-box;
  box-shadow: 0 0 50px 0px #e1e1e1;
}

.text h2 {
  text-align: center;
  font-size: 35px;
  font-weight: 600;
  color: #000;
}

.links {
  text-align: center;
  margin-left: -20px;
  margin-right: -20px;
  margin: 0 auto;
  padding-top: 50px;
}

.app-button {
  color: #c4c4c4;
  background-color: #ffffff;
  border: 1px solid #000;
  font-weight: bold;
  font-size: 17px;
  width: 200px;
  margin: 0 20px;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

.app-button:hover {
  background: #c4c4c4;
  color: #000000;
  transition: 0.5s;
}

/* ACTIVE STATE */

.links .active,
.app-button:hover {
  border: 1px solid #c4c4c4;
  background-color: #c4c4c4;
  color: #000;
}

/* FORM */

.form input::placeholder {
  font-size: 14px;
  color: #000;
}

.form label {
  color: #000;
  margin: 20px 0;
  font-size: 17px;
}

.form-u {
  margin: 70px 0;
  padding: 0px 100px;
}

.form input {
  width: 100%;
  padding: 20px;
  margin: 20px 0;
  box-sizing: border-box;
  border: none;
  outline: none;
  background: #ffffff;
  border: 1.7px solid #e1e1e1;
}

.form input:focus {
  border-color: #c4c4c4;
  box-shadow: 0 0 15px 0px #e1e1e1;
}

.button-u {
  color: #c4c4c4;
  background-color: #000;
  border: 1px solid rg#c4c4c4;
  font-weight: bold;
  font-size: 17px;
  width: 100%;
  margin: 40px 0;
  display: inline-block;
  line-height: 40px;
  padding: 5px;
  cursor: pointer;
}

/* DROPDOWN FOR LOCATION*/

.form input {
  font-size: 15px;
  color: #000;
}

.selector {
  width: 100%;
  padding-top: 20px;
  margin-bottom: 25px;
  position: relative;
}

#selectField p {
  font-size: 15px;
}

#selectField {
  width: 100%;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
  padding: 20px 20px;
  color: #000;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
}

CREATE

      <button type="button" class="app-button active">Distribute</button>
      <button type="button" class="app-button">Buy</button>
      <button type="button" class="app-button">Sell</button>

      <form action="" class="form">

        Full Name:
        <input type="text" name="name=" Enter full name "required">

        Password:
        <input type="password " name="password " placeholder="Enter password " required>

        Location:

Select a Location

        <button type="submit " class="button-u ">SUBMIT</button>

      </form>

In summary, I want to be able to click all buttons and each button clicked should have different content as seen from the images. Hope I was clear enough. Thank you


问:
Insert offset method, in working code to copy data, to copy to next empty row
I am copying data from two workbooks to another workbook.

The code written by me works and serves the purpose.

I am having difficulty getting the syntax for using the offset method to copy to next empty row after the first paste.

With wsdly
    lrowdly = Cells(Rows.Count, 2).End(xlUp).Row
    .Range("A2:O" & lrowdly).ClearContents
    wsb.Range("A2:O" & lrowb).Copy .Range("A2")
End With
With wsdly
    lrowdly2 = Cells(Rows.Count, 2).End(xlUp).Row
    lrowdly3 = lrowdly2 + 1
    wsn.Range("A2:O" & lrown).Copy .Range("A" & lrowdly3)
End With
```
<p>Whole program.</p>
<pre class="lang-vb prettyprint-override"><code>Sub copy_bond_dat()
Dim wbb As Workbook
Dim wbn As Workbook
Dim wbdly As Workbook
Dim wsb As Worksheet
Dim wsn As Worksheet
Dim wsdly As Worksheet
Set wbb = Workbooks("BSE_BOND.xlsm")
Set wbn = Workbooks("NSE_BOND.xlsm")
Set wbdly = Workbooks("Dly_Debt_Trnx_2022_TMP.xlsx")
Set wsb = wbb.Worksheets("BSEDATA")
Set wsn = wbn.Worksheets("NSEDATA")
Set wsdly = wbdly.Worksheets("Dly_Debt_Trnx_2022_TMP")
Dim lrowb As Long
Dim lrown As Long
Dim lrowdly As Long
Dim lrowdly2 As Long
Dim lrowdly3 As Long
With wsb
    lrowb = Cells(Rows.Count, 2).End(xlUp).Row
End With
With wsn
    lrown = Cells(Rows.Count, 2).End(xlUp).Row
End With
With wsdly
    lrowdly = Cells(Rows.Count, 2).End(xlUp).Row
    .Range("A2:O" & lrowdly).ClearContents
    wsb.Range("A2:O" & lrowb).Copy .Range("A2")
End With
With wsdly
    lrowdly2 = Cells(Rows.Count, 2).End(xlUp).Row
    lrowdly3 = lrowdly2 + 1
    wsn.Range("A2:O" & lrown).Copy .Range("A" & lrowdly3)
End With
wbdly.Close
End Sub
</code>```

答:
Changing the mentioned code lines to following code lines problem gets resolved.</p>
```<code>With wsdly
    lrowdly = .Cells(Rows.Count, 2).End(xlUp).Row
    .Range("A2:O" & lrowdly).ClearContents
    wsb.Range("A2:O" & lrowb).Copy .Range("A2")

    wsn.Range("A2:O" & lrown).Copy

    .Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

End With
</code>```

Body:
I am copying data from two workbooks to another workbook.

The code written by me works and serves the purpose.

I am having difficulty getting the syntax for using the offset method to copy to next empty row after the first paste.

With wsdly
    lrowdly = Cells(Rows.Count, 2).End(xlUp).Row
    .Range("A2:O" & lrowdly).ClearContents
    wsb.Range("A2:O" & lrowb).Copy .Range("A2")
End With
With wsdly
    lrowdly2 = Cells(Rows.Count, 2).End(xlUp).Row
    lrowdly3 = lrowdly2 + 1
    wsn.Range("A2:O" & lrown).Copy .Range("A" & lrowdly3)
End With

Whole program.

Sub copy_bond_dat()
Dim wbb As Workbook
Dim wbn As Workbook
Dim wbdly As Workbook
Dim wsb As Worksheet
Dim wsn As Worksheet
Dim wsdly As Worksheet
Set wbb = Workbooks("BSE_BOND.xlsm")
Set wbn = Workbooks("NSE_BOND.xlsm")
Set wbdly = Workbooks("Dly_Debt_Trnx_2022_TMP.xlsx")
Set wsb = wbb.Worksheets("BSEDATA")
Set wsn = wbn.Worksheets("NSEDATA")
Set wsdly = wbdly.Worksheets("Dly_Debt_Trnx_2022_TMP")
Dim lrowb As Long
Dim lrown As Long
Dim lrowdly As Long
Dim lrowdly2 As Long
Dim lrowdly3 As Long
With wsb
    lrowb = Cells(Rows.Count, 2).End(xlUp).Row
End With
With wsn
    lrown = Cells(Rows.Count, 2).End(xlUp).Row
End With
With wsdly
    lrowdly = Cells(Rows.Count, 2).End(xlUp).Row
    .Range("A2:O" & lrowdly).ClearContents
    wsb.Range("A2:O" & lrowb).Copy .Range("A2")
End With
With wsdly
    lrowdly2 = Cells(Rows.Count, 2).End(xlUp).Row
    lrowdly3 = lrowdly2 + 1
    wsn.Range("A2:O" & lrown).Copy .Range("A" & lrowdly3)
End With
wbdly.Close
End Sub

Body:
Changing the mentioned code lines to following code lines problem gets resolved.

With wsdly
    lrowdly = .Cells(Rows.Count, 2).End(xlUp).Row
    .Range("A2:O" & lrowdly).ClearContents
    wsb.Range("A2:O" & lrowb).Copy .Range("A2")

    wsn.Range("A2:O" & lrown).Copy

    .Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

End With


问:
running into decleration error in solidity course
just started a solidity coding course and ran into this issue with this code:

```<code>//SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;

import "./simplestorage.sol";
``
contract StorageFactory {
function createsimplestoragecontract() public {
simplestorage _simplestorage = new simplestorage();
}

}
</code>```

I'm running into this error:
DeclarationError: Identifier not found or not unique.
--> contracts/storageFactory.sol:9:9:
|
9 | simplestorage _simplestorage = new simplestorage();
| ^^^^^^^^^^^^^

答:
The following code worked fine for me.

```<code> //SPDX-License-Identifier: MIT

 pragma solidity >=0.6.0;

 import "./1_Storage.sol";

 contract StorageFactory {

      function createsimplestoragecontract() public {
           Storage _simplestorage = new Storage();
      }

 }
</code>```

Did you check if the name of the contract in simplestorage.sol is "simplestorage"? Usually is Pascal case (not mandatory, but good practice), something like SimpleStorage. Be aware about this. Your error probably is about lowercase instead of uppercase.

Body:
just started a solidity coding course and ran into this issue with this code:

//SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;

import "./simplestorage.sol";
``
contract StorageFactory {
function createsimplestoragecontract() public {
simplestorage _simplestorage = new simplestorage();
}

}

I'm running into this error:
DeclarationError: Identifier not found or not unique.
--> contracts/storageFactory.sol:9:9:
|
9 | simplestorage _simplestorage = new simplestorage();
| ^^^^^^^^^^^^^

Body:
The following code worked fine for me.

 //SPDX-License-Identifier: MIT

 pragma solidity >=0.6.0;

 import "./1_Storage.sol";

 contract StorageFactory {

      function createsimplestoragecontract() public {
           Storage _simplestorage = new Storage();
      }

 }

Did you check if the name of the contract in simplestorage.sol is "simplestorage"? Usually is Pascal case (not mandatory, but good practice), something like SimpleStorage. Be aware about this. Your error probably is about lowercase instead of uppercase.


问:
How to count occurrences by day using dplyr
I am trying to use dplyr to do some basic statistics. The two parts of my data that I’m interested in are the dates and the outcomes of an event.

My data has three events that occur, reward, stop, or none (meaning neither a reward or stop occurred). What I want to do is calculate which days have the highest average of rewards by day. I was also hoping to try and obtain the count for overall occurrences, number of stops, rewards, and nones per day.

I have had some success obtaining the unique days and the overall occurrences per day. However, I am struggling to get the remaining data. When I try to adjust the group_by, it ends up causing issues trying to find the unique days.

```<code>df %>%
  mutate(ind, ind2 = case_when(ind=="Reward"~1, ind=="Stop"~0, ind=="None"~0)) %>%
  group_by(time2) %>%
  count(time2, sort = TRUE)
</code>```

Here, I try to create a new column that converts the event to binary formate so I could then try and calculate the average reward per day. This code is not required in an answer, just an example

Desires output:

```<code>Date        num_occ stop    reward  none        avg_reward
2022-01-03  3   1   1   1   0.3333333
2022-01-04  9   5   3   1   0.3333333
2022-01-05  2   1   1   0   0.5
2022-01-06  3   3   0   0   0
</code>```

My question is, how can I calculate the average reward occurrences per day as well as obtain count information regarding the number of overall (reward, stop, none) occurrences per day, number of stops per day, number of rewards per day, and number of nones per day?

Example data:

```<code>structure(list(values = c(0, 18, 3, 2, 1, 9, 15, 13, 0, 12, 8,
2, 3, 7, 6, 3), ind = structure(c(1L, 2L, 3L, 3L, 3L, 3L, 2L,
2L, 1L, 2L, 3L, 3L, 2L, 3L, 3L, 3L), .Label = c("None", "Reward",
"Stop"), class = "factor"), entry = c(TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE), time = structure(c(1641234180, 1641235020, 1641308400,
1641312840, 1641312900, 1641316920, 1641322920, 1641325080, 1641325560,
1641328740, 1641329220, 1641393900, 1641412140, 1641491040, 1641491640,
1641493200), class = c("POSIXct", "POSIXt"), tzone = ""), time2 = structure(c(18995,
18995, 18996, 18996, 18996, 18996, 18996, 18996, 18996, 18996,
18996, 18997, 18997, 18998, 18998, 18998), class = "Date")), row.names = c(NA,
16L), class = "data.frame")
</code>```

答:
Using @Bruno's sample data (thanks!)

## count totals per day
d1 <- (example_data
  %>% count(time2)
)
## count number of each event type per day; convert to wide format
d2 <- (example_data
  %>% count(time2, ind)
  %>% pivot_wider(names_from = "ind", values_from = n)
  %>% replace_na(list(None = 0, Reward = 0, Stop = 0))
)
## combine and compute averages
(full_join(d1, d2, by = "time2")
  %>% mutate(avg_reward = Reward/n)
)
```

Body:
I am trying to use dplyr to do some basic statistics. The two parts of my data that I’m interested in are the dates and the outcomes of an event.

My data has three events that occur, reward, stop, or none (meaning neither a reward or stop occurred). What I want to do is calculate which days have the highest average of rewards by day. I was also hoping to try and obtain the count for overall occurrences, number of stops, rewards, and nones per day.

I have had some success obtaining the unique days and the overall occurrences per day. However, I am struggling to get the remaining data. When I try to adjust the group_by, it ends up causing issues trying to find the unique days.

df %>%
  mutate(ind, ind2 = case_when(ind=="Reward"~1, ind=="Stop"~0, ind=="None"~0)) %>%
  group_by(time2) %>%
  count(time2, sort = TRUE)

Here, I try to create a new column that converts the event to binary formate so I could then try and calculate the average reward per day. This code is not required in an answer, just an example

Desires output:

Date        num_occ stop    reward  none        avg_reward
2022-01-03  3   1   1   1   0.3333333
2022-01-04  9   5   3   1   0.3333333
2022-01-05  2   1   1   0   0.5
2022-01-06  3   3   0   0   0

My question is, how can I calculate the average reward occurrences per day as well as obtain count information regarding the number of overall (reward, stop, none) occurrences per day, number of stops per day, number of rewards per day, and number of nones per day?

Example data:

structure(list(values = c(0, 18, 3, 2, 1, 9, 15, 13, 0, 12, 8,
2, 3, 7, 6, 3), ind = structure(c(1L, 2L, 3L, 3L, 3L, 3L, 2L,
2L, 1L, 2L, 3L, 3L, 2L, 3L, 3L, 3L), .Label = c("None", "Reward",
"Stop"), class = "factor"), entry = c(TRUE, TRUE, TRUE, TRUE,
TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE), time = structure(c(1641234180, 1641235020, 1641308400,
1641312840, 1641312900, 1641316920, 1641322920, 1641325080, 1641325560,
1641328740, 1641329220, 1641393900, 1641412140, 1641491040, 1641491640,
1641493200), class = c("POSIXct", "POSIXt"), tzone = ""), time2 = structure(c(18995,
18995, 18996, 18996, 18996, 18996, 18996, 18996, 18996, 18996,
18996, 18997, 18997, 18998, 18998, 18998), class = "Date")), row.names = c(NA,
16L), class = "data.frame")


问:
Transporter move through wall
In my model I use a transporter which uses free navigation. If it is right, the transporters can not move through walls, the strange thing is that in my model at one point somehow the transporter is able to move through a wall?

He slips through the wall somewhere at the red circled section, when I check the simulation. (see screenshot, blue is the transporter)

When I look at the model, I also see that there is no gap or something (see second image). Am I'm overlooking something (maybe something about that I've multiple floors)? or is it a bug? Does somebody know how to fix it.

答: For other people facing this problem, when having a low turn radius (0.01) and no speed limit near obstacle in your transporterfleet, it is possible to move through walls, if you change this the problem is solved!</p>

Title: Transporter move through wall


问:
How would I validate User input (names only / no numbers) using an if statement
The following takes in 10 names and then prints them using System.out.println later. I have an if statement below when I enter a number it warns me "do no enter numbers".

The problem is that after the warning prompt I enter 10 names but the number prints off as the first item in the Array? Then the names print afterwards?

```<code>import java.io.*;

public class Input {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] myarray = new String[10];

        System.out.println("Enter a 10 names");

        for (int i = 0; i < 10; i++) {

            myarray[i] = br.readLine();
            if (!myarray[i].matches("[a-zA-Z_]+")) {
                System.out.println("Invalid name,please do not enter numbers");
            }
        }
        System.out.println("Here are your names");

        for (int i = 0; i < 10; i++) {

            System.out.println(myarray[i]);

        }
    }
}
</code>```

答:
The problem is that when you're rejecting a value you're incrementing the loop counter as if you'd accepted it.

Instead of writing the input to the array, check whether it is valid first:

```<code>int i = 0;
while (i < 10) {
  String line = br.readLine();
  if (line.matches("[a-zA-Z_]+") {
    myarray[i++] = line;
  } else {
    System.out.println("Invalid name");
  }
}
</code>```

Note that i is only incremented when a value is written to the array, and while is used in preference to for since the number of iterations is unknown.

Body:
The following takes in 10 names and then prints them using System.out.println later. I have an if statement below when I enter a number it warns me "do no enter numbers".

The problem is that after the warning prompt I enter 10 names but the number prints off as the first item in the Array? Then the names print afterwards?

import java.io.*;

public class Input {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] myarray = new String[10];

        System.out.println("Enter a 10 names");

        for (int i = 0; i < 10; i++) {

            myarray[i] = br.readLine();
            if (!myarray[i].matches("[a-zA-Z_]+")) {
                System.out.println("Invalid name,please do not enter numbers");
            }
        }
        System.out.println("Here are your names");

        for (int i = 0; i < 10; i++) {

            System.out.println(myarray[i]);

        }
    }
}

Body:
The problem is that when you're rejecting a value you're incrementing the loop counter as if you'd accepted it.

Instead of writing the input to the array, check whether it is valid first:

int i = 0;
while (i < 10) {
  String line = br.readLine();
  if (line.matches("[a-zA-Z_]+") {
    myarray[i++] = line;
  } else {
    System.out.println("Invalid name");
  }
}

Note that i is only incremented when a value is written to the array, and while is used in preference to for since the number of iterations is unknown.


问:
How to find min/max aggregations with diffrerent filters in MongoDB?
Considering collection clothing of documents with this strucure

```<code>{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}
</code>```

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

```<code>SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand
</code>```

How to express this in MongoDB query?

答:
The answer above yields null for min when only a single data observation is present; it should show the same value for both max and min.  Here are some alternatives.   The first is the simple one that directly answers the OP question -- but it is noticeably "hardcoded" for color:

db.foo.aggregate([
    {$group: {_id: '$brand',
              'red_max': {$max: {$cond: [{$eq:['$color','red']}, '$size', 0]}},
              'red_min': {$min: {$cond: [{$eq:['$color','red']}, '$size', 99999999]}},
              'blue_max': {$max: {$cond: [{$eq:['$color','blue']}, '$size', 0]}},
              'blue_min': {$min: {$cond: [{$eq:['$color','blue']}, '$size', 99999999]}}
             }
    }
]);
```
<p>The second solution is more exciting as it will produce <code>max</code> and <code>min</code> for <em>all</em> colors encountered.</p>
<pre class="lang-js prettyprint-override"><code>db.foo.aggregate([
    {$group: {_id: {c:'$color',b:'$brand'}, max:{$max: "$size"}, min:{$min: "$size"}}}
    // Arguably, you are done by the stage above -- but to make the output more
    // convenient, employ a "regroup" stage to move the material around:
    ,{$group: {_id: '$_id.b', data: {$push: {color: '$_id.c', max: '$max', min: '$min'}}}}
    ,{$unwind: "$data"}  // optional, really...
]);
</code>```

You can easily capture just red and blue by performing a $match before the $group, or to get everything else as "OTHER" besides the target red and blue, change the first $group stage to:

    {$group: {_id: {c:{$cond:[{$in:['$color',['red','blue']]},'$color',"OTHER"]},  b:'$brand'},
              max:{$max: "$size"}, min:{$min: "$size"}}}
```
<p>Lastly, there may be times when in addition to finding the max and min, we wish to know about other fields in the same doc as the max and min.  This is possible with a slightly more complex query:</p>
<pre class="lang-js prettyprint-override"><code>db.foo.aggregate([
    {$group: {_id: {c:'$color',b:'$brand'}, XX:{$push: "$$CURRENT"}}}

    ,{$addFields: {XX: {$reduce: {
        input: "$XX",
        initialValue: {max:{size:0}, min:{size:99999999}},
            in: {
                max: {$cond: [{$gt:['$$this.size','$$value.max.size']},'$$this','$$value.max']},
                min: {$cond: [{$lt:['$$this.size','$$value.min.size']},'$$this','$$value.min']}
            }
    }}
    }}

    ,{$group: {_id: '$_id.b', data: {$push: {color: '$_id.c', max: '$XX.max', min: '$XX.min'}} }}
]);
</code>```

Yes, you do end up with repeated/redundant data in the max and min objects (specifically brand and color) but all other peer fields will be carried over without having to change the query, e.g.:

{
    "_id" : "B2",
    "data" : [
        {
            "color" : "red",
            "max" : {
                "_id" : 13,
                "brand" : "B2",
                "color" : "red",
                "size" : 8,
                "o1" : "A14",
                "o2" : [
                    "P",
                    "Q"
                ]
            },
            "min" : {
                "_id" : 8,
                "brand" : "B2",
                "color" : "red",
                "size" : 6,
                "o1" : "A9",
                "o2" : [
                    "K",
                    "L"
                ]
            }
        },
        {
            "color" : "blue",
            "max" : {
                "_id" : 9,
                "brand" : "B2",
                "color" : "blue",
                "size" : 7,
                "o1" : "A10",
                "o2" : [
                    "L",
                    "M"
                ]
            },
            "min" : {
                "_id" : 9,
                "brand" : "B2",
                "color" : "blue",
                "size" : 7,
                "o1" : "A10",
                "o2" : [
                    "L",
                    "M"
                ]
            }
        },
...
```
<p>If the redundant data is unacceptable, then you can use the <code>objectToArray-filter-arrayToObject</code> pattern to remove <code>color</code> and <code>brand</code>:</p>
<pre class="lang-js prettyprint-override"><code>    {$group: {_id: {c:'$color',b:'$brand'}, XX:{$push:
                   // "$$CURRENT"
                   {$arrayToObject: {$filter: {input: {$objectToArray: "$$CURRENT"},
                                               cond: {$not:{$in:['$$this.k', ['brand','color']]}}
                   }}}
    }}}
</code>```

Body:
Considering collection clothing of documents with this strucure

{
  "brand": <string>,
  "color": <string>,
  "size": <number>
}

In a single aggregation grouing by brand I would like to find two values:

min size for all documents in a group where color="blue"

max size for all documents in a group where color="red"

In SQL it would be something like this:

SELECT MIN(CASE color WHEN "blue" THEN size ELSE NULL END),
       MAX(CASE color WHEN "red" THEN size ELSE NULL END),
       brand
  FROM clothing
 GROUP BY brand

How to express this in MongoDB query?

Body:
The answer above yields null for min when only a single data observation is present; it should show the same value for both max and min.  Here are some alternatives.   The first is the simple one that directly answers the OP question -- but it is noticeably "hardcoded" for color:

db.foo.aggregate([
    {$group: {_id: '$brand',
              'red_max': {$max: {$cond: [{$eq:['$color','red']}, '$size', 0]}},
              'red_min': {$min: {$cond: [{$eq:['$color','red']}, '$size', 99999999]}},
              'blue_max': {$max: {$cond: [{$eq:['$color','blue']}, '$size', 0]}},
              'blue_min': {$min: {$cond: [{$eq:['$color','blue']}, '$size', 99999999]}}
             }
    }
]);

The second solution is more exciting as it will produce max and min for all colors encountered.

db.foo.aggregate([
    {$group: {_id: {c:'$color',b:'$brand'}, max:{$max: "$size"}, min:{$min: "$size"}}}
    // Arguably, you are done by the stage above -- but to make the output more
    // convenient, employ a "regroup" stage to move the material around:
    ,{$group: {_id: '$_id.b', data: {$push: {color: '$_id.c', max: '$max', min: '$min'}}}}
    ,{$unwind: "$data"}  // optional, really...
]);

You can easily capture just red and blue by performing a $match before the $group, or to get everything else as "OTHER" besides the target red and blue, change the first $group stage to:

    {$group: {_id: {c:{$cond:[{$in:['$color',['red','blue']]},'$color',"OTHER"]},  b:'$brand'},
              max:{$max: "$size"}, min:{$min: "$size"}}}

Lastly, there may be times when in addition to finding the max and min, we wish to know about other fields in the same doc as the max and min.  This is possible with a slightly more complex query:

db.foo.aggregate([
    {$group: {_id: {c:'$color',b:'$brand'}, XX:{$push: "$$CURRENT"}}}

    ,{$addFields: {XX: {$reduce: {
        input: "$XX",
        initialValue: {max:{size:0}, min:{size:99999999}},
            in: {
                max: {$cond: [{$gt:['$$this.size','$$value.max.size']},'$$this','$$value.max']},
                min: {$cond: [{$lt:['$$this.size','$$value.min.size']},'$$this','$$value.min']}
            }
    }}
    }}

    ,{$group: {_id: '$_id.b', data: {$push: {color: '$_id.c', max: '$XX.max', min: '$XX.min'}} }}
]);

Yes, you do end up with repeated/redundant data in the max and min objects (specifically brand and color) but all other peer fields will be carried over without having to change the query, e.g.:

{
    "_id" : "B2",
    "data" : [
        {
            "color" : "red",
            "max" : {
                "_id" : 13,
                "brand" : "B2",
                "color" : "red",
                "size" : 8,
                "o1" : "A14",
                "o2" : [
                    "P",
                    "Q"
                ]
            },
            "min" : {
                "_id" : 8,
                "brand" : "B2",
                "color" : "red",
                "size" : 6,
                "o1" : "A9",
                "o2" : [
                    "K",
                    "L"
                ]
            }
        },
        {
            "color" : "blue",
            "max" : {
                "_id" : 9,
                "brand" : "B2",
                "color" : "blue",
                "size" : 7,
                "o1" : "A10",
                "o2" : [
                    "L",
                    "M"
                ]
            },
            "min" : {
                "_id" : 9,
                "brand" : "B2",
                "color" : "blue",
                "size" : 7,
                "o1" : "A10",
                "o2" : [
                    "L",
                    "M"
                ]
            }
        },
...

If the redundant data is unacceptable, then you can use the objectToArray-filter-arrayToObject pattern to remove color and brand:

    {$group: {_id: {c:'$color',b:'$brand'}, XX:{$push:
                   // "$$CURRENT"
                   {$arrayToObject: {$filter: {input: {$objectToArray: "$$CURRENT"},
                                               cond: {$not:{$in:['$$this.k', ['brand','color']]}}
                   }}}
    }}}


问:
api platform with graphQL support
Just started to work with api platform with graphQl support enabled. If I understand correctly with graphQl I don't need to create routes like we need with REST, the endpoints are created in the frontend from the Model schemas.

But what if I have a method which had some logic in it and I need to run that code? If I dont have a route I can't execute that. What can I do than?

Thanks for the answers in advance.
Br

答:
You can solve that by using custom queries to fetch data or custom mutations to post/put/delete data in REST terms.

You question implies you want to have a custom mutation, according to the docs this would work like this:

Create your resolver:

```<code><?php

namespace App\Resolver;

use ApiPlatform\Core\GraphQl\Resolver\MutationResolverInterface;
use App\Model\Book;

final class BookMutationResolver implements MutationResolverInterface
{
    /**
     * @param Book|null $item
     *
     * @return Book
     */
    public function __invoke($item, array $context)
    {
        // Mutation input arguments are in $context['args']['input'].

        // Do something with the book.
        // Or fetch the book if it has not been retrieved.

        // The returned item will pe persisted.
        return $item;
    }
}
</code>```

then use this custom mutation as following:

```<code><?php

namespace App\Model;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Resolver\BookMutationResolver;

#[ApiResource(
    graphql: [
        // Auto-generated queries and mutations
        'item_query',
        'collection_query',
        'create',
        'update',
        'delete',

        'mutation' => [
            'mutation' => BookMutationResolver::class
        ],
        'withCustomArgsMutation' => [
            'mutation' => BookMutationResolver::class,
            'args' => [
                'sendMail' => ['type' => 'Boolean!', 'description'=> 'Send a mail?' ]
            ]
        ],
        'disabledStagesMutation' => [
            'mutation' => BookMutationResolver::class,
            'deserialize' => false,
            'write' => false
        ]
    ]
)]
class Book
{
    // ...
}
</code>```

Title: api platform with graphQL support

Body:
You can solve that by using custom queries to fetch data or custom mutations to post/put/delete data in REST terms.

You question implies you want to have a custom mutation, according to the docs this would work like this:

Create your resolver:

<?php

namespace App\Resolver;

use ApiPlatform\Core\GraphQl\Resolver\MutationResolverInterface;
use App\Model\Book;

final class BookMutationResolver implements MutationResolverInterface
{
    /**
     * @param Book|null $item
     *
     * @return Book
     */
    public function __invoke($item, array $context)
    {
        // Mutation input arguments are in $context['args']['input'].

        // Do something with the book.
        // Or fetch the book if it has not been retrieved.

        // The returned item will pe persisted.
        return $item;
    }
}

then use this custom mutation as following:

<?php

namespace App\Model;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Resolver\BookMutationResolver;

#[ApiResource(
    graphql: [
        // Auto-generated queries and mutations
        'item_query',
        'collection_query',
        'create',
        'update',
        'delete',

        'mutation' => [
            'mutation' => BookMutationResolver::class
        ],
        'withCustomArgsMutation' => [
            'mutation' => BookMutationResolver::class,
            'args' => [
                'sendMail' => ['type' => 'Boolean!', 'description'=> 'Send a mail?' ]
            ]
        ],
        'disabledStagesMutation' => [
            'mutation' => BookMutationResolver::class,
            'deserialize' => false,
            'write' => false
        ]
    ]
)]
class Book
{
    // ...
}