问:
Create Laravel Relationship through Many-To-One and Many-To-Many
I'm having trouble defining a relationship between several models.
In the Laravel documentation, I was able to find a hasManyThrough() relationship where the relationship was extended down through two many-to-one models, but I'm having issues with mine from a many-to-one then many-to-many relationship. Here are the tables:

```<code>practices
  id
  name

locations
  id
  practice_id
  name

doctors
  id
  name

doctor_location
  doctor_id
  location_id
</code>```

As you can see, practices can have many locations, and locations can only belong to one practice. Doctors can have many locations, and locations can have many doctors. I'm not certain how to drill down to create a $practice->doctors relationship, however. I did attempt the hasManyThrough() relationship in the practices model:

```<code>public function doctors() {
  return $this->hasManyThrough(Doctor::class, Location::class);
}
</code>```

but this simply threw an sqlstate error looking for a location_id in the doctors table. Is it possible to relate these models?

Edit: SQLState error

```<code>Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id' in 'on clause' (SQL: select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)
</code>```

答:
As you can see in the error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id'

The query which is executed is trying to perform a join between doctors and locations tables

```<code>select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)
</code>```

The query use this clause to perform the join

```<code>inner join `locations` on `locations`.`id` = `doctors`.`location_id`
</code>```

As you doctors table doesn't have a location_id attribute this is the main cause of that error.

This error is because you have have define the hasManyThrough relation using wrong models, It should be like this

```<code>public function doctors() {
    return $this->hasManyThrough(Doctor::class, DoctorLocation::class);
}
</code>```

This supposed you have already define a model DoctorLocation which refered to the doctor_location table. This will allow you to access doctors from from Practice

This will allow eloquent to perform the join between Practice and Doctor by passing through the doctor_location table as it has location_id and doctor_id attributes.

Body:
I'm having trouble defining a relationship between several models.
In the Laravel documentation, I was able to find a hasManyThrough() relationship where the relationship was extended down through two many-to-one models, but I'm having issues with mine from a many-to-one then many-to-many relationship. Here are the tables:

practices
  id
  name

locations
  id
  practice_id
  name

doctors
  id
  name

doctor_location
  doctor_id
  location_id

As you can see, practices can have many locations, and locations can only belong to one practice. Doctors can have many locations, and locations can have many doctors. I'm not certain how to drill down to create a $practice->doctors relationship, however. I did attempt the hasManyThrough() relationship in the practices model:

public function doctors() {
  return $this->hasManyThrough(Doctor::class, Location::class);
}

but this simply threw an sqlstate error looking for a location_id in the doctors table. Is it possible to relate these models?

Edit: SQLState error

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id' in 'on clause' (SQL: select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)

Body:
As you can see in the error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'doctors.location_id'

The query which is executed is trying to perform a join between doctors and locations tables

select `doctors`.*, `locations`.`practice_id` as `laravel_through_key` from `doctors` inner join `locations` on `locations`.`id` = `doctors`.`location_id` where `locations`.`practice_id` = 1)

The query use this clause to perform the join

inner join `locations` on `locations`.`id` = `doctors`.`location_id`

As you doctors table doesn't have a location_id attribute this is the main cause of that error.

This error is because you have have define the hasManyThrough relation using wrong models, It should be like this

public function doctors() {
    return $this->hasManyThrough(Doctor::class, DoctorLocation::class);
}

This supposed you have already define a model DoctorLocation which refered to the doctor_location table. This will allow you to access doctors from from Practice

This will allow eloquent to perform the join between Practice and Doctor by passing through the doctor_location table as it has location_id and doctor_id attributes.


来源: stackexchange

问:
Null check operator used on a null value error in flutter Dashboard page
I got this error when I am running the app. I could not figure out why this error occurred.
So I am switching a project to flutter null safety but i am getting Null check operator used on a null value error i tried looking into other similar issues tried but its not working for me the complete error is as following

Stack Trace

The following _CastError was thrown building DashboardPage(dirty,
dependencies: [_InheritedTheme,
_InheritedProviderScope<DocumentSnapshot?>, _LocalizationsScope-[GlobalKey#556e8]], state:
_DashboardPageState#0b8da): Null check operator used on a null value

The relevant error-causing widget was:   DashboardPage

My main.app

```<code>void main() => runApp(ElectricalIssueTrackerApp());

class ElectricalIssueTrackerApp extends StatelessWidget {
  static const appName = 'Electrical Issue Tracker';
  static const appIcon = AssetImage('assets/icons/192.png');
  static const appLegalese = 'GNU General Public License v3.0';
  // Move to Misc
  static const appIssueTracker =
      '';
  // Move to Misc
  static const appIssueTrackerMailing = '';

  static const appRepository =
      '';

  const ElectricalIssueTrackerApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: appName,
      theme: _theme,
      home: FutureBuilder<FirebaseApp>(
        future: Firebase.initializeApp(),
        builder: (context, snapshot) {
          // Loading screen, when initializing firebase app.
          if (!snapshot.hasData) {
            return Loading();
          }

          return Authenticated(
            child: Verified(
              child: DashboardPage(),
            ),
          );
        },
      ),
    );
  }

  static const _primary = Color.fromARGB(255, 0, 38, 70);
  static const _accent = Color.fromARGB(255, 245, 248, 253);
  static const _secondary = Color(0xFF924642);
  static const _vistaWhite = Color(0xFFFEF9F7);

  static const _fontFamily = 'Ubuntu';

  static get _theme {
    return ThemeData(
      visualDensity: VisualDensity.standard,
      fontFamily: _fontFamily,
      brightness: Brightness.light,
      primaryColor: _primary,
      colorScheme: ColorScheme.light(
        primary: _primary,
        onPrimary: _accent,
        secondary: _secondary,
        onSecondary: _vistaWhite,
        surface: _accent,
        onSurface: _primary,
        background: _accent,
        onBackground: _primary,
      ),
      disabledColor: Color(0x99002646),
      scaffoldBackgroundColor: _accent,
      cardColor: Colors.white,
      appBarTheme: AppBarTheme(
        color: _accent,
        iconTheme: IconThemeData(
          color: _primary,
        ),
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
        ),
        elevation: 0,
        actionsIconTheme: const IconThemeData(
          color: _primary,
        ),
        titleTextStyle: TextStyle(
          fontFamily: _fontFamily,
          fontSize: 20,
          fontWeight: FontWeight.bold,
          letterSpacing: 0.5,
          color: _primary,
        ),
      ),
      bottomSheetTheme: BottomSheetThemeData(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(20),
            topLeft: Radius.circular(20),
          ),
        ),
        elevation: 8,
      ),
      iconTheme: const IconThemeData(
        color: _primary,
      ),
      floatingActionButtonTheme: FloatingActionButtonThemeData(
        backgroundColor: _primary,
        foregroundColor: _accent,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
      ),
      outlinedButtonTheme: OutlinedButtonThemeData(
        style: OutlinedButton.styleFrom(
          backgroundColor: _primary,
          primary: _accent,
          onSurface: _accent,
        ),
      ),
      dialogTheme: DialogTheme(
        backgroundColor: _accent,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
      ),
      snackBarTheme: const SnackBarThemeData(
        backgroundColor: _primary,
        contentTextStyle: TextStyle(
          fontFamily: _fontFamily,
          color: _accent,
          letterSpacing: 0.5,
        ),
      ),
      inputDecorationTheme: InputDecorationTheme(
        filled: true,
        fillColor: _accent,
        enabledBorder: UnderlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide.none,
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: _primary),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.red),
        ),
        focusedErrorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.red),
        ),
        labelStyle: const TextStyle(color: _primary, fontSize: 14),
        focusColor: _primary,
      ),
    );
  }
}
</code>```

My Dashboard.app

```<code>class DashboardPage extends StatefulWidget {
  const DashboardPage({Key? key}) : super(key: key);

  @override
  _DashboardPageState createState() => _DashboardPageState();

  static _DashboardPageState of(BuildContext context) =>
      context.findAncestorStateOfType<_DashboardPageState>()!;
}

class _DashboardPageState extends State<DashboardPage> {
  bool _raiseNewIssueFormIsShown = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    final misc = Provider.of<MiscSnapshot>(context).misc;

    final userSnapshot = Provider.of<UserSnapshot>(context);
    final user = userSnapshot.user;

    NetworkImage? userPhoto;

    final photoUrl = Provider.of<User>(context).photoURL;

    if (photoUrl != null) {
      userPhoto = NetworkImage(photoUrl);
    }

    return Scaffold(
      appBar: AppBar(
        title: FadeInLeft(
          preferences: const AnimationPreferences(
            duration: Duration(milliseconds: 400),
          ),
          child: Text(
            _raiseNewIssueFormIsShown
                ? 'Raise an issue'
                : ElectricalIssueTrackerApp.appName,
          ),
        ),
        actions: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => showDialog(
              context: context,
              builder: (_) => MiscellaneousDialog(userSnapshot),
            ),
            child: Padding(
              padding: const EdgeInsets.all(10),
              child: PhysicalModel(
                color: Colors.transparent,
                elevation: 3,
                shape: BoxShape.circle,
                child: CircleAvatar(
                  backgroundColor: theme.primaryColor,
                  child: Text(
                    ('${user.name}${user.email}-'[0]).toUpperCase(),
                    style: TextStyle(
                      color: theme.colorScheme.onPrimary,
                    ),
                  ),
                  foregroundImage: userPhoto,
                ),
              ),
            ),
          ),
        ],
      ),
      body: CupertinoScrollbar(
        child: SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          padding: const EdgeInsets.all(8),
          child: Wrap(
            spacing: 10,
            runSpacing: 30,
            children: [
              // The analytics widget
              ActiveAndResolvedIssueCounters(misc: misc),

              // View all active issues if user has permission
              if (user.scope.canViewActiveIssues) ActiveIssuesSection(),

              if (user.scope.canViewResolvedIssues)
                buildResolvedIssuesButton(misc, userSnapshot),

              // Raise an issue section
              if (user.scope.canCreateIssue) RaiseAnIssueSection(),

              // All issues raised by the user.
              MyIssuesSection(),

              // Footer
              SizedBox(height: 30),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> showRaiseNewIssueForm(BuildContext context) async {
    setState(() => _raiseNewIssueFormIsShown = true);

    await Scaffold.of(context)
        .showBottomSheet((_) => RaiseNewIssueBottomSheet())
        .closed;

    setState(() => _raiseNewIssueFormIsShown = false);
  }

  Widget buildResolvedIssuesButton(Misc misc, UserSnapshot userSnapshot) {
    return Center(
      child: OutlinedButton(
        child: Text('View already resolved issues'),
        onPressed: () => Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) {
              return MultiProvider(
                providers: [
                  Provider.value(value: userSnapshot),
                  Provider.value(value: misc),
                ],
                child: ResolvedIssuesPage(),
              );
            },
          ),
        ),
      ),
    );
  }
}
</code>```

raise_issue_section.dart

```<code>class RaiseAnIssueSection extends StatelessWidget {
  const RaiseAnIssueSection({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Container(
      margin: const EdgeInsets.all(8),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: theme.cardColor,
        borderRadius: BorderRadius.circular(16),
        // color: theme.colorScheme.surface,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            'Having an electrical issue in campus?',
            style: TextStyle(
              color: theme.primaryColor,
            ),
          ),
          SizedBox(height: 18),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FloatingActionButton.extended(
                onPressed: () =>
                    DashboardPage.of(context).showRaiseNewIssueForm(context),
                label: Text('Raise new issue'),
                icon: Icon(FontAwesomeIcons.feather),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
</code>```

misc.dart

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'misc.freezed.dart';

typedef MiscSnapshot = DocumentSnapshot<Misc>;

@freezed
class Misc with _$Misc {
  const Misc._();

  const factory Misc._create({
    required List<String> locationBlocks,
    required int activeIssuesCount,
    required int resolvedIssuesCount,
  }) = _Misc;

  static const _LocationBlocksKey = 'location-blocks';
  static const _ActiveIssuesCountKey = 'active-issues-count';
  static const _ResolvedIssuesCountKey = 'resolved-issues-count';

  static final _ref =
      FirebaseFirestore.instance.collection('misc').withConverter<Misc>(
    fromFirestore: (snapshot, options) {
      final data = snapshot.data()!;

      return Misc._create(
          locationBlocks: data[_LocationBlocksKey].cast<String>(),
          activeIssuesCount: data[_ActiveIssuesCountKey],
          resolvedIssuesCount: data[_ResolvedIssuesCountKey]);
    },
    toFirestore: (value, options) {
      return {
        _LocationBlocksKey: value.locationBlocks,
      };
    },
  ).doc('default');

  static get ref => _ref;

  static Stream<MiscSnapshot> get watch => _ref.snapshots();

  static Future<MiscSnapshot> get read => _ref.get();

  static Future<void> informIssueCreated() async {
    await _ref.update({
      _ActiveIssuesCountKey: FieldValue.increment(1),
    });
  }

  static Future<void> informIssueResolved() async {
    await _ref.update({
      _ActiveIssuesCountKey: FieldValue.increment(-1),
      _ResolvedIssuesCountKey: FieldValue.increment(1),
    });
  }

  static Future<void> informActiveIssuePurged() async {
    await _ref.update({
      _ActiveIssuesCountKey: FieldValue.increment(-1),
    });
  }

  static Future<void> updateActiveIssuesCount(int value) async {
    assert(value >= 0, 'bad argument: cannot write negative value');

    if (value < 0) {
      return;
    }

    await _ref.update({_ActiveIssuesCountKey: value});
  }
}

extension MiscSnapshotExtension on MiscSnapshot {
  Misc get misc => this.data()!;
}
</code>```

答:
You'll mostly get the "Null check operator used on a null value"-error when ever you explicitly say something is not null using the bang operator ! on something that actually is.

Looking at your code sample that could be in the following lines:

```<code>static _DashboardPageState of(BuildContext context) =>
      context.findAncestorStateOfType<_DashboardPageState>()!
</code>```

I assume DashboardPage.of(context) is called somewhere, when it actually doesn't have a DashboardPage parent for that context instance. However, I cannot find it in the sample. Is it missing from it?

ContentLicense: CC BY-SA 4.0

Body:
I got this error when I am running the app. I could not figure out why this error occurred.
So I am switching a project to flutter null safety but i am getting Null check operator used on a null value error i tried looking into other similar issues tried but its not working for me the complete error is as following

Stack Trace

The following _CastError was thrown building DashboardPage(dirty,
dependencies: [_InheritedTheme,
_InheritedProviderScope<DocumentSnapshot?>, _LocalizationsScope-[GlobalKey#556e8]], state:
_DashboardPageState#0b8da): Null check operator used on a null value

The relevant error-causing widget was:   DashboardPage

My main.app

void main() => runApp(ElectricalIssueTrackerApp());

class ElectricalIssueTrackerApp extends StatelessWidget {
  static const appName = 'Electrical Issue Tracker';
  static const appIcon = AssetImage('assets/icons/192.png');
  static const appLegalese = 'GNU General Public License v3.0';
  // Move to Misc
  static const appIssueTracker =
      '';
  // Move to Misc
  static const appIssueTrackerMailing = '';

  static const appRepository =
      '';

  const ElectricalIssueTrackerApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: appName,
      theme: _theme,
      home: FutureBuilder<FirebaseApp>(
        future: Firebase.initializeApp(),
        builder: (context, snapshot) {
          // Loading screen, when initializing firebase app.
          if (!snapshot.hasData) {
            return Loading();
          }

          return Authenticated(
            child: Verified(
              child: DashboardPage(),
            ),
          );
        },
      ),
    );
  }

  static const _primary = Color.fromARGB(255, 0, 38, 70);
  static const _accent = Color.fromARGB(255, 245, 248, 253);
  static const _secondary = Color(0xFF924642);
  static const _vistaWhite = Color(0xFFFEF9F7);

  static const _fontFamily = 'Ubuntu';

  static get _theme {
    return ThemeData(
      visualDensity: VisualDensity.standard,
      fontFamily: _fontFamily,
      brightness: Brightness.light,
      primaryColor: _primary,
      colorScheme: ColorScheme.light(
        primary: _primary,
        onPrimary: _accent,
        secondary: _secondary,
        onSecondary: _vistaWhite,
        surface: _accent,
        onSurface: _primary,
        background: _accent,
        onBackground: _primary,
      ),
      disabledColor: Color(0x99002646),
      scaffoldBackgroundColor: _accent,
      cardColor: Colors.white,
      appBarTheme: AppBarTheme(
        color: _accent,
        iconTheme: IconThemeData(
          color: _primary,
        ),
        systemOverlayStyle: SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
        ),
        elevation: 0,
        actionsIconTheme: const IconThemeData(
          color: _primary,
        ),
        titleTextStyle: TextStyle(
          fontFamily: _fontFamily,
          fontSize: 20,
          fontWeight: FontWeight.bold,
          letterSpacing: 0.5,
          color: _primary,
        ),
      ),
      bottomSheetTheme: BottomSheetThemeData(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(20),
            topLeft: Radius.circular(20),
          ),
        ),
        elevation: 8,
      ),
      iconTheme: const IconThemeData(
        color: _primary,
      ),
      floatingActionButtonTheme: FloatingActionButtonThemeData(
        backgroundColor: _primary,
        foregroundColor: _accent,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
      ),
      outlinedButtonTheme: OutlinedButtonThemeData(
        style: OutlinedButton.styleFrom(
          backgroundColor: _primary,
          primary: _accent,
          onSurface: _accent,
        ),
      ),
      dialogTheme: DialogTheme(
        backgroundColor: _accent,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
      ),
      snackBarTheme: const SnackBarThemeData(
        backgroundColor: _primary,
        contentTextStyle: TextStyle(
          fontFamily: _fontFamily,
          color: _accent,
          letterSpacing: 0.5,
        ),
      ),
      inputDecorationTheme: InputDecorationTheme(
        filled: true,
        fillColor: _accent,
        enabledBorder: UnderlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide.none,
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: _primary),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.red),
        ),
        focusedErrorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
          borderSide: BorderSide(color: Colors.red),
        ),
        labelStyle: const TextStyle(color: _primary, fontSize: 14),
        focusColor: _primary,
      ),
    );
  }
}

My Dashboard.app

class DashboardPage extends StatefulWidget {
  const DashboardPage({Key? key}) : super(key: key);

  @override
  _DashboardPageState createState() => _DashboardPageState();

  static _DashboardPageState of(BuildContext context) =>
      context.findAncestorStateOfType<_DashboardPageState>()!;
}

class _DashboardPageState extends State<DashboardPage> {
  bool _raiseNewIssueFormIsShown = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    final misc = Provider.of<MiscSnapshot>(context).misc;

    final userSnapshot = Provider.of<UserSnapshot>(context);
    final user = userSnapshot.user;

    NetworkImage? userPhoto;

    final photoUrl = Provider.of<User>(context).photoURL;

    if (photoUrl != null) {
      userPhoto = NetworkImage(photoUrl);
    }

    return Scaffold(
      appBar: AppBar(
        title: FadeInLeft(
          preferences: const AnimationPreferences(
            duration: Duration(milliseconds: 400),
          ),
          child: Text(
            _raiseNewIssueFormIsShown
                ? 'Raise an issue'
                : ElectricalIssueTrackerApp.appName,
          ),
        ),
        actions: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => showDialog(
              context: context,
              builder: (_) => MiscellaneousDialog(userSnapshot),
            ),
            child: Padding(
              padding: const EdgeInsets.all(10),
              child: PhysicalModel(
                color: Colors.transparent,
                elevation: 3,
                shape: BoxShape.circle,
                child: CircleAvatar(
                  backgroundColor: theme.primaryColor,
                  child: Text(
                    ('${user.name}${user.email}-'[0]).toUpperCase(),
                    style: TextStyle(
                      color: theme.colorScheme.onPrimary,
                    ),
                  ),
                  foregroundImage: userPhoto,
                ),
              ),
            ),
          ),
        ],
      ),
      body: CupertinoScrollbar(
        child: SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          padding: const EdgeInsets.all(8),
          child: Wrap(
            spacing: 10,
            runSpacing: 30,
            children: [
              // The analytics widget
              ActiveAndResolvedIssueCounters(misc: misc),

              // View all active issues if user has permission
              if (user.scope.canViewActiveIssues) ActiveIssuesSection(),

              if (user.scope.canViewResolvedIssues)
                buildResolvedIssuesButton(misc, userSnapshot),

              // Raise an issue section
              if (user.scope.canCreateIssue) RaiseAnIssueSection(),

              // All issues raised by the user.
              MyIssuesSection(),

              // Footer
              SizedBox(height: 30),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> showRaiseNewIssueForm(BuildContext context) async {
    setState(() => _raiseNewIssueFormIsShown = true);

    await Scaffold.of(context)
        .showBottomSheet((_) => RaiseNewIssueBottomSheet())
        .closed;

    setState(() => _raiseNewIssueFormIsShown = false);
  }

  Widget buildResolvedIssuesButton(Misc misc, UserSnapshot userSnapshot) {
    return Center(
      child: OutlinedButton(
        child: Text('View already resolved issues'),
        onPressed: () => Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) {
              return MultiProvider(
                providers: [
                  Provider.value(value: userSnapshot),
                  Provider.value(value: misc),
                ],
                child: ResolvedIssuesPage(),
              );
            },
          ),
        ),
      ),
    );
  }
}

raise_issue_section.dart

class RaiseAnIssueSection extends StatelessWidget {
  const RaiseAnIssueSection({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Container(
      margin: const EdgeInsets.all(8),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: theme.cardColor,
        borderRadius: BorderRadius.circular(16),
        // color: theme.colorScheme.surface,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            'Having an electrical issue in campus?',
            style: TextStyle(
              color: theme.primaryColor,
            ),
          ),
          SizedBox(height: 18),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FloatingActionButton.extended(
                onPressed: () =>
                    DashboardPage.of(context).showRaiseNewIssueForm(context),
                label: Text('Raise new issue'),
                icon: Icon(FontAwesomeIcons.feather),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

misc.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'misc.freezed.dart';

typedef MiscSnapshot = DocumentSnapshot<Misc>;

@freezed
class Misc with _$Misc {
  const Misc._();

  const factory Misc._create({
    required List<String> locationBlocks,
    required int activeIssuesCount,
    required int resolvedIssuesCount,
  }) = _Misc;

  static const _LocationBlocksKey = 'location-blocks';
  static const _ActiveIssuesCountKey = 'active-issues-count';
  static const _ResolvedIssuesCountKey = 'resolved-issues-count';

  static final _ref =
      FirebaseFirestore.instance.collection('misc').withConverter<Misc>(
    fromFirestore: (snapshot, options) {
      final data = snapshot.data()!;

      return Misc._create(
          locationBlocks: data[_LocationBlocksKey].cast<String>(),
          activeIssuesCount: data[_ActiveIssuesCountKey],
          resolvedIssuesCount: data[_ResolvedIssuesCountKey]);
    },
    toFirestore: (value, options) {
      return {
        _LocationBlocksKey: value.locationBlocks,
      };
    },
  ).doc('default');

  static get ref => _ref;

  static Stream<MiscSnapshot> get watch => _ref.snapshots();

  static Future<MiscSnapshot> get read => _ref.get();

  static Future<void> informIssueCreated() async {
    await _ref.update({
      _ActiveIssuesCountKey: FieldValue.increment(1),
    });
  }

  static Future<void> informIssueResolved() async {
    await _ref.update({
      _ActiveIssuesCountKey: FieldValue.increment(-1),
      _ResolvedIssuesCountKey: FieldValue.increment(1),
    });
  }

  static Future<void> informActiveIssuePurged() async {
    await _ref.update({
      _ActiveIssuesCountKey: FieldValue.increment(-1),
    });
  }

  static Future<void> updateActiveIssuesCount(int value) async {
    assert(value >= 0, 'bad argument: cannot write negative value');

    if (value < 0) {
      return;
    }

    await _ref.update({_ActiveIssuesCountKey: value});
  }
}

extension MiscSnapshotExtension on MiscSnapshot {
  Misc get misc => this.data()!;
}

Body:
You'll mostly get the "Null check operator used on a null value"-error when ever you explicitly say something is not null using the bang operator ! on something that actually is.

Looking at your code sample that could be in the following lines:

static _DashboardPageState of(BuildContext context) =>
      context.findAncestorStateOfType<_DashboardPageState>()!

I assume DashboardPage.of(context) is called somewhere, when it actually doesn't have a DashboardPage parent for that context instance. However, I cannot find it in the sample. Is it missing from it?


问:
How do i split list using 2 different method in for LOOP?
I am sorry if I am unable to put out the question properly. But here is my CODE

```<code>data1 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG']
data2 = ['TOOK2231515100HG','BOGGOK2221643200GH']

for i in data1:
  splt_1 = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
  print('data1:', splt_1)

for I in data2:
  splt_2 = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print('data2:', splt_2)

</code>```

Output result

```<code>data1: ['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
data1: ['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']

data2: ['', 'TOOK', '22315', '15100', 'HG', '']
data2: ['', 'BOGGOK', '22216', '43200', 'GH', '']
</code>```

What I want to do?

if

```<code>data = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG', 'TOOK2231515100HG','BOGGOK2221643200GH']
</code>```

I want to be able to loop and split data list using the 2 method

```<code>re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i) or
re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]
</code>```

P.S: Output result can be in same or similar format

I tried this Code

```<code>data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print(dk)
</code>```

Result

```<code>['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', None, None, None, None, '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', None, None, None, None, '']
['', None, None, None, None, None, None, 'TOOK', '22315', '15100', 'HG', '']
['', None, None, None, None, None, None, 'BOGGOK', '22216', '43200', 'GH', '']
</code>```

Result I want

```<code>['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']
['', 'TOOK', '22315', '15100', 'HG', '']
['', 'BOGGOK', '22216', '43200', 'GH', '']

or

['TOOK', '22', 'JAN', '15', '15100', 'HG']
['BOGGOK', '22', 'MAR', '17', '42200', 'HG']
['TOOK', '22315', '15100', 'HG']
['BOGGOK', '22216', '43200', 'GH']
</code>```

Thank you for taking your time to answer my question..
really appreciate it.

答:
Try using the filter function to remove None from the lists:

```<code>dk = list(filter(lambda x:x!=None, re.split(Your reg expression here), i))
</code>```

You get None cause there are two capturing groups and if neither of them matches then a None gets into the list.

Body:
I am sorry if I am unable to put out the question properly. But here is my CODE

data1 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG']
data2 = ['TOOK2231515100HG','BOGGOK2221643200GH']

for i in data1:
  splt_1 = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)', i)
  print('data1:', splt_1)

for I in data2:
  splt_2 = re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print('data2:', splt_2)

Output result

data1: ['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
data1: ['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']

data2: ['', 'TOOK', '22315', '15100', 'HG', '']
data2: ['', 'BOGGOK', '22216', '43200', 'GH', '']

What I want to do?

if

data = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG', 'TOOK2231515100HG','BOGGOK2221643200GH']

I want to be able to loop and split data list using the 2 method

re.split(r'(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i) or
re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]

P.S: Output result can be in same or similar format

I tried this Code

data5 = ['TOOK22JAN1515100HG','BOGGOK22MAR1742200HG','TOOK2231515100HG','BOGGOK2221643200GH']

for i in data5:
  dk = re.split(r'(TOOK|BOGGOK)([0-9]{2})(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)([0-9]{2})([0-9]{5})(HG|GH)|(TOOK|BOGGOK)([0-9]{5})([0-9]{5})(HG|GH)', i)
  print(dk)

Result

['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', None, None, None, None, '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', None, None, None, None, '']
['', None, None, None, None, None, None, 'TOOK', '22315', '15100', 'HG', '']
['', None, None, None, None, None, None, 'BOGGOK', '22216', '43200', 'GH', '']

Result I want

['', 'TOOK', '22', 'JAN', '15', '15100', 'HG', '']
['', 'BOGGOK', '22', 'MAR', '17', '42200', 'HG', '']
['', 'TOOK', '22315', '15100', 'HG', '']
['', 'BOGGOK', '22216', '43200', 'GH', '']

or

['TOOK', '22', 'JAN', '15', '15100', 'HG']
['BOGGOK', '22', 'MAR', '17', '42200', 'HG']
['TOOK', '22315', '15100', 'HG']
['BOGGOK', '22216', '43200', 'GH']

Thank you for taking your time to answer my question..
really appreciate it.

Body:
Try using the filter function to remove None from the lists:

dk = list(filter(lambda x:x!=None, re.split(Your reg expression here), i))

You get None cause there are two capturing groups and if neither of them matches then a None gets into the list.


问:
Randomize assigned colors in an array in p5.js
I have been trying to recreate one of Vera Molnar's paintings, and to add a twist, I wanted to randomize the colors in the array as I drag my mouse over the canvas.  However, I cannot for the life of me figure out how to do this.  Below is one of many attempts at this.  What could I be doing wrong?

As for the colors, the intial order of the colors is something I would like to keep, as it is directly mimicking the original painting, but as the mouse is moved into the canvas/frame, i want to trigger the random colors.

Thank you for your help!

```<code>const width = 700;
const height = 700;

let radius = 58;
let len = 8;
let color;
let colors;

function setup() {
  createCanvas(width, height);

  colors = [
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#e2592f",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#000000",
    "#000000",
    "#9bd6ff",
  ];
}

function draw() {
  background(255);

  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      let x = i * 80;
      let y = j * 80;
      color = colors.shift();
      if (color === undefined) {
        color = "white";
      }
      fill(color);
      noStroke();
      ellipse(y + 65, x + 65, radius);
    }
  }

  noLoop();
}

function mouseDragged() {
  color = random(colors);
}

</code>```

答:
If you want to change color for a specific ellipse, you might need to calculate the position based on mouseX and mouseY coordinates.

In this sketch - https://editor.p5js.org/yeren/sketches/7SCNsEMo_, I'm simply shuffling the color array when the mouse is moved over the canvas.

Also, if possible avoid mutating the array.

Body:
I have been trying to recreate one of Vera Molnar's paintings, and to add a twist, I wanted to randomize the colors in the array as I drag my mouse over the canvas.  However, I cannot for the life of me figure out how to do this.  Below is one of many attempts at this.  What could I be doing wrong?

As for the colors, the intial order of the colors is something I would like to keep, as it is directly mimicking the original painting, but as the mouse is moved into the canvas/frame, i want to trigger the random colors.

Thank you for your help!

const width = 700;
const height = 700;

let radius = 58;
let len = 8;
let color;
let colors;

function setup() {
  createCanvas(width, height);

  colors = [
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#e2592f",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#000000",
    "#000000",
    "#9bd6ff",
  ];
}

function draw() {
  background(255);

  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      let x = i * 80;
      let y = j * 80;
      color = colors.shift();
      if (color === undefined) {
        color = "white";
      }
      fill(color);
      noStroke();
      ellipse(y + 65, x + 65, radius);
    }
  }

  noLoop();
}

function mouseDragged() {
  color = random(colors);
}


问:
discord.js How to ban someone when they join if they match a specific ID
I am trying to check to see if a user is a specific user when they join my discord server and then ban them if they are. I am pretty new to this and this code is not working. any help?

client.on("guildMemberAdd", (member) => {
    if (member.id === "401539231828148224") {
        member.ban;
    }
});
```

答:
GuildMember#ban is a method, not a property. You'll have to use parentheses. (())

client.on("guildMemberAdd", (member) => {
    if (member.id === "401539231828148224") {
        member.ban({ reason: "Reason for the ban." });
    }
});
```

Note that you need to activate the Server Members Intent in your application's Bot tab.

Body:
GuildMember#ban is a method, not a property. You'll have to use parentheses. (())

client.on("guildMemberAdd", (member) => {
    if (member.id === "401539231828148224") {
        member.ban({ reason: "Reason for the ban." });
    }
});

Note that you need to activate the Server Members Intent in your application's Bot tab.


问:
Creating DateTime in C#
How would I dynamically create a DateTime object, that always has what the current month/day/year is, but always has the 16:00 time component?

答:
How about:

```<code>DateTime today = DateTime.Today;
DateTime Today16 = new DateTime(today.Year, today.Month, today.Day,
                                16, 0, 0)
</code>```

That should use the year, month, day of today, and set time to 16:00 hours.

ContentLicense: CC BY-SA 3.0

Title: Creating DateTime in C#

Body:
How about:

DateTime today = DateTime.Today;
DateTime Today16 = new DateTime(today.Year, today.Month, today.Day,
                                16, 0, 0)

That should use the year, month, day of today, and set time to 16:00 hours.


问:
Git Structure when dealing with clients
Please bear with me. I'm not a git expert so I may be wrong with everything I'm even saying here.

Ok. So I saw a few questions that are similar to this one. However, I feel like mine is different enough to ask here.

We have several microapps that we have created in Github. I feel I took out all of the common parts between the microapps and separated them into a sort of library for all of the microapps to use.

Clients will purchase our microapps but sometimes want them customized in a way that's not as common. However, no matter what there are a majority of files that don't change in each microapp.

I created a repository for each microapp and for the library. I have questions on how to structure the clients' repository.

My current structure is the following:

```<code>MicroApp1
|-- File 1
|-- File 2
|-- File 3

MicroApp2
|-- File 1
|-- File 2
|-- File 3

MicroAppLibrary
|-- File 1
|-- File 2
|-- File 3
</code>```

My first question would be how should I include the library in the main microapp repositories? From my understanding, I should use submodules. I want to be able to update the library repository and merge it to all of the microapp repositories.

My second and deeper question is how I should structure the clients' repositories? The way I'm thinking of doing it is by having one repository for each client. In each repository, I would have directories basically containing the repositories. Like the following (if i don't do the submodule and instead just clone the library every time):

```<code>Client 1
|-- MicroApp1
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroApp2
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroAppLibrary
    |-- File 1
    |-- File 2
    |-- File 3
</code>```

My problem with that is how to update and merge the code to all of my clients' repositories? For example, If I make a change in the main repository of a microapp, how would I push that change to all of my clients' repositories? It doesn't seem like I can merge a repository to a directory. Would I instead use branches? There's quite a few microapps, and I would want a dev and prod branch on each of them as well.

I have many more questions but feel like it'll be too much for one post.

答: There's a special GitHub App for that, called Git X-Modules. Unlike submodules, this tool allows you to add only certain folders from a repository as a module, and updates automatically in the background. So you can create a separate repository for each of your client, add the needed components to it, and set up a one-way synchronization (so that updates from the main project repo are pulled to the clients' repos, but not vise versa).</p>

Title: Git Structure when dealing with clients

Body:
Please bear with me. I'm not a git expert so I may be wrong with everything I'm even saying here.

Ok. So I saw a few questions that are similar to this one. However, I feel like mine is different enough to ask here.

We have several microapps that we have created in Github. I feel I took out all of the common parts between the microapps and separated them into a sort of library for all of the microapps to use.

Clients will purchase our microapps but sometimes want them customized in a way that's not as common. However, no matter what there are a majority of files that don't change in each microapp.

I created a repository for each microapp and for the library. I have questions on how to structure the clients' repository.

My current structure is the following:

MicroApp1
|-- File 1
|-- File 2
|-- File 3

MicroApp2
|-- File 1
|-- File 2
|-- File 3

MicroAppLibrary
|-- File 1
|-- File 2
|-- File 3

My first question would be how should I include the library in the main microapp repositories? From my understanding, I should use submodules. I want to be able to update the library repository and merge it to all of the microapp repositories.

My second and deeper question is how I should structure the clients' repositories? The way I'm thinking of doing it is by having one repository for each client. In each repository, I would have directories basically containing the repositories. Like the following (if i don't do the submodule and instead just clone the library every time):

Client 1
|-- MicroApp1
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroApp2
    |-- File 1
    |-- File 2
    |-- File 3
|-- MicroAppLibrary
    |-- File 1
    |-- File 2
    |-- File 3

My problem with that is how to update and merge the code to all of my clients' repositories? For example, If I make a change in the main repository of a microapp, how would I push that change to all of my clients' repositories? It doesn't seem like I can merge a repository to a directory. Would I instead use branches? There's quite a few microapps, and I would want a dev and prod branch on each of them as well.

I have many more questions but feel like it'll be too much for one post.


问:
How to check if gzip compression is enabled with PHP?
Is (function_exists('ob_gzhandler') && ini_get('zlib.output_compression')) enough ?

I want to check if the host is serving compressed pages within one of the pages :)

答:
I have a class that checks based on a get request to css or js file if gzip compression is enabled and then tries to output corresponding compressed css or js file if it's enabled or a regular file if it's not.

If you are looking only at how to check if gszip is enabled then isPhpGzCompressionInProcess method of these class can help you but in most cases, you need to process some output base on it and I am pretty sure that the rest of the class can help someone too.

```<code><?php

/**
 * Class AssetBundleController
 */
class AssetBundleCompressionController
{
    /**
     * AssetBundleController constructor.
     */
    public function __construct()
    {
        $this->outputCompression();
    }

    /**
     * Trying to output compression bundle.
     */
    protected function outputCompression()
    {
        // here request to css or js file
        if (empty($_GET['vcv-script']) && empty($_GET['vcv-style'])) {
            return;
        }

        error_reporting(0);
        $mimeType = $this->getMimeType();
        header('Content-Type: ' . $mimeType);

        if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false) {
            // browser cannot accept compressed content, so need output standard JS/CSS
            echo file_get_contents($this->getBundlePath());
        } else {
            if ($this->isPhpGzCompressionInProcess()) {
                // let 3 party app gzip our content.
                echo file_get_contents($this->getBundlePath());
            } else {
                // output our gzip content.
                header("Content-Encoding: gzip");
                echo file_get_contents($this->getBundlePath(true));
            }
        }

        exit;
    }

    /**
     * Get current requested bundle path.
     *
     * @param bool $isCompress
     *
     * @return string
     */
    protected function getBundlePath($isCompress = false)
    {
        $assetType = $this->getAssetType();

        $name = $this->getCompressionRequestName($assetType);

        $path = VCV_PLUGIN_DIR_PATH . 'public/dist/' . $name . '.bundle.' . $assetType;

        if ($isCompress) {
            $path .= '.gz';
        }

        return $path;
    }

    /**
     * Check if php compression is already enabled.
     *
     * @return bool
     */
    protected function isPhpGzCompressionInProcess()
    {
        if (in_array('ob_gzhandler', ob_list_handlers())) {
            return true;
        }

        // check if zlib php exention is working
        if (extension_loaded('zlib')) {
            @ini_set('zlib.output_compression_level', 1);

            if (ini_get('zlib.output_compression_level') === '1') {
                return true;
            }
        }

        return false;
    }

    /**
     * Get compression request name.
     *
     * @return string
     */
    protected function getCompressionRequestName($assetType)
    {
        $name = '';

        $compressList = [
            'editor',
            'wp',
            'vendor',
            'runtime',
        ];

        $searchKey = $assetType === 'js' ? $_GET['vcv-script'] : $_GET['vcv-style'];

        $key = array_search($searchKey, $compressList);

        if ($key !== false) {
            $name = $compressList[$key];
        }

        return $name;
    }

    /**
     * Check current requested asset type
     *
     * @return string
     */
    protected function getAssetType()
    {
        $type = 'js';

        if (!empty($_GET['vcv-style'])) {
            $type = 'css';
        }

        return $type;
    }

    /**
     * Set current request asset mine type.
     */
    protected function getMimeType()
    {
        $type = 'application/javascript';

        if (!empty($_GET['vcv-style'])) {
            $type = 'text/css';
        }

        return $type;
    }
}
</code>```

Body:
I have a class that checks based on a get request to css or js file if gzip compression is enabled and then tries to output corresponding compressed css or js file if it's enabled or a regular file if it's not.

If you are looking only at how to check if gszip is enabled then isPhpGzCompressionInProcess method of these class can help you but in most cases, you need to process some output base on it and I am pretty sure that the rest of the class can help someone too.

<?php

/**
 * Class AssetBundleController
 */
class AssetBundleCompressionController
{
    /**
     * AssetBundleController constructor.
     */
    public function __construct()
    {
        $this->outputCompression();
    }

    /**
     * Trying to output compression bundle.
     */
    protected function outputCompression()
    {
        // here request to css or js file
        if (empty($_GET['vcv-script']) && empty($_GET['vcv-style'])) {
            return;
        }

        error_reporting(0);
        $mimeType = $this->getMimeType();
        header('Content-Type: ' . $mimeType);

        if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false) {
            // browser cannot accept compressed content, so need output standard JS/CSS
            echo file_get_contents($this->getBundlePath());
        } else {
            if ($this->isPhpGzCompressionInProcess()) {
                // let 3 party app gzip our content.
                echo file_get_contents($this->getBundlePath());
            } else {
                // output our gzip content.
                header("Content-Encoding: gzip");
                echo file_get_contents($this->getBundlePath(true));
            }
        }

        exit;
    }

    /**
     * Get current requested bundle path.
     *
     * @param bool $isCompress
     *
     * @return string
     */
    protected function getBundlePath($isCompress = false)
    {
        $assetType = $this->getAssetType();

        $name = $this->getCompressionRequestName($assetType);

        $path = VCV_PLUGIN_DIR_PATH . 'public/dist/' . $name . '.bundle.' . $assetType;

        if ($isCompress) {
            $path .= '.gz';
        }

        return $path;
    }

    /**
     * Check if php compression is already enabled.
     *
     * @return bool
     */
    protected function isPhpGzCompressionInProcess()
    {
        if (in_array('ob_gzhandler', ob_list_handlers())) {
            return true;
        }

        // check if zlib php exention is working
        if (extension_loaded('zlib')) {
            @ini_set('zlib.output_compression_level', 1);

            if (ini_get('zlib.output_compression_level') === '1') {
                return true;
            }
        }

        return false;
    }

    /**
     * Get compression request name.
     *
     * @return string
     */
    protected function getCompressionRequestName($assetType)
    {
        $name = '';

        $compressList = [
            'editor',
            'wp',
            'vendor',
            'runtime',
        ];

        $searchKey = $assetType === 'js' ? $_GET['vcv-script'] : $_GET['vcv-style'];

        $key = array_search($searchKey, $compressList);

        if ($key !== false) {
            $name = $compressList[$key];
        }

        return $name;
    }

    /**
     * Check current requested asset type
     *
     * @return string
     */
    protected function getAssetType()
    {
        $type = 'js';

        if (!empty($_GET['vcv-style'])) {
            $type = 'css';
        }

        return $type;
    }

    /**
     * Set current request asset mine type.
     */
    protected function getMimeType()
    {
        $type = 'application/javascript';

        if (!empty($_GET['vcv-style'])) {
            $type = 'text/css';
        }

        return $type;
    }
}


问:
Changing Windows 10 cursor icon with Powershell without reseting
I'm making a startup script for Windows and have been wanting to change my cursor icons. However, I want to do it without a computer reset and through powershell.

Set-ItemProperty -Path "HKCU:\Control Panel\Cursors\Arrow" -Value
"F:\nutty-squirrels\callmezippy_squirrelUnavailble.cur"

I know that it's possible to change the cursor icon without reset using the GUI, but I can't seem to get it to work using scripts, as regedit does not update the cursor (or, at least, it hasn't through my testing.)

I'm thinking that reseting some process would allow the cursor changes to occur, but I have no idea what that process is. If anyone has any idea, it would be a great help!

答:
The Set-ItemProperty call is missing the -Name argument and you need to call the WinAPI function SystemParametersInfo to notify the system about the settings change:

```<code># Define a C# class for calling WinAPI.
Add-Type -TypeDefinition @'
public class SysParamsInfo {
    [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
    public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);

    const int SPI_SETCURSORS = 0x0057;
    const int SPIF_UPDATEINIFILE = 0x01;
    const int SPIF_SENDCHANGE = 0x02;

    public static void CursorHasChanged() {
        SystemParametersInfo(SPI_SETCURSORS, 0, 0, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
    }
}
'@

# Change the cursor
Set-ItemProperty -Path 'HKCU:\Control Panel\Cursors' -Name 'Arrow' -Value '%SystemRoot%\cursors\aero_arrow_xl.cur'

# Notify the system about settings change by calling the C# code
[SysParamsInfo]::CursorHasChanged()
</code>```

Body:
The Set-ItemProperty call is missing the -Name argument and you need to call the WinAPI function SystemParametersInfo to notify the system about the settings change:

# Define a C# class for calling WinAPI.
Add-Type -TypeDefinition @'
public class SysParamsInfo {
    [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
    public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);

    const int SPI_SETCURSORS = 0x0057;
    const int SPIF_UPDATEINIFILE = 0x01;
    const int SPIF_SENDCHANGE = 0x02;

    public static void CursorHasChanged() {
        SystemParametersInfo(SPI_SETCURSORS, 0, 0, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
    }
}
'@

# Change the cursor
Set-ItemProperty -Path 'HKCU:\Control Panel\Cursors' -Name 'Arrow' -Value '%SystemRoot%\cursors\aero_arrow_xl.cur'

# Notify the system about settings change by calling the C# code
[SysParamsInfo]::CursorHasChanged()


问:
INSERT INTO with subquery and ON CONFLICT
I want to insert all elements from a JSON array into a table:

INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
WHERE value LIKE '%'
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;
```
<p>This works so far, but do I really need the <code>WHERE value LIKE '%'</code> clause?</p>
<p>When I remove it:</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;
</code>```

I get this error:

```<code>[SQLITE_ERROR] SQL error or missing database (near "DO": syntax error)
</code>```

答:
From SQL As Understood By SQLite/Parsing Ambiguity:

When the INSERT statement to which the UPSERT is attached takes its
values from a SELECT statement, there is a potential parsing
ambiguity. The parser might not be able to tell if the "ON" keyword is
introducing the UPSERT or if it is the ON clause of a join. To work
around this, the SELECT statement should always include a WHERE
clause, even if that WHERE clause is just "WHERE true".

So you need the WHERE clause, but it can be a simple WHERE true or just WHERE 1.

Body:
I want to insert all elements from a JSON array into a table:

INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
WHERE value LIKE '%'
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;

This works so far, but do I really need the WHERE value LIKE '%' clause?

When I remove it:

INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;

I get this error:

[SQLITE_ERROR] SQL error or missing database (near "DO": syntax error)


问:
MOSS SSP Issue - Failed database logons from deleted SSP
We've been having some issues with a SharePoint instance in a test
environment. Thankfully this is not production ;) The problems started
when the disk with the SQL Server databases and search index ran out
of space. Following this, the search service would not run and search
settings in the SSP were not accessible. Reclaiming the disk space did
not resolve the issue. So rather than restoring the VM, we decided to
try to fix the issue.

We created a new SSP and changed the association of all services to
the new SSP. The old SSP and it's databases were then deleted. Search
results for PDF files are no longer appearing, but the search works
fine otherwise. MySites also works OK.

Following the implementation of this change, these problems occur:

1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account.

```<code>Event Type: Failure Audit
Event Source: MSSQLSERVER
Event Category: (4)
Event ID: 18456
Date: 8/5/2008
Time: 3:55:19 PM
User: DOMAIN\SPMOSSSvc
Computer: dastest01
Description:
Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: <local machine>]
</code>```

2) SQL Server profiler is showing queries from SharePoint that reference the old
  (deleted) SSP database.

So...

Where would these references to DOMAIN\SPMOSSSvc and the old SSP
database exist?

Is there a way to 'completely' remove the SSP from the server, and
re-create? The option to delete was not available (greyed out) when a
single SSP is in place.

答:
I suspect these are related to the SQL Server Agent trying to login to a database that no longer exists.

To clear it up you need to:
 1. Go to SQL Server Management Studio
 2. Disable the job called <database name>_job_deleteExpiredSessions

If that works, then you should be all clear to delete it.

Body:
We've been having some issues with a SharePoint instance in a test
environment. Thankfully this is not production ;) The problems started
when the disk with the SQL Server databases and search index ran out
of space. Following this, the search service would not run and search
settings in the SSP were not accessible. Reclaiming the disk space did
not resolve the issue. So rather than restoring the VM, we decided to
try to fix the issue.

We created a new SSP and changed the association of all services to
the new SSP. The old SSP and it's databases were then deleted. Search
results for PDF files are no longer appearing, but the search works
fine otherwise. MySites also works OK.

Following the implementation of this change, these problems occur:

1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account.

Event Type: Failure Audit
Event Source: MSSQLSERVER
Event Category: (4)
Event ID: 18456
Date: 8/5/2008
Time: 3:55:19 PM
User: DOMAIN\SPMOSSSvc
Computer: dastest01
Description:
Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: <local machine>]

2) SQL Server profiler is showing queries from SharePoint that reference the old
  (deleted) SSP database.

So...

Where would these references to DOMAIN\SPMOSSSvc and the old SSP
database exist?

Is there a way to 'completely' remove the SSP from the server, and
re-create? The option to delete was not available (greyed out) when a
single SSP is in place.

OwnerDisplayName: Daniel McPherson


问:
deleting a buffer through a different type of pointer?
Say I have the following C++:

```<code>char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
</code>```

Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?

答:
This will work OK if the memory being pointed to and the pointer you are pointing with are both POD. In this case, no destructor would be called anyhow, and the memory allocator does not know or care about the type stored within the memory.

The only case this is OK with non-POD types, is if the pointee is a subtype of the pointer, (e.g. You are pointing at a Car with a Vehicle*) and the pointer's destructor has been declared virtual.

OwnerDisplayName: Roger Lipscombe

Body:
Say I have the following C++:

char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;

Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?

ContentLicense: CC BY-SA 2.5


问:
How do you send complex objects using WCF? Does it work? Is it good?
Can I have a data contract of this shape??

```<code>[DataContract]

public class YearlyStatistic{

[DataMember]
public string Year{get;set;}

[DataMember]
public string StatisticName {get;set;}

[DataMember]
public List<MonthlyStatistic> MonthlyStats {get;set}
};
</code>```

I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?

答: Yep, thats standard WCF serialization right there.  Are you trying to say the MonthlyStats collection has a property called WeeklyStats, or that each individual MonthlyStatistic has a WeeklyStat collection?  If its the former, that doesnt work in WCF natively.  You will have to do some fiddling in order to get it to work.  If its the latter, its perfectly fine.</p>

OwnerDisplayName: Perpetualcoder

Body:
Can I have a data contract of this shape??

[DataContract]

public class YearlyStatistic{

[DataMember]
public string Year{get;set;}

[DataMember]
public string StatisticName {get;set;}

[DataMember]
public List<MonthlyStatistic> MonthlyStats {get;set}
};

I am assuming here that class MonthlyStatistic will also need to be a DataContract. Can you do this in a web service?

LastEditorDisplayName: Perpetualcoder


问:
How do I center a value surrounded by CardActions (material ui)
So I'm having this issue, this is an image of my site

And this is code.

```<code><CardActions>
   <Typography
     style={{
     fontWeight: 'bold',
     color: 'red',
    }}
    >
    {product.price}đ  ///// the price number /////
   </Typography>
</CardActions>

</code>```

I want my price tag to be at the center of the card (similar to the sold button underneath), at first I tried to wrap it in <Box> element then add textAlign to it, no success there.

This seems like a simple issue to solve but I think I'm misunderstanding something here, I've tried many ways but to no avail. Any help would be greatly appreciated.

答: The Typography component has an align property which you can set to center.

Body:
So I'm having this issue, this is an image of my site

And this is code.

<CardActions>
   <Typography
     style={{
     fontWeight: 'bold',
     color: 'red',
    }}
    >
    {product.price}đ  ///// the price number /////
   </Typography>
</CardActions>

I want my price tag to be at the center of the card (similar to the sold button underneath), at first I tried to wrap it in <Box> element then add textAlign to it, no success there.

This seems like a simple issue to solve but I think I'm misunderstanding something here, I've tried many ways but to no avail. Any help would be greatly appreciated.


问:
Is it possible to read character array elements into a struct using ```strtoul``` in C?
I'm working on a project for a class and I could use some guidance. I need to parse a character array into constituent parts - the specifications of which I am given - but I am unsure how to do so in C.

I have been given a file and each page of the file is read into a buffer as a character array like so:

```<code>    typedef struct page_t {
    char reserved[PAGESIZE];
    } page_t;
</code>```

I have been given the following specifications about the pages read:

For each page it starts with a 2 byte gap offset, followed key-value records, a gap at the indicated offset, and lastly an 8 byte address at the end pointing to the next page

The key-value records are of the following form: 8 byte unsigned integer key followed by a value where the first 4 bytes are an unsigned integer inidicating the length of the string part of the value and a string of variable length (it will be the length indicated in the 4 bytes previously mentioned so the total length of the value portion will be length+4)

There can be multiple key-value records in the file but the sum of all key-value records will not exceed 4086 bytes and the gap is always at the end of the file prior to the address of the next page

Since I have not been given anymore explanation about format of the page read in and I need to parse through the char array I was wondering if I could do something like use the strtoul function to read the 8 bytes of the array at a time to find the correct key (and to skip over the key's values if they are not the key I am trying to match). I asked my TA about it and the answer I got was:

You can use functions that convert character (byte) arrays to numbers. Consider making a toy example program that converts a structure to a character array and back to see if scan/atoi/strtoll... have the expected behavior. If the functions do not work you can also consider reading iteratively. You may find them useful to extract the key/value size. The value as a string should work!

So I tried making a short program that converted a struct to an array and back and tried using strtoul on the string but I'm not sure that I'm doing it correctly.

So my tester program looks like this:

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

typedef struct record_test {
    uint64_t key;
    uint32_t val_size;
    char value[255];
} record_test;

int main( int argc, char ** argv ) {
    record_test record = {1234, 13, "asdfghjklqwer"};
    char page[4096];

    // print what is in record
    printf("Here's the record itself:\n");
    printf("key: %llu\n", record.key);
    printf("val_size: %u\n", record.val_size);
    printf("record: %s\n", record.value);

    memcpy(page, &record, sizeof(record_test));

    // print what is in page
    printf("Here's what's in the page:\n");
    printf("page: %s\n", page);

    // check page contents with pointer
    record_test* revert;
    revert = (record_test*)page;
    printf("Here's the reverted record using pointers:\n");
    printf("key: %llu\n", revert->key);
    printf("val_size: %u\n", revert->val_size);
    printf("record: %s\n", revert->value);

    // reading what is in page using strtoul
    char* endKey;
    char* value;

    printf("reading using strtoul:\n");
    printf("key: %lu\n", strtoul(page, &endKey, 8));
    printf("val size: %d\n", (int)strtoul(endKey, &value, 4));
    printf("value: %s\n", value);
}
</code>```

And these are the results I'm getting from it when I use printf to follow it:

```<code>Here's the record itself:
key: 1234
val_size: 13
record: asdfghjklqwer
Here's what's in the page:
page: ?
Here's the reverted record using pointers:
key: 1234
val_size: 13
record: asdfghjklqwer
reading using strtoul:
key: 0
val size: 0
value: ?

</code>```

So based on the pointer that I used to recast the struct, the character array does have the right information in it but for whatever reason the character array itself is showing ? when I try to print it and similarly the printf statements showing what strtoul is reading is showing 0 for the integers. I'm not sure what's going on here, why am I getting ? when that character isn't even in the value string?Can someone tell me where I am going wrong or if I can even use this function at all? Should I be trying to iterate though the character array using bitwise operations to read it instead?

Any help would be great! Thank you!

答:
I'm going to try to help you understand what's happening here. When you do memcpy to "flatten" your structure, let's analyze what should be going into memory.

We start out with 1234. Convert that to hexadecimal and that becomes 04D2. Now a uint64_t is probably an 8 byte long structure on your machine (you can verify this by doing a sizeof(uint64_t)), so in memory you can expect the first 8 bytes to be 00 00 00 00 00 00 04 D2.

Next up, you have 13, which in hexadecimal is 0D and it's in a uint32_t. This is typically half of what a uint64_t is, probably 4 bytes long on your machine (again, you can verify with sizeof). This means the next 4 bytes would be 00 00 00 0D.

Finally, you have an array of 255 char. char's are 1 byte long each. Each letter in your text asdfghjklqwer gets converted to an ASCII code representing that letter, so the hexadecimal would be 61 73 64 66 67 ... and the rest of those 255 bytes are just random data that's in your memory.

Now one final thing to keep in mind is the endianness of your computer. If your computer has an Intel processor or AMD processor, then your computer is using little-endian. If you're unfamiliar with what endianness is, then look at this Wikipedia article for an explanation. But, simply put, endianness refers to the order that bytes are written to memory. Little endian (which is probably what you have) means that the little ends of the bytes are written first.

So what does this mean? Up above I said the first 8 bytes in memory would be 00 00 00 00 00 00 04 D2. For little endian machines, this isn't really true. The bytes are actually written right to left. What's actually in memory would be D2 04 00 00 00 00 00 00. Hopefully this makes sense.

So now, with some little modifications to your program, you can actually print out what's in your computer's memory and you can see more clearly what I am talking about.

First, in your program, change char page[4096]; to unsigned char page[4096];. The reason is because all this would be easier to understand with unsigned characters. If you really want to know how signed and unsigned numbers work in a computer system, Google twos compliment to learn more. For now, just change it to unsigned. Then add this to your program:

```<code>record_test record = { 1234, 13, "asdfghjklqwer" };
unsigned char page[4096];

// print what is in record
printf("Here's the record itself:\n");
printf("key: %llu\n", record.key);
printf("val_size: %u\n", record.val_size);
printf("record: %s\n", record.value);

memcpy(page, &record, sizeof(record_test));

// print what is in page
for (int i = 0; i < sizeof(record_test); i++)
{
    printf("page[%d] = %02X\n", i, page[i]);
}
</code>```

When you run this program, it will execute the memcpy like before, but then I have it printing out the data stored at the page address. Try modifying your record and see if you can understand what my explanation is all about!

Hopefully this all made sense! Good luck!!!

Body:
I'm working on a project for a class and I could use some guidance. I need to parse a character array into constituent parts - the specifications of which I am given - but I am unsure how to do so in C.

I have been given a file and each page of the file is read into a buffer as a character array like so:

    typedef struct page_t {
    char reserved[PAGESIZE];
    } page_t;

I have been given the following specifications about the pages read:

For each page it starts with a 2 byte gap offset, followed key-value records, a gap at the indicated offset, and lastly an 8 byte address at the end pointing to the next page

The key-value records are of the following form: 8 byte unsigned integer key followed by a value where the first 4 bytes are an unsigned integer inidicating the length of the string part of the value and a string of variable length (it will be the length indicated in the 4 bytes previously mentioned so the total length of the value portion will be length+4)

There can be multiple key-value records in the file but the sum of all key-value records will not exceed 4086 bytes and the gap is always at the end of the file prior to the address of the next page

Since I have not been given anymore explanation about format of the page read in and I need to parse through the char array I was wondering if I could do something like use the strtoul function to read the 8 bytes of the array at a time to find the correct key (and to skip over the key's values if they are not the key I am trying to match). I asked my TA about it and the answer I got was:

You can use functions that convert character (byte) arrays to numbers. Consider making a toy example program that converts a structure to a character array and back to see if scan/atoi/strtoll... have the expected behavior. If the functions do not work you can also consider reading iteratively. You may find them useful to extract the key/value size. The value as a string should work!

So I tried making a short program that converted a struct to an array and back and tried using strtoul on the string but I'm not sure that I'm doing it correctly.

So my tester program looks like this:

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

typedef struct record_test {
    uint64_t key;
    uint32_t val_size;
    char value[255];
} record_test;

int main( int argc, char ** argv ) {
    record_test record = {1234, 13, "asdfghjklqwer"};
    char page[4096];

    // print what is in record
    printf("Here's the record itself:\n");
    printf("key: %llu\n", record.key);
    printf("val_size: %u\n", record.val_size);
    printf("record: %s\n", record.value);

    memcpy(page, &record, sizeof(record_test));

    // print what is in page
    printf("Here's what's in the page:\n");
    printf("page: %s\n", page);

    // check page contents with pointer
    record_test* revert;
    revert = (record_test*)page;
    printf("Here's the reverted record using pointers:\n");
    printf("key: %llu\n", revert->key);
    printf("val_size: %u\n", revert->val_size);
    printf("record: %s\n", revert->value);

    // reading what is in page using strtoul
    char* endKey;
    char* value;

    printf("reading using strtoul:\n");
    printf("key: %lu\n", strtoul(page, &endKey, 8));
    printf("val size: %d\n", (int)strtoul(endKey, &value, 4));
    printf("value: %s\n", value);
}

And these are the results I'm getting from it when I use printf to follow it:

Here's the record itself:
key: 1234
val_size: 13
record: asdfghjklqwer
Here's what's in the page:
page: ?
Here's the reverted record using pointers:
key: 1234
val_size: 13
record: asdfghjklqwer
reading using strtoul:
key: 0
val size: 0
value: ?

So based on the pointer that I used to recast the struct, the character array does have the right information in it but for whatever reason the character array itself is showing ? when I try to print it and similarly the printf statements showing what strtoul is reading is showing 0 for the integers. I'm not sure what's going on here, why am I getting ? when that character isn't even in the value string?Can someone tell me where I am going wrong or if I can even use this function at all? Should I be trying to iterate though the character array using bitwise operations to read it instead?

Any help would be great! Thank you!

Body:
I'm going to try to help you understand what's happening here. When you do memcpy to "flatten" your structure, let's analyze what should be going into memory.

We start out with 1234. Convert that to hexadecimal and that becomes 04D2. Now a uint64_t is probably an 8 byte long structure on your machine (you can verify this by doing a sizeof(uint64_t)), so in memory you can expect the first 8 bytes to be 00 00 00 00 00 00 04 D2.

Next up, you have 13, which in hexadecimal is 0D and it's in a uint32_t. This is typically half of what a uint64_t is, probably 4 bytes long on your machine (again, you can verify with sizeof). This means the next 4 bytes would be 00 00 00 0D.

Finally, you have an array of 255 char. char's are 1 byte long each. Each letter in your text asdfghjklqwer gets converted to an ASCII code representing that letter, so the hexadecimal would be 61 73 64 66 67 ... and the rest of those 255 bytes are just random data that's in your memory.

Now one final thing to keep in mind is the endianness of your computer. If your computer has an Intel processor or AMD processor, then your computer is using little-endian. If you're unfamiliar with what endianness is, then look at this Wikipedia article for an explanation. But, simply put, endianness refers to the order that bytes are written to memory. Little endian (which is probably what you have) means that the little ends of the bytes are written first.

So what does this mean? Up above I said the first 8 bytes in memory would be 00 00 00 00 00 00 04 D2. For little endian machines, this isn't really true. The bytes are actually written right to left. What's actually in memory would be D2 04 00 00 00 00 00 00. Hopefully this makes sense.

So now, with some little modifications to your program, you can actually print out what's in your computer's memory and you can see more clearly what I am talking about.

First, in your program, change char page[4096]; to unsigned char page[4096];. The reason is because all this would be easier to understand with unsigned characters. If you really want to know how signed and unsigned numbers work in a computer system, Google twos compliment to learn more. For now, just change it to unsigned. Then add this to your program:

record_test record = { 1234, 13, "asdfghjklqwer" };
unsigned char page[4096];

// print what is in record
printf("Here's the record itself:\n");
printf("key: %llu\n", record.key);
printf("val_size: %u\n", record.val_size);
printf("record: %s\n", record.value);

memcpy(page, &record, sizeof(record_test));

// print what is in page
for (int i = 0; i < sizeof(record_test); i++)
{
    printf("page[%d] = %02X\n", i, page[i]);
}

When you run this program, it will execute the memcpy like before, but then I have it printing out the data stored at the page address. Try modifying your record and see if you can understand what my explanation is all about!

Hopefully this all made sense! Good luck!!!


问:
Dictionary to dataclasses with inheritance of classes
I have the following class

```<code>@dataclass_json
@dataclass
class Input:
    sources: List[Sources] =None
    Transformations: List[str] =None
</code>```

As well as:

```<code>@dataclass_json
@dataclass
class Source:
    type: str =None
    label: str =None
    path: str = None
</code>```

and the two subclasses:

```<code>@dataclass_json
@dataclass
class Csv(Source):
    csv_path: str=None
    delimiter: str=';'
</code>```

and

```<code>@dataclass_json
@dataclass
class Parquet(Source):
    parquet_path: str=None
</code>```

Given now the dictionary:

```<code>parquet={type: 'Parquet', label: 'events', path: '/.../test.parquet', parquet_path: '../../result.parquet'}
</code>```

```<code>csv={type: 'Csv', label: 'events', path: '/.../test.csv', csv_path: '../../result.csv', delimiter:','}
</code>```

```<code>input={'sources':[csv, parquet]}
</code>```

Now I would like to do something like

```<code>Input().from_dict(input)
</code>```

with Output:

```<code>Input(sources: [Parquet(...), Csv(...)]).
</code>```

This actually works but it just returns the values of the 3 paremeters from dataclass Source (type, label and path) and not the other specific parameters of Csv and Parquet (csv_path, delimiter and parquet_path), which are just given its default value. This may be due to the library dataclass_json taken the schema of a class before initializing it. On the other hand, I would like to make still use of dataclass_json and just make a wrapper since it has good case and error handling.

I want this behaviour since each source type has different arguments which defines itself (for example Csv has delimiters but Parquet does not, etc. ...).

I struggled trying to obtain the class Source and find the subclasses in the library dataclass_json. Doing so, I encountered

```<code>cls.__args__[0]
</code>```

which is of type 'GenericMeta'. But given this, I could not obtain access to its subclasses.

Is there any work around?

I am using Python 3.6, by the way.

Thanks in advance for your help.

答:
I know that this thread is fairly old but for anyone else looking for a solution have a look at dacite.

Here is the link to their github repository: https://github.com/konradhalas/dacite#quick-start

and here is the quickstart code for the sake of completeness:

```<code>from dataclasses import dataclass
from dacite import from_dict

@dataclass
class User:
    name: str
    age: int
    is_active: bool

data = {
    'name': 'John',
    'age': 30,
    'is_active': True,
}

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)
</code>```

Body:
I have the following class

@dataclass_json
@dataclass
class Input:
    sources: List[Sources] =None
    Transformations: List[str] =None

As well as:

@dataclass_json
@dataclass
class Source:
    type: str =None
    label: str =None
    path: str = None

and the two subclasses:

@dataclass_json
@dataclass
class Csv(Source):
    csv_path: str=None
    delimiter: str=';'

and

@dataclass_json
@dataclass
class Parquet(Source):
    parquet_path: str=None

Given now the dictionary:

parquet={type: 'Parquet', label: 'events', path: '/.../test.parquet', parquet_path: '../../result.parquet'}

csv={type: 'Csv', label: 'events', path: '/.../test.csv', csv_path: '../../result.csv', delimiter:','}

input={'sources':[csv, parquet]}

Now I would like to do something like

Input().from_dict(input)

with Output:

Input(sources: [Parquet(...), Csv(...)]).

This actually works but it just returns the values of the 3 paremeters from dataclass Source (type, label and path) and not the other specific parameters of Csv and Parquet (csv_path, delimiter and parquet_path), which are just given its default value. This may be due to the library dataclass_json taken the schema of a class before initializing it. On the other hand, I would like to make still use of dataclass_json and just make a wrapper since it has good case and error handling.

I want this behaviour since each source type has different arguments which defines itself (for example Csv has delimiters but Parquet does not, etc. ...).

I struggled trying to obtain the class Source and find the subclasses in the library dataclass_json. Doing so, I encountered

cls.__args__[0]

which is of type 'GenericMeta'. But given this, I could not obtain access to its subclasses.

Is there any work around?

I am using Python 3.6, by the way.

Thanks in advance for your help.

Body:
I know that this thread is fairly old but for anyone else looking for a solution have a look at dacite.

Here is the link to their github repository: https://github.com/konradhalas/dacite#quick-start

and here is the quickstart code for the sake of completeness:

from dataclasses import dataclass
from dacite import from_dict

@dataclass
class User:
    name: str
    age: int
    is_active: bool

data = {
    'name': 'John',
    'age': 30,
    'is_active': True,
}

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)


问:
I am working with a data set in Python and Pandas, I need to plot a horizontal bar graph
enter image description hereI need to do a horizontal bar plot. I have countries on one axis and I need to plot 'yes','no' and 'don't know' responses per country. However, there is no numerical value and I am trying to use Pandas to achieve this. So, how can I 'count' the three different responses and then have them be linked to each different countries and then plot them in a horizontal bar plot.

This is my code:
pd.DataFrame([dataFrame['Country'].value_counts() for count in dataFrame.columns]).plot.bar(stacked=True)

But I want to link a specific column with the country

答:
Try:

```<code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'country':['iran', 'norway', 'us', 'iran','iran'], 'program': ['yes', 'yes', 'yes', 'no', 'no']})
pd.DataFrame(df.groupby('country')['program'].apply(lambda x: x.value_counts())).reset_index().pivot(index = 'country', columns = 'level_1').fillna(0).plot.bar(stacked=True)
</code>```

input df:

output:

Body:
Try:

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'country':['iran', 'norway', 'us', 'iran','iran'], 'program': ['yes', 'yes', 'yes', 'no', 'no']})
pd.DataFrame(df.groupby('country')['program'].apply(lambda x: x.value_counts())).reset_index().pivot(index = 'country', columns = 'level_1').fillna(0).plot.bar(stacked=True)

input df:

output:


问:
Python/Matplotlib: adding regression line to a plot given its intercept and slope
Using the following small dataset:

```<code>bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]
</code>```

I calculated a best-fit regression line (by hand).

```<code>yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept
</code>```

I've plotted my original data using Matplotlib like this:

```<code>plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)

#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")

plt.scatter(74,10, c="red")

#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
        arrowprops=dict(facecolor="black", shrink=0.01),
        )

#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")

#display plot
plt.show()
</code>```

I am unsure how to get the regression line onto the plot itself. I'm aware that there are plenty of builtin stuff for quickly fitting and displaying best fit lines, but I did this as practice. I know I can start the line at points '0,0.8188' (the intercept), but I don't know how to use the slope value to complete the line (set the lines end points).

Given that for each increase on the x axis, the slope should increase by '0.1462'; for the line coordinates I tried (0,0.8188) for the starting point, and (100,14.62) for the end point. But this line does not pass through my centroid point. It just misses it.

Cheers,
Jon

答:
New in matplotlib 3.3.0

plt.axline now makes it much easier to plot a regression line (or any arbitrary infinite line).

Slope-intercept form

This is simplest for regression lines. Use np.polyfit to compute the slope m and intercept b and plug them into plt.axline:

# y = m * x + b
m, b = np.polyfit(x=bill, y=tip, deg=1)
plt.axline(xy1=(0, b), slope=m, label=f'$y = {m}x {b:+}$')
```
<p><img src="https://i.stack.imgur.com/xF4zX.png" width="280"></p>
</li>
</ul>
<hr />
<ul>
<li><p><strong>Point-slope form</strong></p>
<p>If you have some other arbitrary point <code>(x1, y1)</code> along the line, it can also be used with the slope:</p>
<pre class="lang-py prettyprint-override"><code># y - y1 = m * (x - x1)
x1, y1 = (1, -0.6741)
plt.axline(xy1=(x1, y1), slope=m, label=f'$y {-y1:+} = {m}(x {-x1:+})$')
</code>```

Two points

It's also possible to use any two arbitrary points along the line:

xy1 = (1, -0.6741)
xy2 = (0, -0.8203)
plt.axline(xy1=xy1, xy2=xy2, label=f'${xy1} \\rightarrow {xy2}$')
```

Body:
Using the following small dataset:

bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]

I calculated a best-fit regression line (by hand).

yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept

I've plotted my original data using Matplotlib like this:

plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)

#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")

plt.scatter(74,10, c="red")

#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
        arrowprops=dict(facecolor="black", shrink=0.01),
        )

#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")

#display plot
plt.show()

I am unsure how to get the regression line onto the plot itself. I'm aware that there are plenty of builtin stuff for quickly fitting and displaying best fit lines, but I did this as practice. I know I can start the line at points '0,0.8188' (the intercept), but I don't know how to use the slope value to complete the line (set the lines end points).

Given that for each increase on the x axis, the slope should increase by '0.1462'; for the line coordinates I tried (0,0.8188) for the starting point, and (100,14.62) for the end point. But this line does not pass through my centroid point. It just misses it.

Cheers,
Jon

Body:
New in matplotlib 3.3.0

plt.axline now makes it much easier to plot a regression line (or any arbitrary infinite line).

Slope-intercept form

This is simplest for regression lines. Use np.polyfit to compute the slope m and intercept b and plug them into plt.axline:

# y = m * x + b
m, b = np.polyfit(x=bill, y=tip, deg=1)
plt.axline(xy1=(0, b), slope=m, label=f'$y = {m}x {b:+}$')

Point-slope form

If you have some other arbitrary point (x1, y1) along the line, it can also be used with the slope:

# y - y1 = m * (x - x1)
x1, y1 = (1, -0.6741)
plt.axline(xy1=(x1, y1), slope=m, label=f'$y {-y1:+} = {m}(x {-x1:+})$')

Two points

It's also possible to use any two arbitrary points along the line:

xy1 = (1, -0.6741)
xy2 = (0, -0.8203)
plt.axline(xy1=xy1, xy2=xy2, label=f'${xy1} \\rightarrow {xy2}$')


问:
Regex for parsing list of floating numbers in python
What's the best why to parse lists of floating numbers separated by space in python?

I have rows of this kind that will come out from a source:

```<code>string = "  4    1.6  8.29   0   0  3.55e-15 -1.28e-13   "
</code>```

with an unknown number of whitespaces separating the numbers and on the beggining or end of the string.

I usually just used numbers = map(float, string.split(" ")) when I could guarantee that there would be only one space between the numbers, and that there would not be spaces in the beginning or end of the string. I'm not skilled in regexps, but someone suggested me to use re.split("\s+", string) but that doesn't work because sometimes I got empty strings in the beggining of the resulting list.

I'm using now: re.split("\s+") but that doesn't work because sometimes I got empty strings in the beggining of the resulting list.

I'm using now:

```<code>res = map(float, re.findall("\d+\S*\d*", string)
</code>```

which is working somehow, but looks fragile and ugly to me. It can match many strings that will fail to produce numbers.

What's the best regexp pattern that will always match integers and floating point numbers with or without exponential notation so that I could use re.findall(patt, string) and safely recover a list of numbers?

Body:
What's the best why to parse lists of floating numbers separated by space in python?

I have rows of this kind that will come out from a source:

string = "  4    1.6  8.29   0   0  3.55e-15 -1.28e-13   "

with an unknown number of whitespaces separating the numbers and on the beggining or end of the string.

I usually just used numbers = map(float, string.split(" ")) when I could guarantee that there would be only one space between the numbers, and that there would not be spaces in the beginning or end of the string. I'm not skilled in regexps, but someone suggested me to use re.split("\s+", string) but that doesn't work because sometimes I got empty strings in the beggining of the resulting list.

I'm using now: re.split("\s+") but that doesn't work because sometimes I got empty strings in the beggining of the resulting list.

I'm using now:

res = map(float, re.findall("\d+\S*\d*", string)

which is working somehow, but looks fragile and ugly to me. It can match many strings that will fail to produce numbers.

What's the best regexp pattern that will always match integers and floating point numbers with or without exponential notation so that I could use re.findall(patt, string) and safely recover a list of numbers?

Body:
An example of using the str.split() method with a list comprehension -- mildly more Pythonic, and IMHO clearer, than map:

>>> string = "  4    1.6  8.29   0   0  3.55e-15 -1.28e-13   "
>>> floats = [float(x) for x in string.split()]
>>> floats
[4.0, 1.6000000000000001, 8.2899999999999991, 0.0, 0.0, 3.5500000000000001e-15,
 -1.2800000000000001e-13]


问:
getElementsByClassName not showing data in an element
I know there are a lot of questions regarding the getElementsByClassName not working, however I browsed through many and coudldnt find an answer for my situation.

Basically I have the following code:

```<code><script>

var res = localStorage.getItem('img');
    if(res == null){
            const myList = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
            res  = myList[Math.floor(Math.random() * myList.length)];
            localStorage.setItem('img', res);
        }
console.log(res);

document.getElementsByClassName("emoji").innerHTML = res
</code>```

And several spans with same class:

```<code><span class="emoji" style="font-size: 40px !important;"></span>
</code>```

The problem is that the "res" doesn't print anything in span.

The console log prints everything fine and LS stores the information perfectly .

I have tried with ID's:

```<code>document.getElementsById("emoji").innerHTML = res
</code>```

And it works perfectly, however only with the first div (as it should i suppose).

What could I be doing wrong in this situation?

Maybe I am not able to see a very simple mistake in my code.

答:
getElementByClassName always return array of element, usually can read an element from array as index basis, also similar way can get the element  from getElementByClassName.Pls see the below snippet.

const myList = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
var res  = myList[Math.floor(Math.random() * myList.length)];
document.getElementsByClassName("emoji")[0].innerHTML = res```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="emoji" style="font-size: 40px !important;"></span></code>```

Body:
getElementByClassName always return array of element, usually can read an element from array as index basis, also similar way can get the element  from getElementByClassName.Pls see the below snippet.

const myList = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
var res  = myList[Math.floor(Math.random() * myList.length)];
document.getElementsByClassName("emoji")[0].innerHTML = res

<span class="emoji" style="font-size: 40px !important;"></span>