问:
Unable to show data on Data Table at startsup the page while using Search filter but showing data after search something?
I trying to implement rows Search on Data Table on my flutter web app using TextEditingController. The data comes from The API as Json formte using Employee model.
I used FutureBuilder to get the data from the API. And i inserted Snapshot data into 'empList' as List. Also Created empsFiltered List to show search filtered data.

The issue is: Unable to show actual data in the datatable on startup. But the data is shown while searching and after clearing the searchtextfield.

I want to show the actual data on startup. And also the data should be shown as searched.

How to do this.

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

  @override
  _EditorHomeState createState() => _EditorHomeState();
}

class _EditorHomeState extends State<EditorHome> {
  TextEditingController searchController = TextEditingController();
  String _searchResult = '';

  List empList = [];
  List empsFiltered = [];

  @override
  void initState() {
    super.initState();
    empsFiltered = empList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example with search'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: ListTile(
                leading: const Icon(Icons.search),
                title: TextField(
                    controller: searchController,
                    decoration: const InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: (value) {
                      setState(() {
                        _searchResult = value;
                        empsFiltered = empList
                            .where((e) =>
                                e.name.contains(_searchResult.toLowerCase()) ||
                                e.email.contains(_searchResult.toLowerCase()))
                            .toList();
                      });
                    }),
                trailing: IconButton(
                  icon: const Icon(Icons.cancel),
                  onPressed: () {
                    setState(() {
                      searchController.clear();
                      _searchResult = '';
                      empsFiltered = empList;
                    });
                  },
                ),
              ),
            ),
            FutureBuilder<List<Employees>>(
              //initialData: const <Employees>[],
              future: fetchResults(),
              builder: (context, snapshot) {
                if (snapshot.hasError ||
                    snapshot.data == null ||
                    snapshot.connectionState == ConnectionState.waiting) {
                  return const CircularProgressIndicator();
                }
                empList = snapshot.data!;

                return DataTable(
                  headingTextStyle: const TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.black),
                  headingRowHeight: 50,
                  showBottomBorder: true,
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1)),
                  columns: const [
                    DataColumn(label: SizedBox(width: 30, child: Text('ID'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Name'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Email'))),
                  ],
                  rows: List.generate(
                    empsFiltered.length,
                    (index) {
                      var emp = empsFiltered[index];
                      return DataRow(cells: [
                        DataCell(
                          Text(emp.id.toString()),
                        ),
                        DataCell(
                          Text(emp.name),
                        ),
                        DataCell(
                          Text(emp.email),
                        ),
                      ]);
                    },
                  ).toList(),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Below is my API:

```<code>Future<List<Employees>> fetchResults() async {
  //List<Employees> _results = [];
  Uri url = Uri.parse(" http:link ");
  var response = await http.get(url);
  var resultsJson = json.decode(response.body).cast<Map<String, dynamic>>();
  List<Employees> emplist = await resultsJson
      .map<Employees>((json) => Employees.fromJson(json))
      .toList();
  return emplist;
}
</code>```

答:
I got a solution. In this Case I used Two StatefulWidgets. One is for calling Future with fetchResults() and converted into a List, And second is for Table with Search filter, And called that first stateFulWidget List into a variable on second StatefulWidgets and set that List variable in initState as into empFiltered List. Working Fine.

Example Code:

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

  @override
  _EditorHomeState createState() => _EditorHomeState();
}

class _EditorHomeState extends State<EditorHome> {
  List empList = [];

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Employees>>(
        future: fetchResults(),
        builder: (context, snapshot) {
          if (snapshot.hasError ||
              snapshot.data == null ||
              snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          }
          empList = snapshot.data!;
          return TableSec(fempList: empList);
        });
  }
}

class TableSec extends StatefulWidget {
  final List fempList;
  const TableSec({Key? key, required this.fempList}) : super(key: key);

  @override
  _TableSecState createState() => _TableSecState();
}

class _TableSecState extends State<TableSec> {
  late List empList = widget.fempList;
  List empsFiltered = [];

  TextEditingController searchController = TextEditingController();
  String _searchResult = '';

  @override
  void initState() {
    super.initState();
    empsFiltered = empList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Table"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: ListTile(
                leading: const Icon(Icons.search),
                title: TextField(
                    controller: searchController,
                    decoration: const InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: (value) {
                      setState(() {
                        _searchResult = value;
                        empsFiltered = empList
                            .where((e) =>
                                e.name.contains(_searchResult.toLowerCase()) ||
                                e.email.contains(_searchResult.toLowerCase()))
                            .toList();
                        //print(_searchResult);
                      });
                    }),
                trailing: IconButton(
                  icon: const Icon(Icons.cancel),
                  onPressed: () {
                    setState(() {
                      searchController.clear();
                      _searchResult = '';
                      empsFiltered = empList;
                    });
                  },
                ),
              ),
            ),
            DataTable(

              headingTextStyle: const TextStyle(
                  fontWeight: FontWeight.bold, color: Colors.black),
              headingRowHeight: 50,
              showBottomBorder: true,
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey, width: 1)),
              columns: const [
                DataColumn(label: SizedBox(width: 30, child: Text('ID'))),
                DataColumn(label: SizedBox(width: 100, child: Text('Name'))),
                DataColumn(label: SizedBox(width: 100, child: Text('Email'))),
              ],
              rows: List.generate(
                empsFiltered.length,
                (index) {
                  var emp = empsFiltered[index];
                  return DataRow(cells: [
                    DataCell(
                      Text(emp.id.toString()),
                    ),
                    DataCell(
                      Text(emp.name),
                    ),
                    DataCell(
                      Text(emp.email),
                    ),
                  ]);
                },
              ).toList(),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I trying to implement rows Search on Data Table on my flutter web app using TextEditingController. The data comes from The API as Json formte using Employee model.
I used FutureBuilder to get the data from the API. And i inserted Snapshot data into 'empList' as List. Also Created empsFiltered List to show search filtered data.

The issue is: Unable to show actual data in the datatable on startup. But the data is shown while searching and after clearing the searchtextfield.

I want to show the actual data on startup. And also the data should be shown as searched.

How to do this.

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

  @override
  _EditorHomeState createState() => _EditorHomeState();
}

class _EditorHomeState extends State<EditorHome> {
  TextEditingController searchController = TextEditingController();
  String _searchResult = '';

  List empList = [];
  List empsFiltered = [];

  @override
  void initState() {
    super.initState();
    empsFiltered = empList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example with search'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: ListTile(
                leading: const Icon(Icons.search),
                title: TextField(
                    controller: searchController,
                    decoration: const InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: (value) {
                      setState(() {
                        _searchResult = value;
                        empsFiltered = empList
                            .where((e) =>
                                e.name.contains(_searchResult.toLowerCase()) ||
                                e.email.contains(_searchResult.toLowerCase()))
                            .toList();
                      });
                    }),
                trailing: IconButton(
                  icon: const Icon(Icons.cancel),
                  onPressed: () {
                    setState(() {
                      searchController.clear();
                      _searchResult = '';
                      empsFiltered = empList;
                    });
                  },
                ),
              ),
            ),
            FutureBuilder<List<Employees>>(
              //initialData: const <Employees>[],
              future: fetchResults(),
              builder: (context, snapshot) {
                if (snapshot.hasError ||
                    snapshot.data == null ||
                    snapshot.connectionState == ConnectionState.waiting) {
                  return const CircularProgressIndicator();
                }
                empList = snapshot.data!;

                return DataTable(
                  headingTextStyle: const TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.black),
                  headingRowHeight: 50,
                  showBottomBorder: true,
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1)),
                  columns: const [
                    DataColumn(label: SizedBox(width: 30, child: Text('ID'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Name'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Email'))),
                  ],
                  rows: List.generate(
                    empsFiltered.length,
                    (index) {
                      var emp = empsFiltered[index];
                      return DataRow(cells: [
                        DataCell(
                          Text(emp.id.toString()),
                        ),
                        DataCell(
                          Text(emp.name),
                        ),
                        DataCell(
                          Text(emp.email),
                        ),
                      ]);
                    },
                  ).toList(),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

Below is my API:

Future<List<Employees>> fetchResults() async {
  //List<Employees> _results = [];
  Uri url = Uri.parse(" http:link ");
  var response = await http.get(url);
  var resultsJson = json.decode(response.body).cast<Map<String, dynamic>>();
  List<Employees> emplist = await resultsJson
      .map<Employees>((json) => Employees.fromJson(json))
      .toList();
  return emplist;
}

Body:
I got a solution. In this Case I used Two StatefulWidgets. One is for calling Future with fetchResults() and converted into a List, And second is for Table with Search filter, And called that first stateFulWidget List into a variable on second StatefulWidgets and set that List variable in initState as into empFiltered List. Working Fine.

Example Code:

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

  @override
  _EditorHomeState createState() => _EditorHomeState();
}

class _EditorHomeState extends State<EditorHome> {
  List empList = [];

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Employees>>(
        future: fetchResults(),
        builder: (context, snapshot) {
          if (snapshot.hasError ||
              snapshot.data == null ||
              snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          }
          empList = snapshot.data!;
          return TableSec(fempList: empList);
        });
  }
}

class TableSec extends StatefulWidget {
  final List fempList;
  const TableSec({Key? key, required this.fempList}) : super(key: key);

  @override
  _TableSecState createState() => _TableSecState();
}

class _TableSecState extends State<TableSec> {
  late List empList = widget.fempList;
  List empsFiltered = [];

  TextEditingController searchController = TextEditingController();
  String _searchResult = '';

  @override
  void initState() {
    super.initState();
    empsFiltered = empList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Table"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: ListTile(
                leading: const Icon(Icons.search),
                title: TextField(
                    controller: searchController,
                    decoration: const InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: (value) {
                      setState(() {
                        _searchResult = value;
                        empsFiltered = empList
                            .where((e) =>
                                e.name.contains(_searchResult.toLowerCase()) ||
                                e.email.contains(_searchResult.toLowerCase()))
                            .toList();
                        //print(_searchResult);
                      });
                    }),
                trailing: IconButton(
                  icon: const Icon(Icons.cancel),
                  onPressed: () {
                    setState(() {
                      searchController.clear();
                      _searchResult = '';
                      empsFiltered = empList;
                    });
                  },
                ),
              ),
            ),
            DataTable(

              headingTextStyle: const TextStyle(
                  fontWeight: FontWeight.bold, color: Colors.black),
              headingRowHeight: 50,
              showBottomBorder: true,
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey, width: 1)),
              columns: const [
                DataColumn(label: SizedBox(width: 30, child: Text('ID'))),
                DataColumn(label: SizedBox(width: 100, child: Text('Name'))),
                DataColumn(label: SizedBox(width: 100, child: Text('Email'))),
              ],
              rows: List.generate(
                empsFiltered.length,
                (index) {
                  var emp = empsFiltered[index];
                  return DataRow(cells: [
                    DataCell(
                      Text(emp.id.toString()),
                    ),
                    DataCell(
                      Text(emp.name),
                    ),
                    DataCell(
                      Text(emp.email),
                    ),
                  ]);
                },
              ).toList(),
            )
          ],
        ),
      ),
    );
  }
}


来源: stackexchange

问:
Django authenticate user does not work after logging in
I'm trying to create a custom session-based login in Django using a custom user model and a custom login template.

For some reasons it worked at first but now the authenticate method from django.contrib.auth is not authenticating user. When it did work, the login and signup button were hidden.

users/urls.py

app_name = 'users'
urlpatterns = [
    path('login/', login_user, name='login_user'),
    path('logout/', logout_user, name='logout_user'),
]

```
<p><strong>users/views.py</strong></p>
<pre class="lang-py prettyprint-override"><code>app_name = 'users'
def login_user(request):
    django_logout(request)
    message = ''
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(request, email=email, password=password)
        if user is not None:
            django_login(request, user)
            return redirect('homepage')
        else:
            message = "Log in failed!"
            messages.error(request, message)
            return redirect('users:login_user')
    else:
        return render(request, 'users/login.html')

@login_required(login_url='users/login/')
def logout_user(request):
    django_logout(request)
</code>```

templates/users/login.html

<form class="bg-white rounded-5 shadow-5-strong p-5" method="post" action="/">
            {% csrf_token %}

            Email address
            <input type="email" name="email" id="form1Example1" class="form-control" />

            Password
            <input type="password" type="password" id="form1Example2" class="form-control" />

          <button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>

```
<p><strong>users/models.py</strong></p>
<pre class="lang-py prettyprint-override"><code>class CustomUserManager(BaseUserManager):
    def create_superuser(self, email, password):
        if email is None:
            raise TypeError('Users should have an Email')
        if password is None:
            raise TypeError('Password should not be none')
        user = self.create_user(email, password)
        user.is_superuser = True
        user.is_staff = True
        if user.is_superuser is not True:
            raise ValueError(
                'Superuser must be assigned to is_staff=True.')
        if user.is_staff is not True:
            raise ValueError(
                'Superuser must be assigned to is_superuser=True.')
        user.save()
        return user

    def create_user(self, email, password):
        if email is None:
            raise TypeError('Users should have an Email')
        if password is None:
            raise TypeError('Users must have a password')
        email = self.normalize_email(email)
        user = self.model(email=email)
        user.set_password(password)
        user.save()
        return user

AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google',
                  'twitter': 'twitter', 'email': 'email'}
class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True, db_index=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    about = models.TextField(_(
        'about'), max_length=500, blank=True)
    auth_provider = models.CharField(
        max_length=255, blank=False,
        null=False, default=AUTH_PROVIDERS.get('email'))
    USERNAME_FIELD = 'email'
    objects = CustomUserManager()

    def __str__(self):
        return self.email
</code>```

My sign in button in homepage.html

          <button type="button" class="btn btn-link px-3 me-2">
            Login
          </button>

```

Could you show me the way to solve this? Thank you!

答:
Change your form like this

```<code><form class="bg-white rounded-5 shadow-5-strong p-5" method="post" action="{% url 'users:login_user' %}">
            {% csrf_token %}

          <!-- Email input -->
          <div class="form-outline mb-4">
            <label class="form-label" for="form1Example1">Email address</label>
            <input type="email" name="email" id="form1Example1" class="form-control" />

          </div>

          <!-- Password input -->
          <div class="form-outline mb-4">
            <label class="form-label" for="form1Example2">Password</label>
            <input type="password" name="password" type="password" id="form1Example2" class="form-control" />

          </div>

          <!-- Submit button -->
          <button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>
</code>```

MultiValueDictKeyError at /users/login/ 'password'

this is because you're trying to access password value from request like this request.POST['password'] but you've not set name to your input(password) that's why it is giving you an error

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a custom session-based login in Django using a custom user model and a custom login template.

For some reasons it worked at first but now the authenticate method from django.contrib.auth is not authenticating user. When it did work, the login and signup button were hidden.

users/urls.py

app_name = 'users'
urlpatterns = [
    path('login/', login_user, name='login_user'),
    path('logout/', logout_user, name='logout_user'),
]

users/views.py

app_name = 'users'
def login_user(request):
    django_logout(request)
    message = ''
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        user = authenticate(request, email=email, password=password)
        if user is not None:
            django_login(request, user)
            return redirect('homepage')
        else:
            message = "Log in failed!"
            messages.error(request, message)
            return redirect('users:login_user')
    else:
        return render(request, 'users/login.html')

@login_required(login_url='users/login/')
def logout_user(request):
    django_logout(request)

templates/users/login.html

<form class="bg-white rounded-5 shadow-5-strong p-5" method="post" action="/">
            {% csrf_token %}

            Email address
            <input type="email" name="email" id="form1Example1" class="form-control" />

            Password
            <input type="password" type="password" id="form1Example2" class="form-control" />

          <button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>

users/models.py

class CustomUserManager(BaseUserManager):
    def create_superuser(self, email, password):
        if email is None:
            raise TypeError('Users should have an Email')
        if password is None:
            raise TypeError('Password should not be none')
        user = self.create_user(email, password)
        user.is_superuser = True
        user.is_staff = True
        if user.is_superuser is not True:
            raise ValueError(
                'Superuser must be assigned to is_staff=True.')
        if user.is_staff is not True:
            raise ValueError(
                'Superuser must be assigned to is_superuser=True.')
        user.save()
        return user

    def create_user(self, email, password):
        if email is None:
            raise TypeError('Users should have an Email')
        if password is None:
            raise TypeError('Users must have a password')
        email = self.normalize_email(email)
        user = self.model(email=email)
        user.set_password(password)
        user.save()
        return user

AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google',
                  'twitter': 'twitter', 'email': 'email'}
class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True, db_index=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    about = models.TextField(_(
        'about'), max_length=500, blank=True)
    auth_provider = models.CharField(
        max_length=255, blank=False,
        null=False, default=AUTH_PROVIDERS.get('email'))
    USERNAME_FIELD = 'email'
    objects = CustomUserManager()

    def __str__(self):
        return self.email

My sign in button in homepage.html

          <button type="button" class="btn btn-link px-3 me-2">
            Login
          </button>

Could you show me the way to solve this? Thank you!

Body:
Change your form like this

<form class="bg-white rounded-5 shadow-5-strong p-5" method="post" action="{% url 'users:login_user' %}">
            {% csrf_token %}

          <!-- Email input -->
          <div class="form-outline mb-4">
            <label class="form-label" for="form1Example1">Email address</label>
            <input type="email" name="email" id="form1Example1" class="form-control" />

          </div>

          <!-- Password input -->
          <div class="form-outline mb-4">
            <label class="form-label" for="form1Example2">Password</label>
            <input type="password" name="password" type="password" id="form1Example2" class="form-control" />

          </div>

          <!-- Submit button -->
          <button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>

MultiValueDictKeyError at /users/login/ 'password'

this is because you're trying to access password value from request like this request.POST['password'] but you've not set name to your input(password) that's why it is giving you an error


问:
Why dont the buttons in my Drawer Do anything?
I have some icons in a drawer, but none of them seem to navigate to another page, and I have no clue why. There are no errors, etc. it's just a navigation drawer, with a few buttons, and MainDrawer.dart contains the Drawer, while DrawerListTile.dart contains the attributes of each tile on the drawer.

Here is the MainDrawer.dart

```<code>import 'package:iona_central/Screens/News/news.dart';
import 'package:iona_central/Screens/Exam/Exam_Rseult.dart';
import 'package:iona_central/Screens/Leave_Apply/Leave_apply.dart';
import 'package:iona_central/Screens/home.dart';
import 'package:iona_central/Widgets/DrawerListTile.dart';

class MainDrawer extends StatefulWidget {
  @override
  _MainDrawerState createState() => _MainDrawerState();
}

class _MainDrawerState extends State<MainDrawer> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(
      children: [
        DrawerListTile(
            imgpath: "home.png",
            name: "Home",
            ontap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => Home(),
                ),
              );
            }),
        DrawerListTile(
          imgpath: "news.png",
          name: "News",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => attendance(),
              ),
            );
          },
        ),

        //DrawerListTile(imgpath: "profile.png", name: "Profile", ontap: () {}),
        DrawerListTile(
          imgpath: "ipsports.png",
          name: "Sports",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => ExamResult(),
              ),
            );
          },
        ),
        /*DrawerListTile(
            imgpath: "calendar.png", name: "Time Table", ontap: () {}), */
        DrawerListTile(
          imgpath: "gfl.png",
          name: "GFL",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
        DrawerListTile(
          imgpath: "club.png",
          name: "Clubs",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
      ],
    ));
  }
}

</code>```

Here is DrawerListTile.dart

```<code>import 'package:flutter/material.dart';

class DrawerListTile extends StatelessWidget {
  final String name;
  final String imgpath;
  final Function ontap;

  const DrawerListTile(
      {Key? key,
      required this.name,
      required this.imgpath,
      required this.ontap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () => ontap,
      leading: Image.asset(
        "assets/${imgpath}",
        height: 30,
      ),
      contentPadding: EdgeInsets.only(
        left: 70,
        top: 5,
        bottom: 5,
      ),
      title: Text(
        "${name}",
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}

</code>```

答:
The problem comes from onTap: () => ontap - it doesn't call the ontap functions passed.

Use a tear-off like: onTap: ontap

Check this out:

```<code>class DrawerListTile extends StatelessWidget {
  final String name;
  final String imgpath;
  final VoidCallback ontap;

  const DrawerListTile(
      {Key? key,
      required this.name,
      required this.imgpath,
      required this.ontap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: ontap,
      leading: Image.asset(
        "assets/${imgpath}",
        height: 30,
      ),
      contentPadding: EdgeInsets.only(
        left: 70,
        top: 5,
        bottom: 5,
      ),
      title: Text(
        "${name}",
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}
</code>```

Body:
I have some icons in a drawer, but none of them seem to navigate to another page, and I have no clue why. There are no errors, etc. it's just a navigation drawer, with a few buttons, and MainDrawer.dart contains the Drawer, while DrawerListTile.dart contains the attributes of each tile on the drawer.

Here is the MainDrawer.dart

import 'package:iona_central/Screens/News/news.dart';
import 'package:iona_central/Screens/Exam/Exam_Rseult.dart';
import 'package:iona_central/Screens/Leave_Apply/Leave_apply.dart';
import 'package:iona_central/Screens/home.dart';
import 'package:iona_central/Widgets/DrawerListTile.dart';

class MainDrawer extends StatefulWidget {
  @override
  _MainDrawerState createState() => _MainDrawerState();
}

class _MainDrawerState extends State<MainDrawer> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(
      children: [
        DrawerListTile(
            imgpath: "home.png",
            name: "Home",
            ontap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => Home(),
                ),
              );
            }),
        DrawerListTile(
          imgpath: "news.png",
          name: "News",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => attendance(),
              ),
            );
          },
        ),

        //DrawerListTile(imgpath: "profile.png", name: "Profile", ontap: () {}),
        DrawerListTile(
          imgpath: "ipsports.png",
          name: "Sports",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => ExamResult(),
              ),
            );
          },
        ),
        /*DrawerListTile(
            imgpath: "calendar.png", name: "Time Table", ontap: () {}), */
        DrawerListTile(
          imgpath: "gfl.png",
          name: "GFL",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
        DrawerListTile(
          imgpath: "club.png",
          name: "Clubs",
          ontap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (BuildContext context) => LeaveApply(),
              ),
            );
          },
        ),
      ],
    ));
  }
}

Here is DrawerListTile.dart

import 'package:flutter/material.dart';

class DrawerListTile extends StatelessWidget {
  final String name;
  final String imgpath;
  final Function ontap;

  const DrawerListTile(
      {Key? key,
      required this.name,
      required this.imgpath,
      required this.ontap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () => ontap,
      leading: Image.asset(
        "assets/${imgpath}",
        height: 30,
      ),
      contentPadding: EdgeInsets.only(
        left: 70,
        top: 5,
        bottom: 5,
      ),
      title: Text(
        "${name}",
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}

Body:
The problem comes from onTap: () => ontap - it doesn't call the ontap functions passed.

Use a tear-off like: onTap: ontap

Check this out:

class DrawerListTile extends StatelessWidget {
  final String name;
  final String imgpath;
  final VoidCallback ontap;

  const DrawerListTile(
      {Key? key,
      required this.name,
      required this.imgpath,
      required this.ontap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: ontap,
      leading: Image.asset(
        "assets/${imgpath}",
        height: 30,
      ),
      contentPadding: EdgeInsets.only(
        left: 70,
        top: 5,
        bottom: 5,
      ),
      title: Text(
        "${name}",
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}


问:
flutter richtext separated align
i see this code for rich text in flutter:

```<code>  return Row(
        children: <Widget>[
          ?
          Container(
            child: RichText(
              text: TextSpan(
                text: "Hello",
                style: TextStyle(fontSize: 20.0,color: Colors.black),
                children: <TextSpan>[
                  TextSpan(text:"Bold"),
                    style: TextStyle( fontSize: 10.0, color: Colors.grey),

                  ),

                ],
              ),
            ),
          )
</code>```

this print

```<code>Hellobold
</code>```

but i need to separe both text one aling to left other to right, like this

```<code>Hello                               bold
</code>```

how i do this?

thanks

答:
if you want to use textalign in RichText use WidgetSpan and Text widget

```<code>WidgetSpan(
  child: Text(
    'your text',
    textAlign: TextAlign.left,
    textDirection: TextDirection.ltr,
  ),
),
</code>```

Title: flutter richtext separated align

Body:
i see this code for rich text in flutter:

  return Row(
        children: <Widget>[
          ?
          Container(
            child: RichText(
              text: TextSpan(
                text: "Hello",
                style: TextStyle(fontSize: 20.0,color: Colors.black),
                children: <TextSpan>[
                  TextSpan(text:"Bold"),
                    style: TextStyle( fontSize: 10.0, color: Colors.grey),

                  ),

                ],
              ),
            ),
          )

this print

Hellobold

but i need to separe both text one aling to left other to right, like this

Hello                               bold

how i do this?

thanks

Body:
if you want to use textalign in RichText use WidgetSpan and Text widget

WidgetSpan(
  child: Text(
    'your text',
    textAlign: TextAlign.left,
    textDirection: TextDirection.ltr,
  ),
),


问:
What is the easiest way to simulate 100 different browsers connections?
I have a website that I want to conduct testing on. All you need to do is to go to homepage and enter given password. Unfortunately, I can only open one instance in one browser(have no idea what it uses, probably cookies). If I open second tab in the same browser it just redirects me to the same screen as first tab. The question is: How can I simulate 100 broswers connection (Is there any addons or something else, so the application would not treat different tabs as the same browser or something?)</p>

答:
Use Apache's ab (Apache benchmark) tool. http://httpd.apache.org/docs/2.0/programs/ab.html
Example:
ab -c 10 -n 1000 http://www.yourdomain.com/mypage.jsp

This keeps sending 10 concurrent requests (-c 10) until 1000 http-requests (-n 1000) have been sent.

Option -A allows you to send authentication credentials.

ContentLicense: CC BY-SA 3.0


问:
ModuleNotFoundError: No module named 'sklearn.linear_model._base' - Why found this error on my ec2 ubuntu cloud server?
On my AWS ec2 cloud server(ubuntu) when I run the server.py file to run my server then is showed me the below error:

```<code>File "server.py", line 31, in <module>
    util.load_saved_artifacts()
  File "/home/ubuntu/HousePricePrediction/server/util.py", line 39, in load_saved_artifacts
    __model = pickle.load(f)
ModuleNotFoundError: No module named 'sklearn.linear_model._base'
</code>```

答:
The model was created on a different system with a different version of sklearn.
After finding this error then I checked the scikit-learn version.

Check the current version:

```<code>sudo pip3 list scikit
</code>```

Note: If your os isn't ubuntu then remove 'sudo'. And if you are
using 'conda' then use 'conda' instead of pip3.

Then I found the current version scikit-learn (0.20.3) and realized that maybe this version is backdated or not suitable for the system. Then I upgrade scikit-learn.

Upgrade scikit-learn:

```<code>sudo pip3 install -U scikit-learn
</code>```

After that, I again run my server.py file to run the server and my server successfully runs.

Note: If your system needs a specific version of the 'scikit-learn' library for your system
then use this command:

sudo pip3 install scikit-learn=0.17 - (for example)

Body:
On my AWS ec2 cloud server(ubuntu) when I run the server.py file to run my server then is showed me the below error:

File "server.py", line 31, in <module>
    util.load_saved_artifacts()
  File "/home/ubuntu/HousePricePrediction/server/util.py", line 39, in load_saved_artifacts
    __model = pickle.load(f)
ModuleNotFoundError: No module named 'sklearn.linear_model._base'

Body:
The model was created on a different system with a different version of sklearn.
After finding this error then I checked the scikit-learn version.

Check the current version:

sudo pip3 list scikit

Note: If your os isn't ubuntu then remove 'sudo'. And if you are
using 'conda' then use 'conda' instead of pip3.

Then I found the current version scikit-learn (0.20.3) and realized that maybe this version is backdated or not suitable for the system. Then I upgrade scikit-learn.

Upgrade scikit-learn:

sudo pip3 install -U scikit-learn

After that, I again run my server.py file to run the server and my server successfully runs.

Note: If your system needs a specific version of the 'scikit-learn' library for your system
then use this command:

sudo pip3 install scikit-learn=0.17 - (for example)


问:
JSTL JSP ternary if in expression language
Specifically about problem:

I have two tags

It's work:

```<code><td style="color: ${mealTo.excess ? "red" : "green"}">${mealTo.dateTime}</td>
</code>```

It don't work:

```<code><c:set var="colorText" value="${mealTo.excess ? " red" : "green"}"/>
</code>```

code from IDE

Why don't work ternary if in expression language?

More about the problem:

Two tags duplicates the code in expression language:

```<code><td style="color: ${mealTo.excess ? "red" : "green"}">${mealTo.dateTime}</td>
<td style="color: ${mealTo.excess ? "red" : "green"}">${mealTo.description}</td>
</code>```

I want this code place in jstl variable and use it:

```<code><c:set var="colorText" value="${mealTo.excess ? " red" : "green"}"/>
<td style="color: ${colorText}">${mealTo.dateTime}</td>
<td style="color: ${colorText}">${mealTo.description}</td>
</code>```

But IDE suggests what first tag with jstl variable incorrect.

Thanks!

答: Use single quote around 'red' and 'green' Hope this will help

Body:
Specifically about problem:

I have two tags

It's work:

${mealTo.dateTime}

It don't work:

<c:set var="colorText" value="${mealTo.excess ? " red" : "green"}"/>

code from IDE

Why don't work ternary if in expression language?

More about the problem:

Two tags duplicates the code in expression language:

${mealTo.dateTime}
${mealTo.description}

I want this code place in jstl variable and use it:

<c:set var="colorText" value="${mealTo.excess ? " red" : "green"}"/>
${mealTo.dateTime}
${mealTo.description}

But IDE suggests what first tag with jstl variable incorrect.

Thanks!


问:
VirtualBox error "Failed to open a session for the virtual machine"
I have a virtual machine with Windows XP with a clean installation. I set it as immutable to create a differential machine, so I create a new virtual machine, select the immutable hard disk and create a new snapshot in the new virtual machine folder.

However, when I try to start the virtual machine I get this error:

```<code>"failed to open a session for the virtual machine".

Código Resultado:
VBOX_E_INVALID_OBJECT_STATE (0x80BB0007)
Componente:
ProgressProxy
Interfaz:
IProgress {c20238e4-3221-4d3f-8891-81ce92d9f913}
</code>```

What is the problem? until now I can use differential virtual machines without problems. I have installed the last version or VirtualBox v4.3.4 and the problem persists.

If I set the hard driver as normal and I create a new virtual machine and select this hard drive I don't have any problem.

EDIT: I use the same virtual disk and do the same steps in another computer and it works fine. I think that the problem is the VirtualBox of my computer with the problem, but I try to uninstall the program and reinstall it and the problem persists, so I don't know how to solve the problem.

EDIT 2: if I set the virtual harddrive as multiattached instead of immutable, then it works fine. In my case is enough, but I know that it would be work as immutable because it was work until now and it works in another computer.

I try to create a new user in windows to try if the problem if with the configuration of my account, but the problem persists. So I think that some general configuration of VirtualBox has been corrupted and I am not be able to repair it.

I would like to know if there is any solution to use a immutable hard drive, because I would like to solve the problem with VirtualBox, although by the moment the multiattached hard disk is enough.

答:
This worked for me:

In the Oracle VM Manager - right click on your virtual maching (for example kali linux).

In the menu choose "discard saved state".
Then press discard and restart your virtual machine.

Body:
I have a virtual machine with Windows XP with a clean installation. I set it as immutable to create a differential machine, so I create a new virtual machine, select the immutable hard disk and create a new snapshot in the new virtual machine folder.

However, when I try to start the virtual machine I get this error:

"failed to open a session for the virtual machine".

Código Resultado:
VBOX_E_INVALID_OBJECT_STATE (0x80BB0007)
Componente:
ProgressProxy
Interfaz:
IProgress {c20238e4-3221-4d3f-8891-81ce92d9f913}

What is the problem? until now I can use differential virtual machines without problems. I have installed the last version or VirtualBox v4.3.4 and the problem persists.

If I set the hard driver as normal and I create a new virtual machine and select this hard drive I don't have any problem.

EDIT: I use the same virtual disk and do the same steps in another computer and it works fine. I think that the problem is the VirtualBox of my computer with the problem, but I try to uninstall the program and reinstall it and the problem persists, so I don't know how to solve the problem.

EDIT 2: if I set the virtual harddrive as multiattached instead of immutable, then it works fine. In my case is enough, but I know that it would be work as immutable because it was work until now and it works in another computer.

I try to create a new user in windows to try if the problem if with the configuration of my account, but the problem persists. So I think that some general configuration of VirtualBox has been corrupted and I am not be able to repair it.

I would like to know if there is any solution to use a immutable hard drive, because I would like to solve the problem with VirtualBox, although by the moment the multiattached hard disk is enough.


问:
Accessing SQL metadata in LightSwitch
I am trying to access extended properties in my SQL database in LightSwitch. Ideally I would be able to populate a choicelist based on these extended properties - namely picklist values.

Is there any way in which I can do this?

Any help would be much appreciated.

Cheers

Jimmy

答: WCF RIA Service is always your answer. You can do anything.</p>

Title: Accessing SQL metadata in LightSwitch


问:
How to fetch data from firebase and put inside spinner

I was trying to fetch data from firebase and put it inside a spinner, I just want name of the nodes to be displayed on the spinner drop-down , But the entire branch of node is displaying as a single item in drop down.
Please help me to fix this
Let me show you my Java code

```<code>package com.example.presence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class add_Attendance_Activity extends AppCompatActivity {
    Spinner spinner;
    ArrayList<String> list;
    ArrayAdapter<String> adapter;
    DatabaseReference href;
    ValueEventListener listener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_attendance);
        href= FirebaseDatabase.getInstance().getReference("students");
        spinner=findViewById(R.id.spinner);
        list=new ArrayList<String>();
        adapter=new ArrayAdapter<>(this,R.layout.support_simple_spinner_dropdown_item,list);
        spinner.setAdapter(adapter);
        list.clear();
        fetchData();
        adapter.notifyDataSetChanged();
    }
    public void fetchData(){
        listener=href.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot mydata: snapshot.getChildren()) {
                    list.add(mydata.getValue().toString());
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

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

Spinner Looks like this

答:
Use a POJO model instead of plain string to store your data in the array adapter.

You can use Gson to populate your model from the repository which you get data and in your POJO model, override toString() method and return whatever you want your spinner to show!

Kotlin version:

```<code>override fun toString(): String {
    return when (persianName != null) {
      true -> StringBuilder(name)
        .append(" (").append(persianName)
        .append(")").toString()
      else -> name
    }
  }
</code>```

Java version:

```<code>@NonNull
  @Override
  public String toString() {
    return name + " " + supervisorname;
  }
</code>```

Body:
I was trying to fetch data from firebase and put it inside a spinner, I just want name of the nodes to be displayed on the spinner drop-down , But the entire branch of node is displaying as a single item in drop down.
Please help me to fix this
Let me show you my Java code

package com.example.presence;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class add_Attendance_Activity extends AppCompatActivity {
    Spinner spinner;
    ArrayList<String> list;
    ArrayAdapter<String> adapter;
    DatabaseReference href;
    ValueEventListener listener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_attendance);
        href= FirebaseDatabase.getInstance().getReference("students");
        spinner=findViewById(R.id.spinner);
        list=new ArrayList<String>();
        adapter=new ArrayAdapter<>(this,R.layout.support_simple_spinner_dropdown_item,list);
        spinner.setAdapter(adapter);
        list.clear();
        fetchData();
        adapter.notifyDataSetChanged();
    }
    public void fetchData(){
        listener=href.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot mydata: snapshot.getChildren()) {
                    list.add(mydata.getValue().toString());
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

Spinner Looks like this

Body:
Use a POJO model instead of plain string to store your data in the array adapter.

You can use Gson to populate your model from the repository which you get data and in your POJO model, override toString() method and return whatever you want your spinner to show!

Kotlin version:

override fun toString(): String {
    return when (persianName != null) {
      true -> StringBuilder(name)
        .append(" (").append(persianName)
        .append(")").toString()
      else -> name
    }
  }

Java version:

@NonNull
  @Override
  public String toString() {
    return name + " " + supervisorname;
  }


问:
using setState to add a object in nested array
I'm using ireact set state and trying to post data to my object that is nested with arrays.

Here is my default state:

```<code> const [data, setData] = useState({
    working_hours: [
      {
        id: '',
        description: '',
        hours: '',
        price: '',
        total: '',
      },
    ],
    parts: [
      {
        id: '',
        description: '',
        unit: '',
        quanity: '',
        price: '',
        total: '',
      },
    ],
    other: [
      {
        id: '',
        description: '',
        quanity: '',
        price: '',
        total: '',
      },
    ],
  });
</code>```

So what I want to do is for example push an object to they array working_hours and I don't know how to do it.

Here is my try:

```<code> const handleAdd = () => {
    const test = {
      id: 3,
      description: 'This is a description',
      hours: 4.2,
      price: 500,
      total: 4421,
    };
    setData({ ...data, working_hours: test });
  };
</code>```

But this is removing the last state and only replacing the first item.

答:
This should work</p>
```<code>const handleAdd = () => {
    const test = {
      id: 3,
      description: 'This is a description',
      hours: 4.2,
      price: 500,
      total: 4421,
    };
    const newData = {
      ...data,
      working_hours: [
        ...(data?.working_hours ? data.working_hours : {}),
        test
      ]
    };
    setData(newData);
};
</code>```

Body:
I'm using ireact set state and trying to post data to my object that is nested with arrays.

Here is my default state:

 const [data, setData] = useState({
    working_hours: [
      {
        id: '',
        description: '',
        hours: '',
        price: '',
        total: '',
      },
    ],
    parts: [
      {
        id: '',
        description: '',
        unit: '',
        quanity: '',
        price: '',
        total: '',
      },
    ],
    other: [
      {
        id: '',
        description: '',
        quanity: '',
        price: '',
        total: '',
      },
    ],
  });

So what I want to do is for example push an object to they array working_hours and I don't know how to do it.

Here is my try:

 const handleAdd = () => {
    const test = {
      id: 3,
      description: 'This is a description',
      hours: 4.2,
      price: 500,
      total: 4421,
    };
    setData({ ...data, working_hours: test });
  };

But this is removing the last state and only replacing the first item.

Body:
This should work

const handleAdd = () => {
    const test = {
      id: 3,
      description: 'This is a description',
      hours: 4.2,
      price: 500,
      total: 4421,
    };
    const newData = {
      ...data,
      working_hours: [
        ...(data?.working_hours ? data.working_hours : {}),
        test
      ]
    };
    setData(newData);
};


问:
mysql monitoring and management
i want to monitor and manage mysql database sever with jmx. when i hit google it display connector/mxj. i get it and execute MysqldHtmlAdaptor file. it shows mysql server variables. but i can't rivet that instance into original mysql server running on other server.

plz help.

is there any good tutorial for JMX for mysql ...

答: The MySQL server does not support JMX natively, so you'll need to write something yourself that acts as a bridge between JMX and the MySQL management tools; MySQL Server Status Variables is probably a good place to start.</p>

OwnerDisplayName: captain

ContentLicense: CC BY-SA 2.5

Title: mysql monitoring and management

OwnerDisplayName: andri


问:
'Undefined function' when using DAO QueryDef in VBA
I'm assigning an Access 2007 query to a QueryDef in Excel VBA.  My query calls a user-defined function, because it performs a calculation on the results of evaluating a field with a regular expression.  I'm using a QueryDef because I'm collecting values in a UserForm and want to pass them to the query as parameters.

When I run my VBA code, I get an error: "Run-time error '3085': Undefined function 'regexFunc' in expression."

This question suggests that the problem is that DAO is unable to call Access UDFs from Excel, so I copied my UDF into the Excel VBA module, but I still get the error.

Access query:

```<code>select field1 from dataTable where regexFunc(field1)=[regexVal]
</code>```

Here's the Excel VBA code:

```<code>'QueryDef function
Sub makeQueryDef (str As String)

Dim qdf As QueryDef
Dim db As Database

Set db = OpenDatabase(DBpath)
Set qdf = db.QueryDefs("paramQuery")
qdf.Parameters("regexVal") = (str="test")
doSomething qdf

End Sub

'Regex function copied from Access VBA module to Excel VBA module
Function regexFunc(str As String) As Boolean

Dim re As RegExp
Dim matches As MatchCollection

regexFunc = False
Set re = New RegExp
re.Pattern = "\reg[ex](pattern)?"
Set matches = re.Execute(str)
If matches.Count <> 0 Then
    regexFunc = True
End If

End Function
</code>```

答:
This is how I would do it... just tested it and it works fine with my UDF:

One thing - are you required to not use New Access.Application?

```<code>Sub GetMyDataWithUDF()
    Dim oApp As Access.Application
    Dim qd As QueryDef

    sFileName = "C:\Users\AUser\Desktop\adatabase.mdb"
    Set oApp = New Access.Application
    oApp.OpenCurrentDatabase (sFileName)

    Set qd = oApp.CurrentDb.QueryDefs("Query1")

    If oApp.DCount("*", "MSysObjects", "Name='dataTableResults'") > 0 Then _
        oApp.CurrentDb.TableDefs.Delete "dataTableResults"

    qd.Parameters("avalue") = "4"
    qd.Execute

    oApp.Quit
    Set oApp = Nothing

    Dim oRS As ADODB.Recordset
    sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sFileName & ";User Id=admin;Password=;"
    Set oRS = New ADODB.Recordset
    oRS.Open "SELECT * FROM dataTableResults", sConn
    Sheet1.Cells.Clear
    Sheet1.Range("A1").CopyFromRecordset oRS
    oRS.Close
    Set oRS = Nothing
End Sub
</code>```

Note that I made my underlying query a SELECT ... INTO query that creates a table called 'dataTableResults'

This is my query (QueryDef) in Access:

```<code>SELECT dataTable.Field1, dataTable.Field2 INTO dataTableResults
FROM dataTable
WHERE mysqr(dataTable.Field1)=[avalue];
</code>```

My MS-Access DB has a function called "mysqr", which gets used in the SQL above.

```<code>Function mysqr(Num)
        mysqr = Num * Num
    End Function
</code>```

The table "dataTable" I'm querying against is just a list of numbers, so if my parameter "avalue" is "16", then I get the row "4" back. If I enter "4" (as in my code), I get "2" back.

Body:
I'm assigning an Access 2007 query to a QueryDef in Excel VBA.  My query calls a user-defined function, because it performs a calculation on the results of evaluating a field with a regular expression.  I'm using a QueryDef because I'm collecting values in a UserForm and want to pass them to the query as parameters.

When I run my VBA code, I get an error: "Run-time error '3085': Undefined function 'regexFunc' in expression."

This question suggests that the problem is that DAO is unable to call Access UDFs from Excel, so I copied my UDF into the Excel VBA module, but I still get the error.

Access query:

select field1 from dataTable where regexFunc(field1)=[regexVal]

Here's the Excel VBA code:

'QueryDef function
Sub makeQueryDef (str As String)

Dim qdf As QueryDef
Dim db As Database

Set db = OpenDatabase(DBpath)
Set qdf = db.QueryDefs("paramQuery")
qdf.Parameters("regexVal") = (str="test")
doSomething qdf

End Sub

'Regex function copied from Access VBA module to Excel VBA module
Function regexFunc(str As String) As Boolean

Dim re As RegExp
Dim matches As MatchCollection

regexFunc = False
Set re = New RegExp
re.Pattern = "\reg[ex](pattern)?"
Set matches = re.Execute(str)
If matches.Count <> 0 Then
    regexFunc = True
End If

End Function

Body:
This is how I would do it... just tested it and it works fine with my UDF:

One thing - are you required to not use New Access.Application?

Sub GetMyDataWithUDF()
    Dim oApp As Access.Application
    Dim qd As QueryDef

    sFileName = "C:\Users\AUser\Desktop\adatabase.mdb"
    Set oApp = New Access.Application
    oApp.OpenCurrentDatabase (sFileName)

    Set qd = oApp.CurrentDb.QueryDefs("Query1")

    If oApp.DCount("*", "MSysObjects", "Name='dataTableResults'") > 0 Then _
        oApp.CurrentDb.TableDefs.Delete "dataTableResults"

    qd.Parameters("avalue") = "4"
    qd.Execute

    oApp.Quit
    Set oApp = Nothing

    Dim oRS As ADODB.Recordset
    sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sFileName & ";User Id=admin;Password=;"
    Set oRS = New ADODB.Recordset
    oRS.Open "SELECT * FROM dataTableResults", sConn
    Sheet1.Cells.Clear
    Sheet1.Range("A1").CopyFromRecordset oRS
    oRS.Close
    Set oRS = Nothing
End Sub

Note that I made my underlying query a SELECT ... INTO query that creates a table called 'dataTableResults'

This is my query (QueryDef) in Access:

SELECT dataTable.Field1, dataTable.Field2 INTO dataTableResults
FROM dataTable
WHERE mysqr(dataTable.Field1)=[avalue];

My MS-Access DB has a function called "mysqr", which gets used in the SQL above.

Function mysqr(Num)
        mysqr = Num * Num
    End Function

The table "dataTable" I'm querying against is just a list of numbers, so if my parameter "avalue" is "16", then I get the row "4" back. If I enter "4" (as in my code), I get "2" back.


问:
pop method LinkedList Class
I have implemented the LinkedList class: I need to implement the pop() which takes no parameter. The method removes and returns the item at the end of the linked list. If the list is empty it returns None and does nothing.

```<code>class LinkedList:
        def __init__(self):
            self.head = None
            self.count = 0

        def is_empty(self):
            return self.count == 0

        def size(self):
            return self.count

        def add(self, item):
            new_node = Node(item)
            new_node.set_next(self.head)
            self.head = new_node
            self.count += 1

        def search(self, item):
            current = self.head
            while current != None:
                if current.get_data() == item:
                    return True
                else:
                    current = current.get_next()
            return False

        def remove(self, item):
            found = False
            current = self.head
            previous = None
            while current != None and not found:
                if current.get_data() == item:
                    found = True
                else:
                    previous = current
                    current = current.get_next()
            if found:
                if previous == None:
                    self.head = current.get_next()
                else:
                    previous.set_next(current.get_next())
                self.count -= 1
            else:
                raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")

        def clear(self):
            self.head = None
            self.count = 0

        def __str__(self):
            temp = self.head
            if(temp != None):
                output ="Head"
                while (temp != None):
                    output = output+" --> "+str(temp.data)
                    temp = temp.next
                return output
            else:
                return "Head --> None"

        def append(self, item):
            new_node = Node(item)

            if self.head is None:
                self.head = new_node
                return
            last = self.head
            while(last.next):
                last = last.next

            last.next = new_node

        def pop(self):   #Problem here
            if self.head is None:
                return None
            else:
                popnode = self.head
                self.head = self.head.next
                popnode.next = None
                return popnode.data
</code>```

Test:

```<code>a_list = LinkedList()
a_list.add(1)
a_list.add(2)
a_list.add(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)
</code>```

Expected Output:

```<code>Head --> 3 --> 2 --> 1
Removed item: 1
Removed item: 2
Head --> 3
</code>```

Recd Output:

```<code>Head --> 3 --> 2 --> 1
Removed item: 3
Removed item: 2
Head --> 1
</code>```

Test:

```<code>a_list = LinkedList()
a_list.append(1)
a_list.append(2)
a_list.append(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)
</code>```

Expected output:

```<code>Head --> 1 --> 2 --> 3
Removed item: 3
Removed item: 2
Head --> 1
</code>```

Recd output:

```<code>Head --> 1 --> 2 --> 3
Removed item: 1
Removed item: 2
Head --> 3
</code>```

答:
Here's a simplified pop() method which does what you require -

```<code>def pop(self):   #Problem here
    # Empty LinkedList
    if self.head is None:
        return None

    # There is a single node in the LinkedList = head, read data and delete it
    if self.head.next is None:
        data = self.head.data
        self.head = None
        return data

    # there are 2 or more nodes in the LinkedList
    secondlast = self.head
    while (secondlast.next.next):
        secondlast = secondlast.next
    # found the second last node
    # read the data of the last node and then delete it, by setting secondlast.next = None
    data = secondlast.next.data
    secondlast.next = None
    return data
</code>```

another approach using a temporary dummy node to simplify case when there is a single node in the LinkedList-

```<code>def pop(self):   #Problem here
    # Empty linkedlist
    if self.head is None:
        return None
    # create a dummy secondlast node
    secondlast = Node(-1)
    secondlast.next = self.head
    while (secondlast.next.next):
        secondlast = secondlast.next
    data = secondlast.next.data
    secondlast.next = None
    return data
</code>```

In your LinkedList, both append() and pop() methods are O(n), since you need to traverse through whole LinkedList to do those operations. Consider adding a new property self.tail(or self.secondlast) to the LinkedList which keeps track of the last node in the LinkedList. It would help in simplifying the code and making both append() and pop() operations O(1)

Title: pop method LinkedList Class

Body:
I have implemented the LinkedList class: I need to implement the pop() which takes no parameter. The method removes and returns the item at the end of the linked list. If the list is empty it returns None and does nothing.

class LinkedList:
        def __init__(self):
            self.head = None
            self.count = 0

        def is_empty(self):
            return self.count == 0

        def size(self):
            return self.count

        def add(self, item):
            new_node = Node(item)
            new_node.set_next(self.head)
            self.head = new_node
            self.count += 1

        def search(self, item):
            current = self.head
            while current != None:
                if current.get_data() == item:
                    return True
                else:
                    current = current.get_next()
            return False

        def remove(self, item):
            found = False
            current = self.head
            previous = None
            while current != None and not found:
                if current.get_data() == item:
                    found = True
                else:
                    previous = current
                    current = current.get_next()
            if found:
                if previous == None:
                    self.head = current.get_next()
                else:
                    previous.set_next(current.get_next())
                self.count -= 1
            else:
                raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")

        def clear(self):
            self.head = None
            self.count = 0

        def __str__(self):
            temp = self.head
            if(temp != None):
                output ="Head"
                while (temp != None):
                    output = output+" --> "+str(temp.data)
                    temp = temp.next
                return output
            else:
                return "Head --> None"

        def append(self, item):
            new_node = Node(item)

            if self.head is None:
                self.head = new_node
                return
            last = self.head
            while(last.next):
                last = last.next

            last.next = new_node

        def pop(self):   #Problem here
            if self.head is None:
                return None
            else:
                popnode = self.head
                self.head = self.head.next
                popnode.next = None
                return popnode.data

Test:

a_list = LinkedList()
a_list.add(1)
a_list.add(2)
a_list.add(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)

Expected Output:

Head --> 3 --> 2 --> 1
Removed item: 1
Removed item: 2
Head --> 3

Recd Output:

Head --> 3 --> 2 --> 1
Removed item: 3
Removed item: 2
Head --> 1

Test:

a_list = LinkedList()
a_list.append(1)
a_list.append(2)
a_list.append(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)

Expected output:

Head --> 1 --> 2 --> 3
Removed item: 3
Removed item: 2
Head --> 1

Recd output:

Head --> 1 --> 2 --> 3
Removed item: 1
Removed item: 2
Head --> 3

Body:
Here's a simplified pop() method which does what you require -

def pop(self):   #Problem here
    # Empty LinkedList
    if self.head is None:
        return None

    # There is a single node in the LinkedList = head, read data and delete it
    if self.head.next is None:
        data = self.head.data
        self.head = None
        return data

    # there are 2 or more nodes in the LinkedList
    secondlast = self.head
    while (secondlast.next.next):
        secondlast = secondlast.next
    # found the second last node
    # read the data of the last node and then delete it, by setting secondlast.next = None
    data = secondlast.next.data
    secondlast.next = None
    return data

another approach using a temporary dummy node to simplify case when there is a single node in the LinkedList-

def pop(self):   #Problem here
    # Empty linkedlist
    if self.head is None:
        return None
    # create a dummy secondlast node
    secondlast = Node(-1)
    secondlast.next = self.head
    while (secondlast.next.next):
        secondlast = secondlast.next
    data = secondlast.next.data
    secondlast.next = None
    return data

In your LinkedList, both append() and pop() methods are O(n), since you need to traverse through whole LinkedList to do those operations. Consider adding a new property self.tail(or self.secondlast) to the LinkedList which keeps track of the last node in the LinkedList. It would help in simplifying the code and making both append() and pop() operations O(1)


问:
command not found: ganache-cli
I have installed and reinstalled npm to try to run ganache and it has not been successful..really need help here!

(base) user bin % npm install -g ganache-cli

changed 6 packages, and audited 102 packages in 4s

2 packages are looking for funding
run npm fund for details

8 vulnerabilities (7 moderate, 1 high)

To address issues that do not require attention, run:
npm audit fix

To address all issues (including breaking changes), run:
npm audit fix --force

Run npm audit for details.
(base) user bin % ganache-cli
zsh: command not found: ganache-cli

答:
if you are on linux(my case ubuntu) and you encoutered this issue. you should try

```<code>    $sudo npm install -g ganache
</code>```

OR

```<code>    $sudo yarn global add ganache
</code>```

This is probably because you used sudo privileges to install npm and yarn in first place.
happy hacking :)

Title: command not found: ganache-cli

Body:
if you are on linux(my case ubuntu) and you encoutered this issue. you should try

    $sudo npm install -g ganache

OR

    $sudo yarn global add ganache

This is probably because you used sudo privileges to install npm and yarn in first place.
happy hacking :)


问:
Woocommerce Api callback don't running and return -1 value
I am creating a payment plugin for woocommerce and I must receive a response from the payment gateway as a callback. When I test the callback url, I receive -1 as value with 200 as status code.

  add_action( 'woocommerce_api_'.$this->id, array($this,'ocCallback') );

```<code>public function ocCallback(){
            echo'ok';
}
</code>```

答:
To get your own output, place die() before end in your function, this works for me.
And header() in first line, like the sample in this question

How to trigger woocommerce callback function?

Note comment #2 after the accepted answer.

-1 is returned either when called URL is wrong, but with HTTP/400 code instead of HTTP/200.

Body:
I am creating a payment plugin for woocommerce and I must receive a response from the payment gateway as a callback. When I test the callback url, I receive -1 as value with 200 as status code.

  add_action( 'woocommerce_api_'.$this->id, array($this,'ocCallback') );

public function ocCallback(){
            echo'ok';
}


问:
print outnum to the standard output stream sample input 5,10,6,8 sample output 4
Consider an array of non-zero positive integers inarr. Identify and print a number outnum based on the below logic:

· Across each of the possible ways in which integers in inarr can be sequentially arranged, identify the maximum absolute difference of adjacent values

o The last and the first integers are adjacent

· Print outnum, the minimum value across the maximum differences identified above

Input:

The first line represents the array inarr with its elements separated by ‘,’(comma)

Read the inputs from the standard input stream

Output:

Print outnum to the standard output stream

Sample Input    Sample Output   Explanation

5,10,6,8    4

For the given inarr, the maximum absolute difference of adjacent values for all the possible ways in which integers can be arranged is as below:

5,10,6,8:

5 - 10 =5  àabsolute maximum difference

10 - 6 = 4

6 - 8 =2

8 - 5 =3

Similarly, for other possible ways:

5,10,8,6 - absolute max diff = 5

5,6,8,10 - absolute max diff = 5

5,6,10,8 - absolute max diff = 4

5,8,6,10 - absolute max diff = 5

5,8,10,6 - absolute max diff = 4

10,5,6,8 - absolute max diff = 5

10,5,8,6 - absolute max diff = 5

10,6,5,8 - absolute max diff = 4

10,6,8,5 - absolute max diff = 5

10,8,6,5 - absolute max diff = 5

10,8,5,6 - absolute max diff = 4

6,5,10,8 - absolute max diff = 5

6,5,8,10 - absolute max diff = 4

6,8,5,10 - absolute max diff = 5

6,8,10,5 - absolute max diff = 5

6,10,5,8 - absolute max diff = 5

6,10,8,5 - absolute max diff = 4

8,5,6,10 - absolute max diff = 4

8,5,10,6 - absolute max diff = 5

8,6,5,10 - absolute max diff = 5

8,6,10,5 - absolute max diff = 5

8,10,5,6 - absolute max diff = 5

8,10,6,5 - absolute max diff = 4

The minimum value across the maximum differences is 4

答:
```<code>int main()
{
    vector<int> vect = {5, 10, 6, 8};
    sort(vect.begin(), vect.end());

    int n = vect.size();
    int mid = n / 2;
    reverse(vect.begin() + mid, vect.end());

    for (int i = 0; i < n; i++)
        cout << vect[i] << " ";

    cout << endl;
    int maxx = INT_MIN;

    for (int i = 1; i < vect.size(); i++)
    {
        maxx = max(maxx, abs(vect[i] - vect[i - 1]));
    }

    cout << maxx << endl;
    return 0;
}
</code>```


问:
python, How to find specific key value in json file then save whole line of json file？
I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn't find the code I need, hope this helps me

my json file

```<code>
{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

</code>```

Need to export whole line json file where 'sex' is 'male' in JSON file

```<code>{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

</code>```

full code required

答:
Use:

```<code>import json
s = json.dumps([{'person':{'name':'Silva','sex':'female','age':21}},
{'person':{'name':'LANA','sex':'male','age':28}},
{'person':{'name':'Oliveira','sex':'female','age':35}},
{'person':{'name':'KENN','sex':'male','age':26}}])
</code>```

If you have a json file, so:

```<code>s = 'file_path'

s = pd.read_json(s)
s = s['person'].apply(pd.Series)
s[s['sex']=='male']
</code>```

Here, I convert the json to df then convert each row to separate columns and then filter the df.

Body:
I am a newbie and I need to export specific key value in json file,I searched a lot of sites but couldn't find the code I need, hope this helps me

my json file

{"person":{"name":"Silva","sex":"female","age":21}}
{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"Oliveira","sex":"female","age":35}}
{"person":{"name":"KENN","sex":"male","age":26}}

Need to export whole line json file where 'sex' is 'male' in JSON file

{"person":{"name":"LANA","sex":"male","age":28}}
{"person":{"name":"KENN","sex":"male","age":26}}

full code required

Body:
Use:

import json
s = json.dumps([{'person':{'name':'Silva','sex':'female','age':21}},
{'person':{'name':'LANA','sex':'male','age':28}},
{'person':{'name':'Oliveira','sex':'female','age':35}},
{'person':{'name':'KENN','sex':'male','age':26}}])

If you have a json file, so:

s = 'file_path'

s = pd.read_json(s)
s = s['person'].apply(pd.Series)
s[s['sex']=='male']

Here, I convert the json to df then convert each row to separate columns and then filter the df.


问:
communication between parent and child through pipe
I want a program where the parent and child talk each other.
so the output would be:

p: value

c: value

p: word

c: word

and so on.....

Below there is an example of code where the output makes first talk the parent and after the childs.
How can I correct the code?

```<code>    for(int i=0; i<N; i++){
            pid=fork();
            if(pid==-1){
                    perror("fork\n");
                    exit(EXIT_FAILURE);
            }
            else if(pid==0){
                    srand(time(NULL));
                    int c;
                    read(fd[i][0], &c, 1);
                    printf("c: value: %d\n", c);
                    char word[c];
                    read(fd[i][0],&word, sizeof(word));
                    printf("c: word: %s\n", word);
                    int sum;
                    sum=c*i;
                    write(fd[i][1], &sum, sizeof(int));
                    printf("c: sended %d\n", sum);
                    int flag=0;
                    printf("flag :%d\n", flag);
                    read(fd[i][0], &flag, sizeof(int));
                    printf("c: flag= %d ->exit\n", flag);
                    exit(1);
            }else{
                    int c;
                    c=rand()%100+1;
                    write(fd[i][1], &c, sizeof(int));
                    printf("p: value: %d\n", c);
                    char word[c];
                    write(fd[i][1], &word, sizeof(word));
                    printf("p: word: %s\n", word);
                    int sum;
                    read(fd[i][0], &sum, sizeof(int));
                    printf("p: sum is: %d\n", sum);
                    int flag=1;
                    write(fd[i][1], &flag, sizeof(int));
                    printf("par: flag exit %d\n", flag);
                    wait(NULL);
            }
    }
</code>```

答:
To have duplex communication between two processes, you need two pipes:

One for parent to child communication;

And one for child to parent communication

If you use the same pipe for both, then you can end up with a situation like the child writing something to the pipe, and directly read it back again (and the parent will never see the data).

This could for example happen with e.g.

```<code>write(fd[i][1], &sum, sizeof(int));
// ...
// Could read sum that was written just above in the same process
read(fd[i][0], &flag, sizeof(int));
</code>```

in your child process.

For the example of the write and read calls shown above, you could have something like:

```<code>int parent_to_child[2];  // Pipe where parent process write and child reads
int child_to_parent[2];  // Pipe where parent process reads and child writes

pipe(parent_to_child);
pipe(child_to_parent);

// ...

pid = fork();
if (pid == 0)
{
    // Other code...

    // Child writes to parent
    write(child_to_parent[1], &sum, sizeof(int));

    // Child reads from parent
    read(parent_to_child[0], &flag, sizeof(int));

    // ...
}
else
{
    // Other code...

    // Parent reads from child
    read(child_to_parent[0], &sum, sizeof(int));

    // Parent writes to child
    write(parent_to_child[1], &flag, sizeof(int));

    // ...
}
</code>```

Body:
I want a program where the parent and child talk each other.
so the output would be:

p: value

c: value

p: word

c: word

and so on.....

Below there is an example of code where the output makes first talk the parent and after the childs.
How can I correct the code?

    for(int i=0; i<N; i++){
            pid=fork();
            if(pid==-1){
                    perror("fork\n");
                    exit(EXIT_FAILURE);
            }
            else if(pid==0){
                    srand(time(NULL));
                    int c;
                    read(fd[i][0], &c, 1);
                    printf("c: value: %d\n", c);
                    char word[c];
                    read(fd[i][0],&word, sizeof(word));
                    printf("c: word: %s\n", word);
                    int sum;
                    sum=c*i;
                    write(fd[i][1], &sum, sizeof(int));
                    printf("c: sended %d\n", sum);
                    int flag=0;
                    printf("flag :%d\n", flag);
                    read(fd[i][0], &flag, sizeof(int));
                    printf("c: flag= %d ->exit\n", flag);
                    exit(1);
            }else{
                    int c;
                    c=rand()%100+1;
                    write(fd[i][1], &c, sizeof(int));
                    printf("p: value: %d\n", c);
                    char word[c];
                    write(fd[i][1], &word, sizeof(word));
                    printf("p: word: %s\n", word);
                    int sum;
                    read(fd[i][0], &sum, sizeof(int));
                    printf("p: sum is: %d\n", sum);
                    int flag=1;
                    write(fd[i][1], &flag, sizeof(int));
                    printf("par: flag exit %d\n", flag);
                    wait(NULL);
            }
    }

Body:
To have duplex communication between two processes, you need two pipes:

One for parent to child communication;

And one for child to parent communication

If you use the same pipe for both, then you can end up with a situation like the child writing something to the pipe, and directly read it back again (and the parent will never see the data).

This could for example happen with e.g.

write(fd[i][1], &sum, sizeof(int));
// ...
// Could read sum that was written just above in the same process
read(fd[i][0], &flag, sizeof(int));

in your child process.

For the example of the write and read calls shown above, you could have something like:

int parent_to_child[2];  // Pipe where parent process write and child reads
int child_to_parent[2];  // Pipe where parent process reads and child writes

pipe(parent_to_child);
pipe(child_to_parent);

// ...

pid = fork();
if (pid == 0)
{
    // Other code...

    // Child writes to parent
    write(child_to_parent[1], &sum, sizeof(int));

    // Child reads from parent
    read(parent_to_child[0], &flag, sizeof(int));

    // ...
}
else
{
    // Other code...

    // Parent reads from child
    read(child_to_parent[0], &sum, sizeof(int));

    // Parent writes to child
    write(parent_to_child[1], &flag, sizeof(int));

    // ...
}


问:
How to get winform fullpath?
I have a winform and its fullpath is C:\test.exe

How do I get the winform fullpath at run time? For example, the user may move the winform to other places. Thanks.

答:
This would give you the file name:
    System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name

For folder name, try:
    System.Reflection.Assembly.GetExecutingAssembly().Location (not sure... on top of my head)

Title: How to get winform fullpath?


问:
Keeping full commit history local, remote merge to have a single commit
I would like to keep the whole development history of the branch locally ( multiple commits)

But, for the remote merged branch to have a single commit only.
I was thinking of duplicating the branch, squashing it and then pushing it with --force to the remote development branch, and then merging. is there a faster way?

答:
You can :

locally: store your current branch with another name, e.g : history/development

locally: create a new development branch with one single commit containing your current code

locally: run git replace development history/development

on the remote: run push -force-with-lease development to replace the remote development branch with the 1 commit version

(if you want everyone to have access to the old development branch)

on the remote: push history/development, as a branch (everyone will fetch it automatically), or as a ref which is neither a branch nor a tag :

git push origin history/development:refs/history/development

users will be able to view this ref by running git ls-remote and fetch it explicitly

The git replace command will make all local calls to git log, git merge or git rebase work as though you had one single history branch, while having a branch which stops at that initial commit -- for example : pushing and fetching will "stop" at that initial commit.


问:
Window based averages based on ranges within another table
I have a table that has positions like so:

```<code>create or replace table data (
  pos int not null,
  val float not null,
  constraint data_pk primary key (pos)
);
</code>```

And, a ranges type table like so:

```<code>create or replace table ranges (
  label varchar(32) not null,
  left int not null,
  right int not null,
  constraint ranges_pk primary key (label)
);
</code>```

with ranges like

```<code>        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)
</code>```

for each label, I need to lookup every possible 3 subrange within the "data" table, take these 3 subrange averages, and then average them...

I couldn't think of a good way to describe what I'm after, so I thought I'd show what I'd expect for 'charlie':

The results for charlie in the select should be:

```<code>    ('charlie', 40.111), -- avg(avg(data[pos=11], data[pos=12], data[pos=13]), avg(data[pos=12], data[pos=13], data[pos=14]), avg(data[pos=13], data[pos=14], data[pos=15]))
                         -- -> avg(avg(31, 37, 41), avg(37, 41, 43), avg(41, 43, 47))
                         -- -> avg(36.333, 40.333, 43.667) -> 40.111
</code>```

(for data like)

```<code>insert into data (pos, val) values
    (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
    (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
    (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
    (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
    (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
    (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
    (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251);
</code>```

Is there a way to do this within Snowflake SQL? Or must I resort to python to do this? If it helps I made a gist with more data..

Thanks!

答:
Is there a way to do this within Snowflake SQL? Or must I resort to python to do this?

SQL language is expressive enough to handle such case.

Key point here is to use windowed average with windows size of 3 and then average moving averages:

```<code>WITH cte AS (
 SELECT r.label, r.left, r.right, d.val,
        AVG(d.val) OVER(PARTITION BY r.label ORDER BY d.pos ROWS
                        BETWEEN 2 PRECEDING AND CURRENT ROW) AS r
 FROM ranges r
 JOIN data d
   ON d.pos BETWEEN r.left AND r.right
  QUALIFY ROW_NUMBER() OVER(PARTITION BY r.label ORDER BY d.pos) > 2
)
SELECT label, AVG(r) AS output
FROM cte
GROUP BY label
ORDER BY label;
</code>```

Output:

Intermediate step to ilustrate:

```<code>WITH cte AS (
 SELECT r.label, r.left, r.right, d.val,
        AVG(d.val) OVER(PARTITION BY r.label ORDER BY d.pos
                        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS r
 FROM ranges r
 JOIN data d
   ON d.pos BETWEEN r.left AND r.right
  QUALIFY ROW_NUMBER() OVER(PARTITION BY r.label ORDER BY d.pos) > 2
)
SELECT *
FROM cte
ORDER BY label, r;
</code>```

Output:

Body:
I have a table that has positions like so:

create or replace table data (
  pos int not null,
  val float not null,
  constraint data_pk primary key (pos)
);

And, a ranges type table like so:

create or replace table ranges (
  label varchar(32) not null,
  left int not null,
  right int not null,
  constraint ranges_pk primary key (label)
);

with ranges like

        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)

for each label, I need to lookup every possible 3 subrange within the "data" table, take these 3 subrange averages, and then average them...

I couldn't think of a good way to describe what I'm after, so I thought I'd show what I'd expect for 'charlie':

The results for charlie in the select should be:

    ('charlie', 40.111), -- avg(avg(data[pos=11], data[pos=12], data[pos=13]), avg(data[pos=12], data[pos=13], data[pos=14]), avg(data[pos=13], data[pos=14], data[pos=15]))
                         -- -> avg(avg(31, 37, 41), avg(37, 41, 43), avg(41, 43, 47))
                         -- -> avg(36.333, 40.333, 43.667) -> 40.111

(for data like)

insert into data (pos, val) values
    (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
    (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
    (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
    (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
    (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
    (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
    (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251);

Is there a way to do this within Snowflake SQL? Or must I resort to python to do this? If it helps I made a gist with more data..

Thanks!

Body:
Is there a way to do this within Snowflake SQL? Or must I resort to python to do this?

SQL language is expressive enough to handle such case.

Key point here is to use windowed average with windows size of 3 and then average moving averages:

WITH cte AS (
 SELECT r.label, r.left, r.right, d.val,
        AVG(d.val) OVER(PARTITION BY r.label ORDER BY d.pos ROWS
                        BETWEEN 2 PRECEDING AND CURRENT ROW) AS r
 FROM ranges r
 JOIN data d
   ON d.pos BETWEEN r.left AND r.right
  QUALIFY ROW_NUMBER() OVER(PARTITION BY r.label ORDER BY d.pos) > 2
)
SELECT label, AVG(r) AS output
FROM cte
GROUP BY label
ORDER BY label;

Output:

Intermediate step to ilustrate:

WITH cte AS (
 SELECT r.label, r.left, r.right, d.val,
        AVG(d.val) OVER(PARTITION BY r.label ORDER BY d.pos
                        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS r
 FROM ranges r
 JOIN data d
   ON d.pos BETWEEN r.left AND r.right
  QUALIFY ROW_NUMBER() OVER(PARTITION BY r.label ORDER BY d.pos) > 2
)
SELECT *
FROM cte
ORDER BY label, r;

Output:


问:
Is an end-2-end javascript stack secure?
I want to build a multi tenent cloud app. My stack is javascript / json end-2-end: The user inputs data in the browser which jquery turns to json, sends to my node.js server, which in turn stores it as json in couchdb. When fetching data json goes the other way around. If the user injects something to this json is there anywhere in the above stack this json is actually evaludated? If yes I need to sanitize it. How robust is json sanitization? Or will a sandbox help? how robust is it?

This is a multi tenent environment and a lot of secret data of users and companies will be there.

答:
Look on Caja or Node-validator

Caja is implementation of Google Caja sanitizer

Node-validator is a node validator/sanitizer, here express node-validator wrapper

Good luck


问:
How to destructure an Array from an Object in Redux React?
I am using redux and I want to destructure teamMembers - Array from an Object name - teamData which I am getting from REDUX. This is what I have done below. I just want to confirm whether is this the right way to do.

```<code>  const teamData = useSelector((state) => state.team.teamData);
  const { description, heading } = teamData;
  const teamMembers = useSelector((state) => state.team.teamData.teamMembers);
</code>```

答:
If possible, you should not do

  const teamData = useSelector((state) => state.team.teamData);
  const { description, heading } = teamData;
```
<p>Your code here is interested in <code>description</code> and <code>heading</code>, but your <code>useSelector</code> selects the whole <code>teamData</code>.
Now, if there is a third property on <code>teamData</code>, let's say <code>winStreak</code> and that <code>winStreak</code> changes, your component will rerender. Because that change to <code>winData.teamStreak</code> caused <code>winData</code> to change. And your <code>useSelector</code> is watching <code>winData</code> for changes.</p>
<p>If you instead do</p>
<pre class="lang-js prettyprint-override"><code>const description = useSelector((state) => state.team.teamData.description);
const heading = useSelector((state) => state.team.teamData.heading );
</code>```

your component will only rerender, when description or heading change. Because your useSelector now watches those two properties for changes. It does not care if teamData changes, it only cares if teamData.descriptionorteamData.heading` change.

So, in your case you should do

const description = useSelector((state) => state.team.teamData.description);
const heading = useSelector((state) => state.team.teamData.heading );
const teamMembers = useSelector((state) => state.team.teamData.teamMembers );
```

and not use any destructuring here.
If you have to destructure the result of a useSelector call, that likely means that your useSelector call is also observing data you are not interested in in the first place.

Body:
I am using redux and I want to destructure teamMembers - Array from an Object name - teamData which I am getting from REDUX. This is what I have done below. I just want to confirm whether is this the right way to do.

  const teamData = useSelector((state) => state.team.teamData);
  const { description, heading } = teamData;
  const teamMembers = useSelector((state) => state.team.teamData.teamMembers);

Body:
If possible, you should not do

  const teamData = useSelector((state) => state.team.teamData);
  const { description, heading } = teamData;

Your code here is interested in description and heading, but your useSelector selects the whole teamData.
Now, if there is a third property on teamData, let's say winStreak and that winStreak changes, your component will rerender. Because that change to winData.teamStreak caused winData to change. And your useSelector is watching winData for changes.

If you instead do

const description = useSelector((state) => state.team.teamData.description);
const heading = useSelector((state) => state.team.teamData.heading );

your component will only rerender, when description or heading change. Because your useSelector now watches those two properties for changes. It does not care if teamData changes, it only cares if teamData.descriptionorteamData.heading` change.

So, in your case you should do

const description = useSelector((state) => state.team.teamData.description);
const heading = useSelector((state) => state.team.teamData.heading );
const teamMembers = useSelector((state) => state.team.teamData.teamMembers );

and not use any destructuring here.
If you have to destructure the result of a useSelector call, that likely means that your useSelector call is also observing data you are not interested in in the first place.