问:
File Reading in C returns empty
I'm able to write data into a file but when I read it, it prints an empty file. I tried to make 2 programs one to write to file using permission "w" and one to read using "r" but when I combined both programs and changed permission to "w+" printing the files gives lots of empty spaces.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
void main()
{

    char name[20];
    char roll_no[15];
    char class[10];
    char semester[10];
    char course[20];

    FILE *file_pointer;
    file_pointer = fopen("StudentRecords.txt", "w+");
    if (file_pointer == NULL)
    {
        printf("\nError Opening File StudentRecords.txt\nCreate File Manually and Try Again.");
        exit(1);
    }

    printf("\nENTER DETAILS FOR 5 STUDENTS\n");

    //TAKE 5 RECORDS FROM USERS AND SAVE THEM IN FILE-
    for (int i = 1; i <= 5; i++)
    {
        printf("\nStudent %d", i);
        fprintf(file_pointer, "Student %d", i);

        printf("\nName : ");
        scanf("%s", &name);
        fprintf(file_pointer, "\nName : %s", name);

        printf("Roll No : ");
        scanf("%s", &roll_no);
        fprintf(file_pointer, "\nRoll No : %s", roll_no);

        printf("Class : ");
        scanf("%s", &class);
        fprintf(file_pointer, "\nClass : %s", class);

        printf("Semester : ");
        scanf("%s", &semester);
        fprintf(file_pointer, "\nSemester : %s", semester);

        printf("Course : ");
        scanf("%s", course);
        fprintf(file_pointer, "\nCourse : %s", course);

        printf("\n");
        fprintf(file_pointer, "\n\n");
    }

    //READ ENTIRE FILE WORD BY WORD
    char c;
    c = fgetc(file_pointer);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(file_pointer);
    }

    fclose(file_pointer);
}
</code>```

答:
When you write/read in a file you use a stream (FILE*) that stores where in the file you are (position).

When you finished writting that was the last stream position.

You need to go back to the begin of the file if you want to read it entirely.

You can use fseek for this.

int fseek(FILE *stream, long int offset, int whence);

1  SEEK_SET : Beginning of file

2  SEEK_CUR : Current position of the file pointer

3  SEEK_END : End of file

```<code>...
//READ ENTIRE FILE WORD BY WORD
char c;

fseek(file_pointer, 0, SEEK_SET);

c = fgetc(file_pointer);
while (c != EOF)
{
    printf("%c", c);
    c = fgetc(file_pointer);
}
</code>```

Title: File Reading in C returns empty

Body:
I'm able to write data into a file but when I read it, it prints an empty file. I tried to make 2 programs one to write to file using permission "w" and one to read using "r" but when I combined both programs and changed permission to "w+" printing the files gives lots of empty spaces.

#include <stdio.h>
#include <stdlib.h>
void main()
{

    char name[20];
    char roll_no[15];
    char class[10];
    char semester[10];
    char course[20];

    FILE *file_pointer;
    file_pointer = fopen("StudentRecords.txt", "w+");
    if (file_pointer == NULL)
    {
        printf("\nError Opening File StudentRecords.txt\nCreate File Manually and Try Again.");
        exit(1);
    }

    printf("\nENTER DETAILS FOR 5 STUDENTS\n");

    //TAKE 5 RECORDS FROM USERS AND SAVE THEM IN FILE-
    for (int i = 1; i <= 5; i++)
    {
        printf("\nStudent %d", i);
        fprintf(file_pointer, "Student %d", i);

        printf("\nName : ");
        scanf("%s", &name);
        fprintf(file_pointer, "\nName : %s", name);

        printf("Roll No : ");
        scanf("%s", &roll_no);
        fprintf(file_pointer, "\nRoll No : %s", roll_no);

        printf("Class : ");
        scanf("%s", &class);
        fprintf(file_pointer, "\nClass : %s", class);

        printf("Semester : ");
        scanf("%s", &semester);
        fprintf(file_pointer, "\nSemester : %s", semester);

        printf("Course : ");
        scanf("%s", course);
        fprintf(file_pointer, "\nCourse : %s", course);

        printf("\n");
        fprintf(file_pointer, "\n\n");
    }

    //READ ENTIRE FILE WORD BY WORD
    char c;
    c = fgetc(file_pointer);
    while (c != EOF)
    {
        printf("%c", c);
        c = fgetc(file_pointer);
    }

    fclose(file_pointer);
}

Body:
When you write/read in a file you use a stream (FILE*) that stores where in the file you are (position).

When you finished writting that was the last stream position.

You need to go back to the begin of the file if you want to read it entirely.

You can use fseek for this.

int fseek(FILE *stream, long int offset, int whence);

1  SEEK_SET : Beginning of file

2  SEEK_CUR : Current position of the file pointer

3  SEEK_END : End of file

...
//READ ENTIRE FILE WORD BY WORD
char c;

fseek(file_pointer, 0, SEEK_SET);

c = fgetc(file_pointer);
while (c != EOF)
{
    printf("%c", c);
    c = fgetc(file_pointer);
}


来源: stackexchange

问:
Unity3D Package Cache errors(?)
After deleting and installing Unity due to a problem it caused me, these errors appeared in the console. I've already tried to reinstall Unity but they won't go away.

EDIT: I get these errors in every project I open.

答: for me clicking reset packages to defaults in advanced of the package manager window </p>

ContentLicense: CC BY-SA 4.0

Title: Unity3D Package Cache errors(?)


问:
Flutter error: The getter 'length' was called on null
So, Heres the code of my student list..I am using sqlflite database to store student collection.. but when i run this.. this shows error in my futurebuilder method . I am getting my error in the snapshot.data.lenght line where the error shows that length should not be null thats why i tried some conditions but still not working

```<code>class StudentListPage extends StatefulWidget {
  @override
  _StudentListPageState createState() => _StudentListPageState();
}

class _StudentListPageState extends State<StudentListPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Student List'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add,color: Colors.white,),
            onPressed: (){
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context)=>AddStudentPage()
              ));
            },
          )
        ],
      ),
      body: FutureBuilder(
        future: DBHelpers.getAllStudent(),
        builder: (context,AsyncSnapshot<List<StudentModels>> snapshot)=>
        snapshot.connectionState==ConnectionState.waiting?
        Center(
          child: CircularProgressIndicator(),
        ):
        Padding(
          child:snapshot.data.length !=0? ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context,index)=>StudentItems(snapshot.data[index])):
          Center(

            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                RaisedButton(
                  elevation: 5,
                  color: Theme.of(context).primaryColor,
                  child: Text("Click me To add Employee", style: TextStyle(color: Colors.white),),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  onPressed: (){

                  },
                )
              ],
            ),

          ),
        ),
      ),
    );
  }
}
</code>```

That is my database helper code :

```<code>class DBHelpers{

  static final String CREATE_TABLE=''' create table $TABLE_STUDENT(
  $COL_STUDENT_ID integer primary key autoincrement,
  $COL_STUDENT_NAME text not null,
  $COL_STUDENT_PHONE integer not null,
  $COL_STUDENT_EMAIL text not null,
  $COL_STUDENT_FAVOURITE text )''';

  static Future<Database> open() async{
    final dbpath=await getDatabasesPath();
    final path=Path.join(dbpath,'student.db');
    return openDatabase(path,version: 1,onCreate: (db,version) async{
      db.execute(CREATE_TABLE);
    });
  }

  static Future<int> insertStudent(String table,Map<String,dynamic> map) async{
    final db=await open();
    return db.insert(table, map,conflictAlgorithm: ConflictAlgorithm.replace);
  }

  static Future<List<StudentModels>> getAllStudent() async{
      final db=await open();
      final List<Map<String,dynamic>> map=await db.query(TABLE_STUDENT,orderBy: COL_STUDENT_NAME);
      return List.generate(map.length, (index){
        return StudentModels.fromMap(map[index]);
      });
  }

}
</code>```

This is my students_model:

```<code>final String TABLE_STUDENT='tbl_student';
final String COL_STUDENT_ID='col_id';
final String COL_STUDENT_NAME='col_name';
final String COL_STUDENT_EMAIL='col_email';
final String COL_STUDENT_PHONE='col_phone';
final String COL_STUDENT_FAVOURITE='col_fav';

class StudentModels{
  int id;
  String name;
  String email;
  int phoneNumber;
  bool isFavourite;

  StudentModels({
      this.id, this.name, this.email, this.phoneNumber, this.isFavourite=false
  });

  @override
  String toString() {
    return 'StudentModels{id: $id, name: $name, email: $email, phoneNumber: $phoneNumber, isFavourite: $isFavourite}';
  }

  Map<String,dynamic> toMap(){
    var map=<String,dynamic>{
      COL_STUDENT_NAME:name,
      COL_STUDENT_EMAIL:email,
      COL_STUDENT_PHONE:phoneNumber,
      COL_STUDENT_FAVOURITE:isFavourite,
    };
    if(id!=null){
      map[COL_STUDENT_ID]=id;
    }
    return map;
  }

  StudentModels.fromMap(Map<String,dynamic> map){
    name=map[COL_STUDENT_NAME];
    id=map[COL_STUDENT_ID];
    email=map[COL_STUDENT_EMAIL];
    phoneNumber=map[COL_STUDENT_PHONE];
    isFavourite=map[COL_STUDENT_FAVOURITE];
  }

}
</code>```

And this is the Error that I am getting eaach time i run it:

```<code>E/SQLiteLog(11830): (1) no such table: tbl_student
I/flutter (11830): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (11830): The following NoSuchMethodError was thrown building FutureBuilder<List<StudentModels>>(dirty, state:
I/flutter (11830): _FutureBuilderState<List<StudentModels>>#1afc9):
I/flutter (11830): The getter 'length' was called on null.
I/flutter (11830): Receiver: null
I/flutter (11830): Tried calling: length
I/flutter (11830):
I/flutter (11830): The relevant error-causing widget was:
I/flutter (11830):   FutureBuilder<List<StudentModels>>
I/flutter (11830):   file:///D:/flutterapps/first_flutter_app/lib/pages/student_list.dart:29:13
I/flutter (11830):
I/flutter (11830): When the exception was thrown, this was the stack:
I/flutter (11830): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
I/flutter (11830): #1      _StudentListPageState.build.<anonymous closure> (package:first_flutter_app/pages/student_list.dart:37:31)
I/flutter (11830): #2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
I/flutter (11830): #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
I/flutter (11830): #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
I/flutter (11830): #5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter (11830): #6      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter (11830): #7      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
I/flutter (11830): #8      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:20)
I/flutter (11830): #9      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
I/flutter (11830): #10     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
I/flutter (11830): #11     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
I/flutter (11830): #12     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
I/flutter (11830): #16     _invoke (dart:ui/hooks.dart:261:10)
I/flutter (11830): #17     _drawFrame (dart:ui/hooks.dart:219:3)
I/flutter (11830): (elided 3 frames from dart:async)
I/flutter (11830):
I/flutter (11830): ════════════════════════════════════════════════════════════════════════════════════════════════════
E/SQLiteLog(11830): (1) no such table: tbl_student

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<List<StudentModels>>(dirty, state: _FutureBuilderState<List<StudentModels>>#1afc9):
The getter 'length' was called on null.
Receiver: null
Tried calling: length

The relevant error-causing widget was:
  FutureBuilder<List<StudentModels>> file:///D:/flutterapps/first_flutter_app/lib/pages/student_list.dart:29:13
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _StudentListPageState.build.<anonymous closure> (package:first_flutter_app/pages/student_list.dart:37:31)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
</code>```

答:
try this on snapshot recive</p>

```<code>builder: (context,AsyncSnapshot<List<StudentModels>> snapshot) {
   //progress UI
  if (snapshot.connectionState != ConnectionState.done)
                return Center(child: Circular Progress Indicator());

  //load null data UI
  if (!snapshot.hasData || snapshot.data == null)
                return Container();

  //load empty data UI
  if (snapshot.data.isEmpty)
                return Container();

 //enter your code to show data
 //show the list of student model
...
</code>```

Body:
So, Heres the code of my student list..I am using sqlflite database to store student collection.. but when i run this.. this shows error in my futurebuilder method . I am getting my error in the snapshot.data.lenght line where the error shows that length should not be null thats why i tried some conditions but still not working

class StudentListPage extends StatefulWidget {
  @override
  _StudentListPageState createState() => _StudentListPageState();
}

class _StudentListPageState extends State<StudentListPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Student List'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add,color: Colors.white,),
            onPressed: (){
              Navigator.of(context).push(MaterialPageRoute(
                builder: (context)=>AddStudentPage()
              ));
            },
          )
        ],
      ),
      body: FutureBuilder(
        future: DBHelpers.getAllStudent(),
        builder: (context,AsyncSnapshot<List<StudentModels>> snapshot)=>
        snapshot.connectionState==ConnectionState.waiting?
        Center(
          child: CircularProgressIndicator(),
        ):
        Padding(
          child:snapshot.data.length !=0? ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context,index)=>StudentItems(snapshot.data[index])):
          Center(

            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                RaisedButton(
                  elevation: 5,
                  color: Theme.of(context).primaryColor,
                  child: Text("Click me To add Employee", style: TextStyle(color: Colors.white),),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  onPressed: (){

                  },
                )
              ],
            ),

          ),
        ),
      ),
    );
  }
}

That is my database helper code :

class DBHelpers{

  static final String CREATE_TABLE=''' create table $TABLE_STUDENT(
  $COL_STUDENT_ID integer primary key autoincrement,
  $COL_STUDENT_NAME text not null,
  $COL_STUDENT_PHONE integer not null,
  $COL_STUDENT_EMAIL text not null,
  $COL_STUDENT_FAVOURITE text )''';

  static Future<Database> open() async{
    final dbpath=await getDatabasesPath();
    final path=Path.join(dbpath,'student.db');
    return openDatabase(path,version: 1,onCreate: (db,version) async{
      db.execute(CREATE_TABLE);
    });
  }

  static Future<int> insertStudent(String table,Map<String,dynamic> map) async{
    final db=await open();
    return db.insert(table, map,conflictAlgorithm: ConflictAlgorithm.replace);
  }

  static Future<List<StudentModels>> getAllStudent() async{
      final db=await open();
      final List<Map<String,dynamic>> map=await db.query(TABLE_STUDENT,orderBy: COL_STUDENT_NAME);
      return List.generate(map.length, (index){
        return StudentModels.fromMap(map[index]);
      });
  }

}

This is my students_model:

final String TABLE_STUDENT='tbl_student';
final String COL_STUDENT_ID='col_id';
final String COL_STUDENT_NAME='col_name';
final String COL_STUDENT_EMAIL='col_email';
final String COL_STUDENT_PHONE='col_phone';
final String COL_STUDENT_FAVOURITE='col_fav';

class StudentModels{
  int id;
  String name;
  String email;
  int phoneNumber;
  bool isFavourite;

  StudentModels({
      this.id, this.name, this.email, this.phoneNumber, this.isFavourite=false
  });

  @override
  String toString() {
    return 'StudentModels{id: $id, name: $name, email: $email, phoneNumber: $phoneNumber, isFavourite: $isFavourite}';
  }

  Map<String,dynamic> toMap(){
    var map=<String,dynamic>{
      COL_STUDENT_NAME:name,
      COL_STUDENT_EMAIL:email,
      COL_STUDENT_PHONE:phoneNumber,
      COL_STUDENT_FAVOURITE:isFavourite,
    };
    if(id!=null){
      map[COL_STUDENT_ID]=id;
    }
    return map;
  }

  StudentModels.fromMap(Map<String,dynamic> map){
    name=map[COL_STUDENT_NAME];
    id=map[COL_STUDENT_ID];
    email=map[COL_STUDENT_EMAIL];
    phoneNumber=map[COL_STUDENT_PHONE];
    isFavourite=map[COL_STUDENT_FAVOURITE];
  }

}

And this is the Error that I am getting eaach time i run it:

E/SQLiteLog(11830): (1) no such table: tbl_student
I/flutter (11830): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (11830): The following NoSuchMethodError was thrown building FutureBuilder<List<StudentModels>>(dirty, state:
I/flutter (11830): _FutureBuilderState<List<StudentModels>>#1afc9):
I/flutter (11830): The getter 'length' was called on null.
I/flutter (11830): Receiver: null
I/flutter (11830): Tried calling: length
I/flutter (11830):
I/flutter (11830): The relevant error-causing widget was:
I/flutter (11830):   FutureBuilder<List<StudentModels>>
I/flutter (11830):   file:///D:/flutterapps/first_flutter_app/lib/pages/student_list.dart:29:13
I/flutter (11830):
I/flutter (11830): When the exception was thrown, this was the stack:
I/flutter (11830): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
I/flutter (11830): #1      _StudentListPageState.build.<anonymous closure> (package:first_flutter_app/pages/student_list.dart:37:31)
I/flutter (11830): #2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
I/flutter (11830): #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
I/flutter (11830): #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
I/flutter (11830): #5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter (11830): #6      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter (11830): #7      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2627:33)
I/flutter (11830): #8      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:883:20)
I/flutter (11830): #9      RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
I/flutter (11830): #10     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
I/flutter (11830): #11     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
I/flutter (11830): #12     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
I/flutter (11830): #16     _invoke (dart:ui/hooks.dart:261:10)
I/flutter (11830): #17     _drawFrame (dart:ui/hooks.dart:219:3)
I/flutter (11830): (elided 3 frames from dart:async)
I/flutter (11830):
I/flutter (11830): ════════════════════════════════════════════════════════════════════════════════════════════════════
E/SQLiteLog(11830): (1) no such table: tbl_student

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<List<StudentModels>>(dirty, state: _FutureBuilderState<List<StudentModels>>#1afc9):
The getter 'length' was called on null.
Receiver: null
Tried calling: length

The relevant error-causing widget was:
  FutureBuilder<List<StudentModels>> file:///D:/flutterapps/first_flutter_app/lib/pages/student_list.dart:29:13
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      _StudentListPageState.build.<anonymous closure> (package:first_flutter_app/pages/student_list.dart:37:31)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:732:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)

Body:
try this on snapshot recive

builder: (context,AsyncSnapshot<List<StudentModels>> snapshot) {
   //progress UI
  if (snapshot.connectionState != ConnectionState.done)
                return Center(child: Circular Progress Indicator());

  //load null data UI
  if (!snapshot.hasData || snapshot.data == null)
                return Container();

  //load empty data UI
  if (snapshot.data.isEmpty)
                return Container();

 //enter your code to show data
 //show the list of student model
...


问:
Uploadify is not passing through the scriptData parameters
I'm using the Uploadify script on my site and I'm trying to set the scriptData parameter based on some form fields.  This is the HTML/JS:

```<code><script type="text/javascript">

    function UploadFile() {
        $('#file_upload').uploadifySettings({
            scriptData: $('#uploadForm').serializeObject()
        });

        $('#file_upload').uploadifyUpload();
    }

    $(document).ready(function () {
        $('#file_upload').uploadify({
            'uploader': '/Scripts/uploadify/uploadify.swf',
            'script': '/File/Upload',
            'cancelImg': '/Scripts/uploadify/cancel.png',
            'folder': '/uploads',
            'fileExt': '*.doc, *.pdf',
            'buttonText': 'Select File',
            'auto': false,
            'onSelect': function (event, ID, fileObj) {
                $('#uploadForm #FileName').val(fileObj.name);
            }
        });
    });
</script>
<form id="uploadForm">
<div><label for="Description">Description</label> <input id="Description" name="Description" type="text" value="" /></div>
<div><label for="FileName">File Name</label> <input id="FileName" name="FileName" type="text" value="" /></div>    <input id="file_upload" name="file_upload" type="file" />
<button onclick="UploadFile();" type="button">Upload</button>
</form>
</code>```

serializeObject is just using the serializeobject jQuery plugin to turn the form values into a json object

It uploads the file fine, but nothing in scriptData gets sent.  I've checked in fiddler & the only form values are the ones from the uploadify script: folder, fileext, Filedata & Upload.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Uploadify script on my site and I'm trying to set the scriptData parameter based on some form fields.  This is the HTML/JS:

<form id="uploadForm">

Description <input id="Description" name="Description" type="text" value="" />

File Name <input id="FileName" name="FileName" type="text" value="" />
    <input id="file_upload" name="file_upload" type="file" />
<button onclick="UploadFile();" type="button">Upload</button>
</form>

serializeObject is just using the serializeobject jQuery plugin to turn the form values into a json object

It uploads the file fine, but nothing in scriptData gets sent.  I've checked in fiddler & the only form values are the ones from the uploadify script: folder, fileext, Filedata & Upload.

Body:
I wear this:

 'formData' : {
 'data'      : 'Hello Word',
 'timestamp' : '2020-05-30 16:06:30',
 'token'     : '59284aa85709ddaf3bd246030060f6a2'
},


问:
Why does the control goes back to the caller function after the execution of the first await statement in an async function?
Here's the code:

function B() {
  return 'B';
}

async function test(b) {
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

console.log('A');
test(B);
console.log('C');
console.log('P');```

This output's to A Z C P B X hihihi

Question is:

Why does the control goes to the caller function(that called the async function) after executing the first await statement? How's it useful?

What's to be done to force execute all await statements one after the other somehow preventing it from going to the caller function?

答:
Right now, your single node thread sees an order of execution that looks like this

console.log('A') // > A
test(B) // oh okay, looks like an async function call. i'll start this off and move on
console.log('C'); // > C
console.log('P'); // > P
```

<p>When <code>test(B)</code> is called, another "thread" of sorts handles the execution. This is all because <code>test</code> is an async function, so every operation inside that function is handled a bit differently than a regular synchronous function.</p>

<p>If you want them all to appear in order, you can use another async function and <code>await test(B)</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function B(){
  return 'B';
}

async function test(b){
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

async function main() {
  console.log('A');
  await test(B);
  console.log('C');
  console.log('P');
}

main()</code>```

All of this is pretty useful because of a nodejs thing called non-blocking io. Here's a question that could shed some light on that.

Here is node's very own explanation of the event loop, which is a key concept for understanding non-blocking io

Body:
Here's the code:

function B() {
  return 'B';
}

async function test(b) {
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

console.log('A');
test(B);
console.log('C');
console.log('P');

This output's to A Z C P B X hihihi

Question is:

Why does the control goes to the caller function(that called the async function) after executing the first await statement? How's it useful?

What's to be done to force execute all await statements one after the other somehow preventing it from going to the caller function?

Body:
Right now, your single node thread sees an order of execution that looks like this

console.log('A') // > A
test(B) // oh okay, looks like an async function call. i'll start this off and move on
console.log('C'); // > C
console.log('P'); // > P

When test(B) is called, another "thread" of sorts handles the execution. This is all because test is an async function, so every operation inside that function is handled a bit differently than a regular synchronous function.

If you want them all to appear in order, you can use another async function and await test(B)

function B(){
  return 'B';
}

async function test(b){
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

async function main() {
  console.log('A');
  await test(B);
  console.log('C');
  console.log('P');
}

main()

All of this is pretty useful because of a nodejs thing called non-blocking io. Here's a question that could shed some light on that.

Here is node's very own explanation of the event loop, which is a key concept for understanding non-blocking io


问:
Normalize dataset so that median is 0.5
I have a dataset of positive integers that I want to scale so that the output range is [0.0,1.0] and the median maps to 0.5.

Is this possible to do at all?

If so, how can I do it in Python using scipy or sklearn?

答: This is mathematically impossible to do in general with a linear scale plus translation (that is x[i] = a*x[i] + b).

Title: Normalize dataset so that median is 0.5


问:
init function TypeError: Cannot read property 'style' of null
No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.

I get the message that all these lines are wrong

I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.

document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';

```<code>var scores, roundScore, activePlayer, gamePlaying;

var lastDice;

function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}

document.querySelector('.btn-new').addEventListener('click', init);

init();

</code>```

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
        <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="style.css">
        <title>Pig Game</title>
    </head>

    <body>
        <div class="wrapper clearfix">
            <div class="player-0-panel active">
                <div class="player-name" id="name-0">Player 1</div>
                <div class="player-score" id="score-0">43</div>
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="current-0">11</div>
                </div>
            </div>

            <div class="player-1-panel">
                <div class="player-name" id="name-1">Player 2</div>
                <div class="player-score" id="score-1">72</div>
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="current-1">0</div>
                </div>
            </div>

            <button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
            <button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
            <button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>

            <input type="text" placeholder="Final Score" class="final-score">

            <img src="dice-5.png" alt="Dice" class="dice">
        </div>

        <script type='text/javascript' src="challenges.js"></script>
    </body>
</html>
</code>```

```<code>/**********************************************
*** GENERAL
**********************************************/

.final-score {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 520px;
    color: #555;
    font-size: 18px;
    font-family: 'Lato';
    text-align: center;
    padding: 10px;
    width: 160px;
    text-transform: uppercase;
}

.final-score:focus { outline: none; }

dice-1 { top: 120px; }
#dice-2 { top: 250px; }

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

body {
    background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
    background-size: cover;
    background-position: center;
    font-family: Lato;
    font-weight: 300;
    position: relative;
    height: 100vh;
    color: #555;
}

.wrapper {
    width: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.player-0-panel,
.player-1-panel {
    width: 50%;
    float: left;
    height: 600px;
    padding: 100px;
}

/**********************************************
*** PLAYERS
**********************************************/

.player-name {
    font-size: 40px;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: 100;
    margin-top: 20px;
    margin-bottom: 10px;
    position: relative;
}

.player-score {
    text-align: center;
    font-size: 80px;
    font-weight: 100;
    color: #EB4D4D;
    margin-bottom: 130px;
}

.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }

.active .player-name::after {
    content: "\2022";
    font-size: 47px;
    position: absolute;
    color: #EB4D4D;
    top: -7px;
    right: 10px;

}

.player-current-box {
    background-color: #EB4D4D;
    color: #fff;
    width: 40%;
    margin: 0 auto;
    padding: 12px;
    text-align: center;
}

.player-current-label {
    text-transform: uppercase;
    margin-bottom: 10px;
    font-size: 12px;
    color: #222;
}

.player-current-score {
    font-size: 30px;
}

button {
    position: absolute;
    width: 200px;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    background: none;
    border: none;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }

button:focus {
    outline: none;
}

i {
    color: #EB4D4D;
    display: inline-block;
    margin-right: 15px;
    font-size: 32px;
    line-height: 1;
    vertical-align: text-top;
    margin-top: -4px;
    transition: margin 0.3s;
}

.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}

.dice {
    position: absolute;
    left: 50%;
    top: 178px;
    transform: translateX(-50%);
    height: 100px;
    box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}

.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }
</code>```

Please help me.

答: I don't see element with id="dice-1" or id="dice-2" in your template (HTML), so the error just means, that element with that id doesn't exist, so it's value is null.</p>

Body:
No matter how I wrote the code, I received the same message and I've been trying to fix this since last night, but I don't understand why this is bothering me so much.

I get the message that all these lines are wrong

I work according to my course and this code is from a course that works on video and it doesn't work for me, I've tried a lot of changes but it doesn't work.

document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';

var scores, roundScore, activePlayer, gamePlaying;

var lastDice;

function init() {
    scores = [0, 0];
    activePlayer = 0;
    roundScore = 0;
    gamePlaying = true;

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';

    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');
}

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(gamePlaying) {
        var dice1 = Math.floor(Math.random() * 6) + 1;
        var dice2 = Math.floor(Math.random() * 6) + 1;

        document.getElementById('dice-1').style.display = 'block';
        document.getElementById('dice-2').style.display = 'block';
        document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
        document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';

        if (dice1 !== 1 && dice2 !== 1) {
            roundScore += dice1 + dice2;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;
        } else {
            nextPlayer();
        }
    }
});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        scores[activePlayer] += roundScore;

        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        var input = document.querySelector('.final-score').value;
        var winningScore;

        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }

        // Check if player won the game
        if (scores[activePlayer] >= winningScore) {
            document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
            document.getElementById('dice-2').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer() {
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;

    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    document.getElementById('dice-1').style.display = 'none';
    document.getElementById('dice-2').style.display = 'none';
}

document.querySelector('.btn-new').addEventListener('click', init);

init();

<!DOCTYPE html>

        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
        <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="style.css">
        <title>Pig Game</title>

Player 1

43

Current

11

Player 2

72

Current

0

            <button class="btn-new">New game</button>
            <button class="btn-roll">Roll dice</button>
            <button class="btn-hold">Hold</button>

            <input type="text" placeholder="Final Score" class="final-score">

/**********************************************
*** GENERAL
**********************************************/

.final-score {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    top: 520px;
    color: #555;
    font-size: 18px;
    font-family: 'Lato';
    text-align: center;
    padding: 10px;
    width: 160px;
    text-transform: uppercase;
}

.final-score:focus { outline: none; }

dice-1 { top: 120px; }
#dice-2 { top: 250px; }

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

body {
    background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
    background-size: cover;
    background-position: center;
    font-family: Lato;
    font-weight: 300;
    position: relative;
    height: 100vh;
    color: #555;
}

.wrapper {
    width: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
    overflow: hidden;
}

.player-0-panel,
.player-1-panel {
    width: 50%;
    float: left;
    height: 600px;
    padding: 100px;
}

/**********************************************
*** PLAYERS
**********************************************/

.player-name {
    font-size: 40px;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-weight: 100;
    margin-top: 20px;
    margin-bottom: 10px;
    position: relative;
}

.player-score {
    text-align: center;
    font-size: 80px;
    font-weight: 100;
    color: #EB4D4D;
    margin-bottom: 130px;
}

.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }

.active .player-name::after {
    content: "\2022";
    font-size: 47px;
    position: absolute;
    color: #EB4D4D;
    top: -7px;
    right: 10px;

}

.player-current-box {
    background-color: #EB4D4D;
    color: #fff;
    width: 40%;
    margin: 0 auto;
    padding: 12px;
    text-align: center;
}

.player-current-label {
    text-transform: uppercase;
    margin-bottom: 10px;
    font-size: 12px;
    color: #222;
}

.player-current-score {
    font-size: 30px;
}

button {
    position: absolute;
    width: 200px;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    background: none;
    border: none;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }

button:focus {
    outline: none;
}

i {
    color: #EB4D4D;
    display: inline-block;
    margin-right: 15px;
    font-size: 32px;
    line-height: 1;
    vertical-align: text-top;
    margin-top: -4px;
    transition: margin 0.3s;
}

.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}

.dice {
    position: absolute;
    left: 50%;
    top: 178px;
    transform: translateX(-50%);
    height: 100px;
    box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}

.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }

Please help me.


问:
Segmentation fault (core dumped) - argv - c
I am trying to open a txt file for a program entering the name of the file as a command line argument. if I provide the path as a string it works, so the problem in my code is with the command line argument. I have the following:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char* argv[])
{
    char* filename = "/path/";
    char* name = argv[1];
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);
    printf("%s\n", filename);
    strcat(filename, ".txt");
    printf("%s\n", filename);
    return 0;
}
</code>```

I run it like so:

./program filenamewithoutextension

I get the following output when I run it:

```<code>/path/
filenamewithoutextension
Segmentation fault (core dumped)
</code>```

I don't understand what is happening.

答:
Note that in your code snippet filename and name are just pointers which point to read-only data, so you cannot modify the data they point to.

You can dynamically allocate memory using malloc in order to be able to edit the data they point to. Or just allocate memory for them in stack like, filename[100] or name[100].

Your code should be like that:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char* argv[])
{
    char filename[100];
    char name[100];
    strcpy(filename, "/path/");
    strcpy(name, argv[1]);
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);//You can safely modify name now
    printf("%s\n", filename);
    strcat(filename, ".txt");//You can safely modify filename now
    printf("%s\n", filename);
    return 0;
}
</code>```

Body:
I am trying to open a txt file for a program entering the name of the file as a command line argument. if I provide the path as a string it works, so the problem in my code is with the command line argument. I have the following:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char* argv[])
{
    char* filename = "/path/";
    char* name = argv[1];
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);
    printf("%s\n", filename);
    strcat(filename, ".txt");
    printf("%s\n", filename);
    return 0;
}

I run it like so:

./program filenamewithoutextension

I get the following output when I run it:

/path/
filenamewithoutextension
Segmentation fault (core dumped)

I don't understand what is happening.

Body:
Note that in your code snippet filename and name are just pointers which point to read-only data, so you cannot modify the data they point to.

You can dynamically allocate memory using malloc in order to be able to edit the data they point to. Or just allocate memory for them in stack like, filename[100] or name[100].

Your code should be like that:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char* argv[])
{
    char filename[100];
    char name[100];
    strcpy(filename, "/path/");
    strcpy(name, argv[1]);
    printf("%s\n", filename);
    printf("%s\n", name);
    strcat(filename, name);//You can safely modify name now
    printf("%s\n", filename);
    strcat(filename, ".txt");//You can safely modify filename now
    printf("%s\n", filename);
    return 0;
}


问:
Why does Tkinter make a new window for my button?
Im trying to add a button into my window, but it makes a new window for the button, how can I add it to the same window where I have a background on?</p>

```<code>from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
from PIL import ImageTk

top = Tk()

C = Canvas(top, bg ="blue", height=1920, width=1080)
filename = ImageTk.PhotoImage(file = "C:/Users/plapl/Desktop/ching.jpg")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

root = Tk()

myButton = Button(root, text = "Add a task")
myButton.pack()

root.mainloop()
</code>```

答:
This happens because you have 2 Tk() objects, which means that 2 windows are created. To solve this, change the line: background_label = Label(top, image=filename) to this: background_label = Label(root, image=filename).

Then, you can get rid of this line: top = Tk() because it isn't needed anymore.

Body:
Im trying to add a button into my window, but it makes a new window for the button, how can I add it to the same window where I have a background on?

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
from PIL import ImageTk

top = Tk()

C = Canvas(top, bg ="blue", height=1920, width=1080)
filename = ImageTk.PhotoImage(file = "C:/Users/plapl/Desktop/ching.jpg")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

root = Tk()

myButton = Button(root, text = "Add a task")
myButton.pack()

root.mainloop()


问:
How to access elements in a specific way in json?
I want to learn JSON and I am using Python. I currently have a question about how to access elements. Here would be a generic example of the JSON information:

```<code>"data":{
   "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}
</code>```

Now, I would want to make a for loop that gets a list of all the names that are age 30. How am I going to do this. I tried doing something like this:

```<code>array = []
for x in range(0,3):
    if data[x]['age'] is '30'
    array.append(data[x])
</code>```

but that is definitely wrong. Can somebody teach me how to sort the items in JSON in this way?

答:
Try this:

```<code>data = {
  "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}

names = []
for name, information in data.items():
    if information['age'] == '30':
        names.append(name)

print(names)
</code>```

If you have a dictionary object called data, you can use data.items() to iterate over the keys ('Bob', 'Joe', 'Tom') and values of the dictionary. You could check out the documentation here: https://docs.python.org/3/library/stdtypes.html#dict.items

Body:
I want to learn JSON and I am using Python. I currently have a question about how to access elements. Here would be a generic example of the JSON information:

"data":{
   "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}

Now, I would want to make a for loop that gets a list of all the names that are age 30. How am I going to do this. I tried doing something like this:

array = []
for x in range(0,3):
    if data[x]['age'] is '30'
    array.append(data[x])

but that is definitely wrong. Can somebody teach me how to sort the items in JSON in this way?

Body:
Try this:

data = {
  "Bob":{
      "name":"Bob",
      "age":"30",
      "state":"California",
      "job":"accountant"
   },
   "Joe":{
      "name":"Bob",
      "age":"30",
      "state":"Florida",
      "job":"engineer"
   },
   "Tom":{
      "name":"Bob",
      "age":"25",
      "state":"North Dakota",
      "job":"manager"
   }
}

names = []
for name, information in data.items():
    if information['age'] == '30':
        names.append(name)

print(names)

If you have a dictionary object called data, you can use data.items() to iterate over the keys ('Bob', 'Joe', 'Tom') and values of the dictionary. You could check out the documentation here: https://docs.python.org/3/library/stdtypes.html#dict.items


问:
jQuery - Pre-select from dropdown menu
I have a function to select menu options but even though the item is selected when the dropdown is clicked, it isn't pre-selected on load. In other words the .selected is not receiving the name of the active li.

var selected = $(".selected");
var dropdown = $(".dropdown-list");
var optionList = $(".dropdown-list li");

function menuClick() {
  selected.click(function() {
    dropdown.toggleClass("active");

    if (dropdown.hasClass("active")) {
      optionList.click(function() {
        if (optionList.hasClass("active")) {
          $(this).siblings().removeClass("active");
        } else {
          $(this).addClass("active");
        }
        dropdown.removeClass("active");
        selected.children("span").html($(this).html());
      });
    }
  });
}
menuClick();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import "https://fonts.googleapis.com/css?family=Dosis:300,400,500,700";
.dropdown {
  position: relative;
  width: 90px;
  display: block;
}

.dropdown .selected {
  align-items: center;
  display: flex;
  padding: 1rem;
  cursor: pointer;
  -webkit-transition: all .2s ease-in-out;
  transition: all .2s ease-in-out;
}

.dropdown .selected i {
  position: absolute;
  right: 0.5rem;
}

.dropdown .selected:hover {
  /*box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24) !important;*/
}

.dropdown .dropdown-list {
  position: absolute;
  top: 0;
  width: 100%;
  max-height: 0;
  list-style-type: none;
  padding: 0;
  margin: 0;
  background: white;
  box-shadow: 1px 4px 7px 0px #00000012 !important;
  opacity: 0;
  visibility: hidden;
  overflow: hidden;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  -webkit-transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
  transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
}

.dropdown .dropdown-list li {
  padding: 1rem;
  display: block;
  cursor: pointer;
  -webkit-transition: all 200ms ease;
  transition: all 200ms ease;
}

.dropdown .dropdown-list li.active {
  background: rgba(63, 81, 181, 0.1);
}

.dropdown .dropdown-list li:not(.active):hover {
  background: rgba(63, 81, 181, 0.02);
}

.dropdown .dropdown-list.active {
  opacity: 1;
  visibility: visible;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  max-height: 260px;
  overflow: auto;
  z-index: 999;
}</code>```

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Refine keyboard_arrow_down

All Time

Recent

Today

```

答:
You just need a simple filter on the active element to get it's text into the span on page load

Something like:

```<code>selected.find('span').text(function(){
    return optionList.filter('.active').text()
})
</code>```

var selected = $(".selected");
var dropdown = $(".dropdown-list");
var optionList = $(".dropdown-list li");

// set the selected text on page load based on current active item
selected.find('span').text(function(){
    return optionList.filter('.active').text()
})

function menuClick() {
  selected.click(function() {
    dropdown.toggleClass("active");

    if (dropdown.hasClass("active")) {
      optionList.click(function() {
        if (optionList.hasClass("active")) {
          $(this).siblings().removeClass("active");
        } else {
          $(this).addClass("active");
        }
        dropdown.removeClass("active");
        selected.children("span").html($(this).html());
      });
    }
  });
}

menuClick();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import "https://fonts.googleapis.com/css?family=Dosis:300,400,500,700";
.dropdown {
  position: relative;
  width: 90px;
  display: block;
}

.dropdown .selected {
  align-items: center;
  display: flex;
  padding: 1rem;
  cursor: pointer;
  -webkit-transition: all .2s ease-in-out;
  transition: all .2s ease-in-out;
}

.dropdown .selected i {
  position: absolute;
  right: 0.5rem;
}

.dropdown .selected:hover {
  /*box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24) !important;*/
}

.dropdown .dropdown-list {
  position: absolute;
  top: 0;
  width: 100%;
  max-height: 0;
  list-style-type: none;
  padding: 0;
  margin: 0;
  background: white;
  box-shadow: 1px 4px 7px 0px #00000012 !important;
  opacity: 0;
  visibility: hidden;
  overflow: hidden;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  -webkit-transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
  transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
}

.dropdown .dropdown-list li {
  padding: 1rem;
  display: block;
  cursor: pointer;
  -webkit-transition: all 200ms ease;
  transition: all 200ms ease;
}

.dropdown .dropdown-list li.active {
  background: rgba(63, 81, 181, 0.1);
}

.dropdown .dropdown-list li:not(.active):hover {
  background: rgba(63, 81, 181, 0.02);
}

.dropdown .dropdown-list.active {
  opacity: 1;
  visibility: visible;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  max-height: 260px;
  overflow: auto;
  z-index: 999;
}</code>```

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Refine keyboard_arrow_down

All Time

Recent

Today

```

Title: jQuery - Pre-select from dropdown menu

Body:
I have a function to select menu options but even though the item is selected when the dropdown is clicked, it isn't pre-selected on load. In other words the .selected is not receiving the name of the active li.

var selected = $(".selected");
var dropdown = $(".dropdown-list");
var optionList = $(".dropdown-list li");

function menuClick() {
  selected.click(function() {
    dropdown.toggleClass("active");

    if (dropdown.hasClass("active")) {
      optionList.click(function() {
        if (optionList.hasClass("active")) {
          $(this).siblings().removeClass("active");
        } else {
          $(this).addClass("active");
        }
        dropdown.removeClass("active");
        selected.children("span").html($(this).html());
      });
    }
  });
}
menuClick();

@import "https://fonts.googleapis.com/css?family=Dosis:300,400,500,700";
.dropdown {
  position: relative;
  width: 90px;
  display: block;
}

.dropdown .selected {
  align-items: center;
  display: flex;
  padding: 1rem;
  cursor: pointer;
  -webkit-transition: all .2s ease-in-out;
  transition: all .2s ease-in-out;
}

.dropdown .selected i {
  position: absolute;
  right: 0.5rem;
}

.dropdown .selected:hover {
  /*box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24) !important;*/
}

.dropdown .dropdown-list {
  position: absolute;
  top: 0;
  width: 100%;
  max-height: 0;
  list-style-type: none;
  padding: 0;
  margin: 0;
  background: white;
  box-shadow: 1px 4px 7px 0px #00000012 !important;
  opacity: 0;
  visibility: hidden;
  overflow: hidden;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  -webkit-transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
  transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
}

.dropdown .dropdown-list li {
  padding: 1rem;
  display: block;
  cursor: pointer;
  -webkit-transition: all 200ms ease;
  transition: all 200ms ease;
}

.dropdown .dropdown-list li.active {
  background: rgba(63, 81, 181, 0.1);
}

.dropdown .dropdown-list li:not(.active):hover {
  background: rgba(63, 81, 181, 0.02);
}

.dropdown .dropdown-list.active {
  opacity: 1;
  visibility: visible;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  max-height: 260px;
  overflow: auto;
  z-index: 999;
}

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Refine keyboard_arrow_down

All Time

Recent

Today

Body:
You just need a simple filter on the active element to get it's text into the span on page load

Something like:

selected.find('span').text(function(){
    return optionList.filter('.active').text()
})

var selected = $(".selected");
var dropdown = $(".dropdown-list");
var optionList = $(".dropdown-list li");

// set the selected text on page load based on current active item
selected.find('span').text(function(){
    return optionList.filter('.active').text()
})

function menuClick() {
  selected.click(function() {
    dropdown.toggleClass("active");

    if (dropdown.hasClass("active")) {
      optionList.click(function() {
        if (optionList.hasClass("active")) {
          $(this).siblings().removeClass("active");
        } else {
          $(this).addClass("active");
        }
        dropdown.removeClass("active");
        selected.children("span").html($(this).html());
      });
    }
  });
}

menuClick();

@import "https://fonts.googleapis.com/css?family=Dosis:300,400,500,700";
.dropdown {
  position: relative;
  width: 90px;
  display: block;
}

.dropdown .selected {
  align-items: center;
  display: flex;
  padding: 1rem;
  cursor: pointer;
  -webkit-transition: all .2s ease-in-out;
  transition: all .2s ease-in-out;
}

.dropdown .selected i {
  position: absolute;
  right: 0.5rem;
}

.dropdown .selected:hover {
  /*box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24) !important;*/
}

.dropdown .dropdown-list {
  position: absolute;
  top: 0;
  width: 100%;
  max-height: 0;
  list-style-type: none;
  padding: 0;
  margin: 0;
  background: white;
  box-shadow: 1px 4px 7px 0px #00000012 !important;
  opacity: 0;
  visibility: hidden;
  overflow: hidden;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  -webkit-transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
  transition: all 0.2s cubic-bezier(0.17, 0.67, 0, 1);
}

.dropdown .dropdown-list li {
  padding: 1rem;
  display: block;
  cursor: pointer;
  -webkit-transition: all 200ms ease;
  transition: all 200ms ease;
}

.dropdown .dropdown-list li.active {
  background: rgba(63, 81, 181, 0.1);
}

.dropdown .dropdown-list li:not(.active):hover {
  background: rgba(63, 81, 181, 0.02);
}

.dropdown .dropdown-list.active {
  opacity: 1;
  visibility: visible;
  -webkit-transform: translateY(0%);
  transform: translateY(0%);
  max-height: 260px;
  overflow: auto;
  z-index: 999;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<div class="dropdown">
  <p class="selected"><span>Refine</span> <i class="material-icons">keyboard_arrow_down</i></p>
  <ul class="dropdown-list">
    <li class="active">All Time</li>
    <li>Recent</li>
    <li>Today</li>
  </ul>
</div>


问:
What is HEAD in Git?
You see the Git documentation saying things like

The branch must be fully merged in HEAD.

But what is Git HEAD exactly?

答:
Git is all about commits.

And Head points to the commit which you currently checked out.

```<code>$ git cat-file -t HEAD
commit
</code>```

Whenever you checkout a branch, the HEAD points to the latest commit on that branch. Contents of HEAD can checked as below (for master branch):

```<code>$ cat .git/refs/heads/master
  b089141cc8a7d89d606b2f7c15bfdc48640a8e25
</code>```

Title: What is HEAD in Git?

Body:
Git is all about commits.

And Head points to the commit which you currently checked out.

$ git cat-file -t HEAD
commit

Whenever you checkout a branch, the HEAD points to the latest commit on that branch. Contents of HEAD can checked as below (for master branch):

$ cat .git/refs/heads/master
  b089141cc8a7d89d606b2f7c15bfdc48640a8e25


问:
What is the "right" way to avoid Aliasing (e.g. when adding an element of a container to itself) in C++?
```<code>std::vector<int> a;
a.push_back(1);
a.push_back(a[0]);
</code>```

I just learned that the code above can be very dangerous.

(If it's not obvious why, you're not alone... it wasn't obvious to me either.)

My questions:

What is the "standard" way of dealing with it? Making a new variable and then assigning it immediately to something afterward seems a bit weird to me. Is there a better way of dealing with it?

How do you train yourself to watch out for aliasing issues like this? What pattern(s) do you look for? I have no idea to recognize this situation; I only learned about aliasing when I learned about the restrict keyword in C, and only now do I understand what the issue really is.

Edit:

I'd love to accept an answer, but it doesn't seem like part (2) of the question has been answered. I'm wondering what strategies people use to locate aliasing mistakes in code they have written.

One strategy I've come up with so far is to avoid passing in the same value for in two parameters. (In this case, one parameter is implicit and one explicit.)

Are there any other easy things to notice and watch out for?

答:
In push_back(const T& el); implementation to check if el is inside array or other internal storage. That is the only politically correct way of dealing with such problems.

Container should handle this as different containers - different safety rules.

Body:
std::vector<int> a;
a.push_back(1);
a.push_back(a[0]);

I just learned that the code above can be very dangerous.

(If it's not obvious why, you're not alone... it wasn't obvious to me either.)

My questions:

What is the "standard" way of dealing with it? Making a new variable and then assigning it immediately to something afterward seems a bit weird to me. Is there a better way of dealing with it?

How do you train yourself to watch out for aliasing issues like this? What pattern(s) do you look for? I have no idea to recognize this situation; I only learned about aliasing when I learned about the restrict keyword in C, and only now do I understand what the issue really is.

Edit:

I'd love to accept an answer, but it doesn't seem like part (2) of the question has been answered. I'm wondering what strategies people use to locate aliasing mistakes in code they have written.

One strategy I've come up with so far is to avoid passing in the same value for in two parameters. (In this case, one parameter is implicit and one explicit.)

Are there any other easy things to notice and watch out for?


问:
Abaqus Scripting KeyError
I am trying to do harmonic analysis using abaqus scripting. Everytime I run the code below, I get 'KeyError: XYPlot-1'. Any help would be greatly appreciated. TIA

```<code># -*- coding: mbcs -*-
# Do not delete the following import lines
from abaqus import *
from abaqusConstants import *
import __main__

def Macro1():
    import section
    import regionToolset
    import displayGroupMdbToolset as dgm
    import part
    import material
    import assembly
    import step
    import interaction
    import load
    import mesh
    import optimization
    import job
    import sketch
    import visualization
    import xyPlot
    import displayGroupOdbToolset as dgo
    import connectorBehavior
    s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=1.0)
    g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
    s.setPrimaryObject(option=STANDALONE)
    s.Line(point1=(0.0, 0.0), point2=(0.235000000051223, 0.0))
    s.HorizontalConstraint(entity=g[2], addUndoState=False)
    s.ObliqueDimension(vertex1=v[0], vertex2=v[1], textPoint=(0.140255361795425,
        0.0583333373069763), value=0.985)
    session.viewports['Viewport: 1'].view.setValues(nearPlane=0.686013,
        farPlane=1.19961, width=1.74884, height=0.832297, cameraPosition=(
        0.0144624, 0.0330418, 0.942809), cameraTarget=(0.0144624, 0.0330418,
        0))
    p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=TWO_D_PLANAR,
        type=DEFORMABLE_BODY)
    p = mdb.models['Model-1'].parts['Part-1']
    p.BaseWire(sketch=s)
    s.unsetPrimaryObject()
    p = mdb.models['Model-1'].parts['Part-1']
    session.viewports['Viewport: 1'].setValues(displayedObject=p)
    del mdb.models['Model-1'].sketches['__profile__']
    session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=ON,
        engineeringFeatures=ON)
    session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
        referenceRepresentation=OFF)
    mdb.models['Model-1'].Material(name='Stainless Steel',
        description='Creating of Material Properties for Stainless Steel 304')
    mdb.models['Model-1'].materials['Stainless Steel'].Density(table=((7930.0,
        ), ))
    mdb.models['Model-1'].materials['Stainless Steel'].Elastic(table=((
        200000000000.0, 0.31), ))
    mdb.models['Model-1'].PipeProfile(name='Profile-1', r=0.008, t=0.0015)
    mdb.models['Model-1'].BeamSection(name='Tube Section',
        integration=DURING_ANALYSIS, poissonRatio=0.0, profile='Profile-1',
        material='Stainless Steel', temperatureVar=LINEAR,
        consistentMassMatrix=False)
    p = mdb.models['Model-1'].parts['Part-1']
    e = p.edges
    edges = e.getSequenceFromMask(mask=('[#1 ]', ), )
    region = p.Set(edges=edges, name='Set-1')
    p = mdb.models['Model-1'].parts['Part-1']
    p.SectionAssignment(region=region, sectionName='Tube Section', offset=0.0,
        offsetType=MIDDLE_SURFACE, offsetField='',
        thicknessAssignment=FROM_SECTION)
    p = mdb.models['Model-1'].parts['Part-1']
    e = p.edges
    edges = e.getSequenceFromMask(mask=('[#1 ]', ), )
    region=p.Set(edges=edges, name='Set-2')
    p = mdb.models['Model-1'].parts['Part-1']
    p.assignBeamSectionOrientation(region=region, method=N1_COSINES, n1=(0.0, 0.0,
        -1.0))
    a = mdb.models['Model-1'].rootAssembly
    session.viewports['Viewport: 1'].setValues(displayedObject=a)
    a1 = mdb.models['Model-1'].rootAssembly
    a1.DatumCsysByDefault(CARTESIAN)
    p = mdb.models['Model-1'].parts['Part-1']
    a1.Instance(name='Part-1-1', part=p, dependent=OFF)
    session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=OFF,
        engineeringFeatures=OFF)
    session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
        referenceRepresentation=ON)
    p = mdb.models['Model-1'].parts['Part-1']
    session.viewports['Viewport: 1'].setValues(displayedObject=p)
    p = mdb.models['Model-1'].parts['Part-1']
    e = p.edges
    pickedEdges = e.getSequenceFromMask(mask=('[#1 ]', ), )
    p.PartitionEdgeByParam(edges=pickedEdges, parameter=0.5)
    a1 = mdb.models['Model-1'].rootAssembly
    a1.regenerate()
    a = mdb.models['Model-1'].rootAssembly
    session.viewports['Viewport: 1'].setValues(displayedObject=a)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(
        adaptiveMeshConstraints=ON)
    mdb.models['Model-1'].StaticStep(name='Modes', previous='Initial',
        description='Finding the frequencies fro all the Modal Shapes')
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Modes')
    del mdb.models['Model-1'].steps['Modes']
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Initial')
    mdb.models['Model-1'].FrequencyStep(name='Modes', previous='Initial',
        description='Finding Frequencies of all Mode Shapes', numEigen=20)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Modes')
    mdb.models['Model-1'].fieldOutputRequests['F-Output-1'].setValues(variables=(
        'U', 'E'))
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=ON, bcs=ON,
        predefinedFields=ON, connectors=ON, adaptiveMeshConstraints=OFF)
    a = mdb.models['Model-1'].rootAssembly
    v1 = a.instances['Part-1-1'].vertices
    verts1 = v1.getSequenceFromMask(mask=('[#1 ]', ), )
    region = a.Set(vertices=verts1, name='Set-1')
    mdb.models['Model-1'].EncastreBC(name='BC-1', createStepName='Modes',
        region=region, localCsys=None)
    mdb.models['Model-1'].boundaryConditions.changeKey(fromName='BC-1',
        toName='Left_Edge_Fixed')
    a = mdb.models['Model-1'].rootAssembly
    v1 = a.instances['Part-1-1'].vertices
    verts1 = v1.getSequenceFromMask(mask=('[#4 ]', ), )
    region = a.Set(vertices=verts1, name='Set-2')
    mdb.models['Model-1'].EncastreBC(name='BC-2', createStepName='Modes',
        region=region, localCsys=None)
    mdb.models['Model-1'].boundaryConditions.changeKey(fromName='BC-2',
        toName='Right_Edge_Fixed')
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(mesh=ON, loads=OFF,
        bcs=OFF, predefinedFields=OFF, connectors=OFF)
    session.viewports['Viewport: 1'].assemblyDisplay.meshOptions.setValues(
        meshTechnique=ON)
    a = mdb.models['Model-1'].rootAssembly
    e1 = a.instances['Part-1-1'].edges
    pickedEdges = e1.getSequenceFromMask(mask=('[#3 ]', ), )
    a.seedEdgeByNumber(edges=pickedEdges, number=20, constraint=FINER)
    a = mdb.models['Model-1'].rootAssembly
    partInstances =(a.instances['Part-1-1'], )
    a.generateMesh(regions=partInstances)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(mesh=OFF)
    session.viewports['Viewport: 1'].assemblyDisplay.meshOptions.setValues(
        meshTechnique=OFF)
    mdb.Job(name='Mode_Job', model='Model-1',
        description='Job to find the mode shapes and frequencies',
        type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None,
        memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
        explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,
        modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='',
        scratch='', resultsFormat=ODB)
    mdb.jobs['Mode_Job'].submit(consistencyChecking=OFF)
    session.mdbData.summary()
    o3 = session.openOdb(name='C:/ABAQUS/Simulations/Scripting/Mode_Job.odb')
    session.viewports['Viewport: 1'].setValues(displayedObject=o3)
    session.viewports['Viewport: 1'].makeCurrent()
    session.viewports['Viewport: 1'].odbDisplay.display.setValues(plotState=(
        DEFORMED, ))
    session.linkedViewportCommands.setValues(_highlightLinkedViewports=False)
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/Mode_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), nodePick=(('PART-1-1', 1, ('[#2 ]',
        )), ), )
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/Mode_Job.odb']
    xyList = xyPlot.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=((
        'U', NODAL, ((COMPONENT, 'U2'), )), ), nodePick=(('PART-1-1', 1, (
        '[#2 ]', )), ), )
    xyp = session.xyPlots['XYPlot-1']
    chartName = xyp.charts.keys()[0]
    chart = xyp.charts[chartName]
    curveList = session.curveSet(xyData=xyList)
    chart.setValues(curvesToPlot=curveList)
    session.charts[chartName].autoColor(lines=True, symbols=True)
    session.viewports['Viewport: 1'].setValues(displayedObject=xyp)
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/Mode_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), nodePick=(('PART-1-1', 1, ('[#2 ]',
        )), ), )
    p = mdb.models['Model-1'].parts['Part-1']
    session.viewports['Viewport: 1'].setValues(displayedObject=p)
    a = mdb.models['Model-1'].rootAssembly
    session.viewports['Viewport: 1'].setValues(displayedObject=a)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(
        adaptiveMeshConstraints=ON)
    mdb.models['Model-1'].SteadyStateModalStep(name='FRF', previous='Modes',
        description='FRF of the tube', frequencyRange=((0.0, 750.0, 50, 3.0),
        ), directDamping=((1, 5, 0.06), ))
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='FRF')
    mdb.models['Model-1'].FieldOutputRequest(name='F-Output-FRF',
        createStepName='FRF', variables=('S', 'MISESMAX', 'E', 'U', 'TU', 'TA',
        'RT'))
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=ON, bcs=ON,
        predefinedFields=ON, connectors=ON, adaptiveMeshConstraints=OFF)
    a = mdb.models['Model-1'].rootAssembly
    v1 = a.instances['Part-1-1'].vertices
    verts1 = v1.getSequenceFromMask(mask=('[#2 ]', ), )
    region = a.Set(vertices=verts1, name='Set-4')
    mdb.models['Model-1'].ConcentratedForce(name='Applied Load',
        createStepName='FRF', region=region, cf2=-12.5+0j,
        distributionType=UNIFORM, field='', localCsys=None)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=OFF, bcs=OFF,
        predefinedFields=OFF, connectors=OFF)
    mdb.Job(name='FRF_Job', model='Model-1', description='Job to find FRF',
        type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None,
        memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
        explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,
        modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='',
        scratch='', resultsFormat=ODB)
    mdb.jobs['FRF_Job'].submit(consistencyChecking=OFF)
    session.mdbData.summary()
    o3 = session.openOdb(name='C:/ABAQUS/Simulations/Scripting/FRF_Job.odb')
    session.viewports['Viewport: 1'].setValues(displayedObject=o3)
    session.viewports['Viewport: 1'].makeCurrent()
    session.linkedViewportCommands.setValues(_highlightLinkedViewports=False)
    odbName=session.viewports[session.currentViewportName].odbDisplay.name
    session.odbData[odbName].setValues(activeFrames=(('FRF', ('0:-1', )), ))
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/FRF_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), numericForm=REAL, nodePick=((
        'PART-1-1', 1, ('[#2 ]', )), ), )
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/FRF_Job.odb']
    xyList = xyPlot.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=((
        'U', NODAL, ((COMPONENT, 'U2'), )), ), numericForm=REAL, nodePick=((
        'PART-1-1', 1, ('[#2 ]', )), ), )
    xyp = session.xyPlots['XYPlot-1']
    chartName = xyp.charts.keys()[0]
    chart = xyp.charts[chartName]
    curveList = session.curveSet(xyData=xyList)
    chart.setValues(curvesToPlot=curveList)
    session.charts[chartName].autoColor(lines=True, symbols=True)
    session.viewports['Viewport: 1'].setValues(displayedObject=xyp)
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/FRF_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), numericForm=REAL, nodePick=((
        'PART-1-1', 1, ('[#2 ]', )), ), )
Macro1()
</code>```

Any additional information on how I can do a for loop to do various iterations for different Young's Modulus, Poisson's Ratio and Density will also be greatly appreciated.

答:
Welcome to Stack Overflow. In python sense, it means that the Key XYPlot-1 is not found.

Python commands in the macro executes without waiting for the abaqus job to complete. My recommendation would be either split the into two, one creates and run the analysis and the second one to read the odb and produce the plots you're looking for. Or, use wait for completion before continuing to other parts of the script specifically Francisco Cruz answer.

I strongly recommend you to use session.journalOptions.setValues(replayGeometry=COORDINATE, recoverGeometry=COORDINATE) at the top of the script after all the import statements to avoid issues associated with masks generated by macros, read JulianBauer's answer here.

Regarding how to iterate for different material properties, have a look at Scripting parametric studies in the documentation. Plate penetration by a projectile example in the documentation is beginner friendly example I could find.

Title: Abaqus Scripting KeyError

Body:
I am trying to do harmonic analysis using abaqus scripting. Everytime I run the code below, I get 'KeyError: XYPlot-1'. Any help would be greatly appreciated. TIA

# -*- coding: mbcs -*-
# Do not delete the following import lines
from abaqus import *
from abaqusConstants import *
import __main__

def Macro1():
    import section
    import regionToolset
    import displayGroupMdbToolset as dgm
    import part
    import material
    import assembly
    import step
    import interaction
    import load
    import mesh
    import optimization
    import job
    import sketch
    import visualization
    import xyPlot
    import displayGroupOdbToolset as dgo
    import connectorBehavior
    s = mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=1.0)
    g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
    s.setPrimaryObject(option=STANDALONE)
    s.Line(point1=(0.0, 0.0), point2=(0.235000000051223, 0.0))
    s.HorizontalConstraint(entity=g[2], addUndoState=False)
    s.ObliqueDimension(vertex1=v[0], vertex2=v[1], textPoint=(0.140255361795425,
        0.0583333373069763), value=0.985)
    session.viewports['Viewport: 1'].view.setValues(nearPlane=0.686013,
        farPlane=1.19961, width=1.74884, height=0.832297, cameraPosition=(
        0.0144624, 0.0330418, 0.942809), cameraTarget=(0.0144624, 0.0330418,
        0))
    p = mdb.models['Model-1'].Part(name='Part-1', dimensionality=TWO_D_PLANAR,
        type=DEFORMABLE_BODY)
    p = mdb.models['Model-1'].parts['Part-1']
    p.BaseWire(sketch=s)
    s.unsetPrimaryObject()
    p = mdb.models['Model-1'].parts['Part-1']
    session.viewports['Viewport: 1'].setValues(displayedObject=p)
    del mdb.models['Model-1'].sketches['__profile__']
    session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=ON,
        engineeringFeatures=ON)
    session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
        referenceRepresentation=OFF)
    mdb.models['Model-1'].Material(name='Stainless Steel',
        description='Creating of Material Properties for Stainless Steel 304')
    mdb.models['Model-1'].materials['Stainless Steel'].Density(table=((7930.0,
        ), ))
    mdb.models['Model-1'].materials['Stainless Steel'].Elastic(table=((
        200000000000.0, 0.31), ))
    mdb.models['Model-1'].PipeProfile(name='Profile-1', r=0.008, t=0.0015)
    mdb.models['Model-1'].BeamSection(name='Tube Section',
        integration=DURING_ANALYSIS, poissonRatio=0.0, profile='Profile-1',
        material='Stainless Steel', temperatureVar=LINEAR,
        consistentMassMatrix=False)
    p = mdb.models['Model-1'].parts['Part-1']
    e = p.edges
    edges = e.getSequenceFromMask(mask=('[#1 ]', ), )
    region = p.Set(edges=edges, name='Set-1')
    p = mdb.models['Model-1'].parts['Part-1']
    p.SectionAssignment(region=region, sectionName='Tube Section', offset=0.0,
        offsetType=MIDDLE_SURFACE, offsetField='',
        thicknessAssignment=FROM_SECTION)
    p = mdb.models['Model-1'].parts['Part-1']
    e = p.edges
    edges = e.getSequenceFromMask(mask=('[#1 ]', ), )
    region=p.Set(edges=edges, name='Set-2')
    p = mdb.models['Model-1'].parts['Part-1']
    p.assignBeamSectionOrientation(region=region, method=N1_COSINES, n1=(0.0, 0.0,
        -1.0))
    a = mdb.models['Model-1'].rootAssembly
    session.viewports['Viewport: 1'].setValues(displayedObject=a)
    a1 = mdb.models['Model-1'].rootAssembly
    a1.DatumCsysByDefault(CARTESIAN)
    p = mdb.models['Model-1'].parts['Part-1']
    a1.Instance(name='Part-1-1', part=p, dependent=OFF)
    session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=OFF,
        engineeringFeatures=OFF)
    session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
        referenceRepresentation=ON)
    p = mdb.models['Model-1'].parts['Part-1']
    session.viewports['Viewport: 1'].setValues(displayedObject=p)
    p = mdb.models['Model-1'].parts['Part-1']
    e = p.edges
    pickedEdges = e.getSequenceFromMask(mask=('[#1 ]', ), )
    p.PartitionEdgeByParam(edges=pickedEdges, parameter=0.5)
    a1 = mdb.models['Model-1'].rootAssembly
    a1.regenerate()
    a = mdb.models['Model-1'].rootAssembly
    session.viewports['Viewport: 1'].setValues(displayedObject=a)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(
        adaptiveMeshConstraints=ON)
    mdb.models['Model-1'].StaticStep(name='Modes', previous='Initial',
        description='Finding the frequencies fro all the Modal Shapes')
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Modes')
    del mdb.models['Model-1'].steps['Modes']
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Initial')
    mdb.models['Model-1'].FrequencyStep(name='Modes', previous='Initial',
        description='Finding Frequencies of all Mode Shapes', numEigen=20)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='Modes')
    mdb.models['Model-1'].fieldOutputRequests['F-Output-1'].setValues(variables=(
        'U', 'E'))
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=ON, bcs=ON,
        predefinedFields=ON, connectors=ON, adaptiveMeshConstraints=OFF)
    a = mdb.models['Model-1'].rootAssembly
    v1 = a.instances['Part-1-1'].vertices
    verts1 = v1.getSequenceFromMask(mask=('[#1 ]', ), )
    region = a.Set(vertices=verts1, name='Set-1')
    mdb.models['Model-1'].EncastreBC(name='BC-1', createStepName='Modes',
        region=region, localCsys=None)
    mdb.models['Model-1'].boundaryConditions.changeKey(fromName='BC-1',
        toName='Left_Edge_Fixed')
    a = mdb.models['Model-1'].rootAssembly
    v1 = a.instances['Part-1-1'].vertices
    verts1 = v1.getSequenceFromMask(mask=('[#4 ]', ), )
    region = a.Set(vertices=verts1, name='Set-2')
    mdb.models['Model-1'].EncastreBC(name='BC-2', createStepName='Modes',
        region=region, localCsys=None)
    mdb.models['Model-1'].boundaryConditions.changeKey(fromName='BC-2',
        toName='Right_Edge_Fixed')
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(mesh=ON, loads=OFF,
        bcs=OFF, predefinedFields=OFF, connectors=OFF)
    session.viewports['Viewport: 1'].assemblyDisplay.meshOptions.setValues(
        meshTechnique=ON)
    a = mdb.models['Model-1'].rootAssembly
    e1 = a.instances['Part-1-1'].edges
    pickedEdges = e1.getSequenceFromMask(mask=('[#3 ]', ), )
    a.seedEdgeByNumber(edges=pickedEdges, number=20, constraint=FINER)
    a = mdb.models['Model-1'].rootAssembly
    partInstances =(a.instances['Part-1-1'], )
    a.generateMesh(regions=partInstances)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(mesh=OFF)
    session.viewports['Viewport: 1'].assemblyDisplay.meshOptions.setValues(
        meshTechnique=OFF)
    mdb.Job(name='Mode_Job', model='Model-1',
        description='Job to find the mode shapes and frequencies',
        type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None,
        memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
        explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,
        modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='',
        scratch='', resultsFormat=ODB)
    mdb.jobs['Mode_Job'].submit(consistencyChecking=OFF)
    session.mdbData.summary()
    o3 = session.openOdb(name='C:/ABAQUS/Simulations/Scripting/Mode_Job.odb')
    session.viewports['Viewport: 1'].setValues(displayedObject=o3)
    session.viewports['Viewport: 1'].makeCurrent()
    session.viewports['Viewport: 1'].odbDisplay.display.setValues(plotState=(
        DEFORMED, ))
    session.linkedViewportCommands.setValues(_highlightLinkedViewports=False)
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/Mode_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), nodePick=(('PART-1-1', 1, ('[#2 ]',
        )), ), )
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/Mode_Job.odb']
    xyList = xyPlot.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=((
        'U', NODAL, ((COMPONENT, 'U2'), )), ), nodePick=(('PART-1-1', 1, (
        '[#2 ]', )), ), )
    xyp = session.xyPlots['XYPlot-1']
    chartName = xyp.charts.keys()[0]
    chart = xyp.charts[chartName]
    curveList = session.curveSet(xyData=xyList)
    chart.setValues(curvesToPlot=curveList)
    session.charts[chartName].autoColor(lines=True, symbols=True)
    session.viewports['Viewport: 1'].setValues(displayedObject=xyp)
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/Mode_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), nodePick=(('PART-1-1', 1, ('[#2 ]',
        )), ), )
    p = mdb.models['Model-1'].parts['Part-1']
    session.viewports['Viewport: 1'].setValues(displayedObject=p)
    a = mdb.models['Model-1'].rootAssembly
    session.viewports['Viewport: 1'].setValues(displayedObject=a)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(
        adaptiveMeshConstraints=ON)
    mdb.models['Model-1'].SteadyStateModalStep(name='FRF', previous='Modes',
        description='FRF of the tube', frequencyRange=((0.0, 750.0, 50, 3.0),
        ), directDamping=((1, 5, 0.06), ))
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(step='FRF')
    mdb.models['Model-1'].FieldOutputRequest(name='F-Output-FRF',
        createStepName='FRF', variables=('S', 'MISESMAX', 'E', 'U', 'TU', 'TA',
        'RT'))
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=ON, bcs=ON,
        predefinedFields=ON, connectors=ON, adaptiveMeshConstraints=OFF)
    a = mdb.models['Model-1'].rootAssembly
    v1 = a.instances['Part-1-1'].vertices
    verts1 = v1.getSequenceFromMask(mask=('[#2 ]', ), )
    region = a.Set(vertices=verts1, name='Set-4')
    mdb.models['Model-1'].ConcentratedForce(name='Applied Load',
        createStepName='FRF', region=region, cf2=-12.5+0j,
        distributionType=UNIFORM, field='', localCsys=None)
    session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=OFF, bcs=OFF,
        predefinedFields=OFF, connectors=OFF)
    mdb.Job(name='FRF_Job', model='Model-1', description='Job to find FRF',
        type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None,
        memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
        explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,
        modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='',
        scratch='', resultsFormat=ODB)
    mdb.jobs['FRF_Job'].submit(consistencyChecking=OFF)
    session.mdbData.summary()
    o3 = session.openOdb(name='C:/ABAQUS/Simulations/Scripting/FRF_Job.odb')
    session.viewports['Viewport: 1'].setValues(displayedObject=o3)
    session.viewports['Viewport: 1'].makeCurrent()
    session.linkedViewportCommands.setValues(_highlightLinkedViewports=False)
    odbName=session.viewports[session.currentViewportName].odbDisplay.name
    session.odbData[odbName].setValues(activeFrames=(('FRF', ('0:-1', )), ))
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/FRF_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), numericForm=REAL, nodePick=((
        'PART-1-1', 1, ('[#2 ]', )), ), )
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/FRF_Job.odb']
    xyList = xyPlot.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=((
        'U', NODAL, ((COMPONENT, 'U2'), )), ), numericForm=REAL, nodePick=((
        'PART-1-1', 1, ('[#2 ]', )), ), )
    xyp = session.xyPlots['XYPlot-1']
    chartName = xyp.charts.keys()[0]
    chart = xyp.charts[chartName]
    curveList = session.curveSet(xyData=xyList)
    chart.setValues(curvesToPlot=curveList)
    session.charts[chartName].autoColor(lines=True, symbols=True)
    session.viewports['Viewport: 1'].setValues(displayedObject=xyp)
    odb = session.odbs['C:/ABAQUS/Simulations/Scripting/FRF_Job.odb']
    session.xyDataListFromField(odb=odb, outputPosition=NODAL, variable=(('U',
        NODAL, ((COMPONENT, 'U2'), )), ), numericForm=REAL, nodePick=((
        'PART-1-1', 1, ('[#2 ]', )), ), )
Macro1()

Any additional information on how I can do a for loop to do various iterations for different Young's Modulus, Poisson's Ratio and Density will also be greatly appreciated.


问:
Docker Plugin for Jenkins Pipeline - No user exists for uid 1005
I'm trying to execute an SSH command from inside a Docker container in a Jenkins pipeline. I'm using the CloudBees Docker Pipeline Plugin to spin up the container and execute commands, and the SSH Agent Plugin to manage my SSH keys. Here's a basic version of my Jenkinsfile:

```<code>node {
  step([$class: 'WsCleanup'])
  docker.image('node').inside {
    stage('SSH') {
      sshagent (credentials: [ 'MY_KEY_UUID' ]) {
        sh "ssh -vvv -o StrictHostKeyChecking=no ubuntu@example.org uname -a"
      }
    }
  }
}
</code>```

When the SSH command runs, I get this error:

```<code>+ ssh -vvv -o StrictHostKeyChecking=no ubuntu@example.org uname -a
No user exists for uid 1005
</code>```

答:
I just found another solution to this problem, that I want to share. It differentiates from the existing solutions in that it allows to run the complete pipeline in one agent, instead of per stage.

The trick is to, instead of directly using an image, refer to a Dockerfile (which may be build FROM the original) and then add the user:

```<code># Dockerfile
FROM node

ARG jenkinsUserId=
RUN if ! id $jenkinsUserId; then \
    usermod -u ${jenkinsUserId} jenkins; \
    groupmod -g ${nodeId} jenkins; \
  fi
</code>```

```<code>// Jenkinsfile
pipeline {
  agent {
    dockerfile {
      additionalBuildArgs "--build-arg jenkinsUserId=\$(id -u jenkins)"
    }
  }
}
</code>```

Body:
I'm trying to execute an SSH command from inside a Docker container in a Jenkins pipeline. I'm using the CloudBees Docker Pipeline Plugin to spin up the container and execute commands, and the SSH Agent Plugin to manage my SSH keys. Here's a basic version of my Jenkinsfile:

node {
  step([$class: 'WsCleanup'])
  docker.image('node').inside {
    stage('SSH') {
      sshagent (credentials: [ 'MY_KEY_UUID' ]) {
        sh "ssh -vvv -o StrictHostKeyChecking=no ubuntu@example.org uname -a"
      }
    }
  }
}

When the SSH command runs, I get this error:

+ ssh -vvv -o StrictHostKeyChecking=no ubuntu@example.org uname -a
No user exists for uid 1005

Body:
I just found another solution to this problem, that I want to share. It differentiates from the existing solutions in that it allows to run the complete pipeline in one agent, instead of per stage.

The trick is to, instead of directly using an image, refer to a Dockerfile (which may be build FROM the original) and then add the user:

# Dockerfile
FROM node

ARG jenkinsUserId=
RUN if ! id $jenkinsUserId; then \
    usermod -u ${jenkinsUserId} jenkins; \
    groupmod -g ${nodeId} jenkins; \
  fi

// Jenkinsfile
pipeline {
  agent {
    dockerfile {
      additionalBuildArgs "--build-arg jenkinsUserId=\$(id -u jenkins)"
    }
  }
}