text:
Q: Add columns for CSV output I have this PowerShell query listed below and I require the headers to be machine, path, filewalkmethod
$fs = Get-FileServer
foreach ($s in $fs) {
    foreach ($share in $s.Volumes) {
        ($s.Servername, $share.Share, $share.FileWalkMethod) -join "," |
            Out-File -Append D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv
    }
}

Sample output:

nas01e,E$,Windows

Updated Query I'm using:
Import-Module -Name VaronisManagement
Connect-Idu
$fs = Get-FileServer
      foreach($s in $fs){
         $s.Volumes | Select-Object @{n='ServerName'; e={$s.ServerName}}, Share, FileWalkMethod |
         Export-CSV D:\data\splunk\otl_varonis\otl_varonis_monitoring_test.csv
            -NoTypeInformation -NoClobber }

A: Untested but this should work:
foreach($s in $fs){
    $s.Volumes | Select-Object @{n='Machine'; e={$s.ServerName}}, Share, FileWalkMethod | Export-CSV D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv -NoTypeInformation -Append
}

Note that the parameter -Append for Export-Csv was introduced with PowerShell v3. To make this compatible with earlier versions you could pipeline the loop:
$fs | ForEach-Object {
    $machine = $_.ServerName
    $_.Volumes | Select-Object @{n='Machine';e={$machine}}, Share, FileWalkMethod
} | Export-Csv D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv -NoType


text:
Q: Integrity constraint violation: 1052 Column and in where clause is ambiguous I have two table the Tbl_payroll_leave_employeev2 and tbl_payroll_leave_schedulev2 and i want to join them but im getting an error like this

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'payroll_leave_employee_id' in where clause is ambiguous (SQL: select payroll_employee_id from tbl_payroll_leave_employee_v2 inner join tbl_payroll_leave_schedulev2 on tbl_payroll_leave_employee_v2.payroll_leave_employee_id = tbl_payroll_leave_schedulev2.payroll_leave_employee_id where payroll_leave_employee_id = 5) ◀

My table structure

$employee_id = Tbl_payroll_leave_employeev2::select('payroll_employee_id')
   ->join('tbl_payroll_leave_schedulev2','tbl_payroll_leave_employee_v2.payroll_leave_employee_id','=','tbl_payroll_leave_schedulev2.payroll_leave_employee_id')
   ->where('payroll_leave_employee_id',$emp)
   ->get();

A: In where condition,  you must define the field payroll_leave_employee_id of table tbl_payroll_leave_employee_v2  or table tbl_payroll_leave_schedulev2
$employee_id = Tbl_payroll_leave_employeev2::select('payroll_employee_id')
   ->join('tbl_payroll_leave_schedulev2','tbl_payroll_leave_employee_v2.payroll_leave_employee_id','=','tbl_payroll_leave_schedulev2.payroll_leave_employee_id')
   ->where('tbl_payroll_leave_schedulev2.payroll_leave_employee_id',$emp)
   ->get();

redpajama_set_name: RedPajamaStackExchange


text:
Q: File Search API for .NET I have a requirement to provide file search functionality in our application. How can I use windows search from .NET so that I needn't do the normal recursive searching myself.
EDIT:
Since I'm working on Win XP, search should not be based on indexes.

A: You can still use the Windows Search API without using an index as Magnus Johansson says.
What you need to do is to stop the Windows Search service and prevent it from starting (see this link for details on that). With the indexing service disabled, Windows Search will default to a real-time search instead.
And since you are working on XP, don't forget to change the FilterFilesWithUnknownExtensions value to 1 in the registry at
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet\Control\ContentIndex.
KB309173 states that this will let you search all file types in stead of just the registered ones.


text:
Q: Why is my SQL Server Differential backup failing sometimes? I'm having an issue that only happens sometimes where my SQL Server differential backup job fails with an error message similar to
Msg 3035, Sev 16, State 1, Line 1 : Cannot perform a differential backup for database "MyDatabaseName", because a current database backup does not exist. Perform a full database backup by reissuing BACKUP DATABASE, omitting the WITH DIFFERENTIAL option. [SQLSTATE 42000]
Msg 3013, Sev 16, State 1, Line 1 : BACKUP DATABASE is terminating abnormally. [SQLSTATE 42000]

I'm currently using Ola Hallengren's SQL Server Mantenance Solution script for backup's, integrity check's and index maintenance. I've scheduled the backup job's as such:

*

*Full Backup of system databases every day @ 1:30 AM

*Full Backup of all user databases every week on Monday, Wednesday & Friday @ 2:30 AM

*Differential Backup of all user databases every week on Sunday, Tuesday, Thursday & Saturday @ 2:30 AM

*Transaction Log backup or all user databases every 30 minutes

I've also set the cleanup time to 168 hours...which is 7 days.
I know that usually when this error message comes up, it is due to a full backup not being present, or possible the recovery mode on a database being changed. I have checked both of these and neither seems to be the case. I can confirm that my Friday full backup was successful, however my Saturday and Sunday Differentials failed. There have also been no changes to the recovery model, and no manual backup taken through SQL Server.
It's worth noting that this only happens sometimes. Sometimes the differential backups work without a problem and other times they fail.
This server is a VM, and we are using VMWare vSphere/vCenter 6.5. I've talked to my server admin and asked how his backup is running an he told me that we are using Quest AppAssure which leverage VMWare snapshot technology, and that he is backuping the drives every x number of minutes, so it is possible that the time of his backup changes and eventually overlaps with mine.
We looked back at the time that his backups ran on the weekend and they happened within a few minutes before mine started. I'm wondering if this is causing my backup issues? if so is there a way to prevent this, or do we simply need to plan the backups at different times that don't overlap?
Thanks

A: We had another call with Quest today and figured out a solution to the problem.
It would seem that when configuring the backup through Quest Rapid Recovery, you have the option to do Machine level backups or Volume level backup. When it's configured to do volume level backups you can choose for it to either do a block level backup which isn't SQL Server aware, or for it to do a backup that is SQL Server aware, which ends up using the volume shadow copy service and these backups show up as Full (Copy Only) backups in the SQL backup history...even though you can't restore them from SQL Server.
Rapid Recovery can only do backups on a schedule, plus has the option to Truncate Logs after the backup complete to avoid filling the log files, but can't do transaction log backups, so you loose the ability to do a more granular recovery down to the second like with the native SQL Timeline Recovery...Which is why we chose to use native SQL Server Backups.
So to fix the issue, you need to either do a machine level backup which has not SQL Server Awareness/integration. Or you can do a volume level backup, but disable the SQL Server Writer extension, and the truncate logs options to remove the integration.
We've run a bunch of tests, and from the point/time that this change was done, we only see SQL Server backups and no longer the Rapid Recovery backups in the SQL Server Backup history.
So now i am in talks with my server/backup admin see if we can do a machine level backup once a day, so that we can do a machine level restore in case of disaster, and also add a volume level backup of my Backup drive, so that he captures my backups more frequently during the day. I think once this is complete, we'll have the best of both backup solutions.

*

*Ability to do machine level restores (Rapid Recovery)

*Retention of SQL Server Backups (Rapid Recovery)

*Flexible point in time recovery (SQL Server)

A: Just wanted to post a update to this issue
We scheduled a call with Quest yesterday, and they assured me that their backup is only taking volume snapshots and will have no impact on my SQL backups. They said that the reason that i was seeing these errors is likely do to Rapid Recovery(I guess AppAssure was renamed to Rapid Recovery) and my SQL backup jobs both trying to use the volume shadow copy service at the same time and so we simply needed to stagger the backup jobs. I end up finding out that this wasn't completely true because the Rapid Recovery backups were configured to truncate my SQL Logs. I also told the guy from rapid recovery that when i queried the msdb backupset table that i was seeing backup jobs listed that lined up with the times of the rapid recovery backup. Still he assured me that it would have zero impact on my backups.
I was still concerned that the Rapid Recovery backups might be impacting the chain of my backup files, so in our test environment i right clicked on one of our databases and clicked tasks > restore >database just to see the recovery history. I see a database backup listed as type Full (Copy Only) which coincides with the rapid recovery backup, then a number of my transaction log backups.
It would seem to me that Rapid Recovery is definitely impacting my SQL Backups.
One other thing to note that i just tried in out test environment. I did a few tests backups using Full's , Transaction Log, Differentials and Full (Copy Only) just to see how things showed up in the restore window in SQL Server Management Studio.
So i realized that in the default restore screen, it tries to recover to the nearest point in time using the least combination of various backup files. To go past the last full backup, I have to use the Timeline option.

*

*I could see the Full backup as the first item, and then the transaction logs backups.

*Once i do the Differential backup, i see the Full plus the differential, but no more transaction log backups.... which makes sense since it's trying to get the the closest time possible for the recovery.

*Next if i do another Transaction Log backup, I see the Full, Differential and the Transaction Log back

One thing that surprised me however is if i do a Full (Copy Only) followed by a transaction log backup, that i see these two item in the list of files for the recovery, yet if i do a differential after a Full (Copy Only) that it show me the last Full (non copy only), plus the differential. I expected that the backups would always be based off of the last full, both for transaction log and differential backups. I thought that the Copy Only backups would be ignored in the backup chain.
Next I decided to use the timeline restore feature and select a point in time during my tests where the Rapid Recovery backup wasn't part of the listed backups, and do a verify backup. As expected it was successful. After this i tried a restore to another point in time where the Rapid Recovery Full (Copy Only) backup was listed and the verify failed on the Full (Copy Only) backup file from rapid recovery, since it doesn't exist on the sql server.
Any recommendations on how to fix this? The point of the Rapid Recovery backup is supposed to be to backup the machine, in case we ever loose the server and have to restore the entire server, plus for it to pick up my sql server backups to keep for retention, since i only keep 7 days worth of backup on the server itself.

A: You can check the error log file.

*

*Your job may be the victim of deadlock transactions.

*Backup file location may not have enough permission.
So, you should check all the possible error log files.


text:
Q: Show USB speed for all devices in Windows 7 I am using Windows 7 and would like to see which USB versions each attached USB device is using  (1.1 or 2). How can I do this?

A: Disclaimer: Greg mentioned this utility in his answer, but as slm points out, his answer is a very sparse.
NirSoft has a free utility called USBDeview.  This software will display lots of information about all USB devices currently and previously attached to the computer including the USB version:

Like most NirSoft utilities, it's a standalone executable that does not require installation. It also has command line options. It works extremely well and I have found it very useful. IMHO, it's easier to obtain than the MS USB View utility mentioned in the accepted answer. And USBDeview is less "cryptic" then USB View in the information it displays.

A: I thought I would also add a reply because I found this tool which is based on the Microsoft USB View code but it adds a little bit to it:
http://www.uwe-sieber.de/usbtreeview_e.html
Moreover, unlike USB View this tool is freeware and you don't need to download a complete development kit to get it. I recommend.

A: You can determine the USB specification that a device supports by examining its bcdUSB field. It is not stored in the registry, so you cannot just search or access it. It is stored on the device itself, so you need a way to query the device to retrieve it.
You can use the USB View utility from Microsoft. It is available on the installation CD of some versions of Windows (and possibly some old versions of the Resource Kit). I'm not sure if it's legal to distribute it, but it's certainly easy enough to find a copy. You could also use the commercial program USBlyzer.

The bcdUSB field is a hexadecimal number that will indicate the highest USB version the device supports in a packed-decimal format:

0x0100 = USB 1.0
0x0110 = USB 1.1
0x0200 = USB 2.0
0x0300 = USB 3.0

In addition, you can view the actual speed the device supports in the Device Bus Speed field:
Low Speed  : <= 1.5 Mbps (USB 1.0+)
Full Speed : <= 12  Mbps (USB 1.0+)
High Speed : <= 480 Mbps (USB 2.0+)
SuperSpeed : <= 5.0 Gbps (USB 3.0+)

(Check your motherboard's BIOS to determine what mode the USB controller is configured for.)

Figure 1: USB 1.1 device

Figure 2: USB 2.0 device

A: If the device is using USB 1.0, windows will throw a message at you saying that there might be a problem with the device and that it is using a slower technology (in my experience).
Alternatively, you can write files to the drive and see how fast they get written/read. A USB 1.1 drive, while it has a theoretical speed of 12 MBit/S is usually far slower (<2 MBit). You will not see such speeds on a 2.0 drive unless there is something wrong with it or your computer.

A: http://www.nirsoft.net/utils/usb_devices_view.html
USBDeview v2.22 - View all installed/Nir Sofer
Interrogate exiting and past USB devices


text:
Q: Streaming upload with python-requests UnicodeDecodeError I am trying to write simple upload app if i use this
files = {'upfile_0': (open('mplayer.exe', 'rb'))}
fin = r.post(action, files=files)

It work but whole file is in ram.
After i read on requests docs about streaming uploads. I wanted to try...
with open('mplayer.exe') as f:
    requests.post(action, data=f)

But i get this error. Thanks for any help.
Traceback (most recent call last):
File "C:\Users\pulpe\Projekty\ulozto.py", line 23, in <module> requests.post(action, data=f)
File "C:\Python33\lib\site-packages\requests\api.py", line 88, in post return request('post', url, data=data, **kwargs)
File "C:\Python33\lib\site-packages\requests\api.py", line 44, in request return session.request(method=method, url=url, **kwargs)
File "C:\Python33\lib\site-packages\requests\sessions.py", line 335, in request resp = self.send(prep, **send_kwargs)
File "C:\Python33\lib\site-packages\requests\sessions.py", line 438, in send r = adapter.send(request, **kwargs)
File "C:\Python33\lib\site-packages\requests\adapters.py", line 292, in send timeout=timeout
File "C:\Python33\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 428, in urlopen body=body, headers=headers)
File "C:\Python33\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 280, in _make_request conn.request(method, url, **httplib_request_kw)
File "C:\Python33\lib\http\client.py", line 1061, in request self._send_request(method, url, body, headers)
File "C:\Python33\lib\http\client.py", line 1099, in _send_request self.endheaders(body)
File "C:\Python33\lib\http\client.py", line 1057, in endheaders self._send_output(message_body)
File "C:\Python33\lib\http\client.py", line 906, in _send_output self.send(message_body)
File "C:\Python33\lib\http\client.py", line 863, in send datablock = data.read(blocksize)
File "C:\Python33\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined>

If i use 'rb' in open.
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 428, in urlopen body=body, headers=headers)
File "C:\Python33\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 280, in _make_request conn.request(method, url, **httplib_request_kw)
File "C:\Python33\lib\http\client.py", line 1061, in request self._send_request(method, url, body, headers)
File "C:\Python33\lib\http\client.py", line 1099, in _send_request self.endheaders(body)
File "C:\Python33\lib\http\client.py", line 1057, in endheaders self._send_output(message_body)
File "C:\Python33\lib\http\client.py", line 906, in _send_output self.send(message_body)
File "C:\Python33\lib\http\client.py", line 868, in send self.sock.sendall(datablock)
ConnectionResetError: [WinError 10054] Stávající připojení bylo vynuceně ukončeno vzdáleným hostitelem

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python33\lib\site-packages\requests\adapters.py", line 292, in sendtimeout=timeout
File "C:\Python33\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 474, in urlopen raise MaxRetryError(self, url, e)
requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='upload.uloz.to', port=80): Max retries exceeded with url: /upload?user_id=4179756&did=uloz-to&host=www.uloz.to&a=ca92c8242dce5806238751f24114367174cf797d&rk=ocjd5s5ehl&t=1375618794 (Caused by <class 'ConnectionResetError'>: [WinError 10054] Stávající připojení bylo vynuceně ukončeno vzdáleným hostitelem)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\pulpe\Projekty\ulozto.py", line 23, in <module> requests.post(action, data=f)
File "C:\Python33\lib\site-packages\requests\api.py", line 88, in post return request('post', url, data=data, **kwargs)
File "C:\Python33\lib\site-packages\requests\api.py", line 44, in request return session.request(method=method, url=url, **kwargs)
File "C:\Python33\lib\site-packages\requests\sessions.py", line 335, in request resp = self.send(prep, **send_kwargs)
File "C:\Python33\lib\site-packages\requests\sessions.py", line 438, in send r = adapter.send(request, **kwargs)
File "C:\Python33\lib\site-packages\requests\adapters.py", line 327, in send raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='upload.uloz.to', port=80): Max retries exceeded with url: /upload?user_id=4179756&did=uloz-to&host=www.uloz.to&a=ca92c8242dce5806238751f24114367174cf797d&rk=ocjd5s5ehl&t=1375618794 (Caused by <class 'ConnectionResetError'>: [WinError 10054] Stávající připojení bylo vynuceně ukončeno vzdáleným hostitelem)


text:
Q: A property of F-Snedecor distribuction Let $X$ be a random variable with F-Snedecor distribuction with parameters $(n,m)$.
Let $F_{n,m}(\alpha)$, for $\alpha \in (0,1)$, be the element such that $ F_X(F_{n,m}( \alpha )) = 1 - \alpha $.
Show that $ F_{n,m}(\alpha) = \dfrac{1}{F_{m,n}(1-\alpha)}$
My first question is what does $F_{m,n}(1-\alpha)$ mean. Is it the point $y$ such that $F_{1/X}(y) = \alpha$? Because I already proved that $\frac{1}{X}$ has distribuction F-Snedecor with parameters $(m,n)$.
But even if it is that, I don't know how to approach this problem. Am I supposed to compute $F_{X}(F_{n,m}(\alpha))$ and $\dfrac{1}{F_{1/X}(F_{m,n}(1-\alpha))}$ and then compare the results?
Any help would be appreciated.

A: Let $X\sim F(n,m)$.
Then the notation $F_{n,m;\,\alpha}$ is often used to denote the upper $\alpha$ percent point of the $F(n,m)$ distribution. This is what you have here. In other words, this means $P(X>F_{n,m;\,\alpha})=\alpha$.
You know that $X\sim F(n,m)\implies Y=\frac{1}{X}\sim F(m,n)$.
So for any $c>0$, you have $P(X>c)=P\left(\frac{1}{X}<\frac{1}{c}\right)=P\left(Y<\frac{1}{c}\right)$.
This implies that $P(X>F_{n,m;\,\alpha})=P\left(Y<\dfrac{1}{F_{n,m;\,\alpha}}\right)=\alpha\tag{1}$
Moreover, from definition of $\alpha$ you have,
$P(Y<F_{m,n;\,1-\alpha})=\alpha\tag{2}$
From $(1)$ and $(2)$ your result follows.


text:
Q: Inode and deleted file entries This is in reference to the answer here , since I received no response to my question in the comments.

What it really means is that a file entry was created in the
  /dev/ashmem/ directory, then later removed, but that the corresponding
  i-node still exists because there is at least one open file-descriptor
  for it

What does this mean in *nix terms ? AFAIK, Android is of ext4 type. I knew that in some file systems the inode structure retains the data after the file is deleted and in some the contents of the structure are reset. But what does the above statement mean? If the file entry is deleted, how is there at least one open file-descriptor still open ? There's no hard-link or soft-link here.

A: After lot of digging with mmap and file deletions, this answers (no self-promotion) helps me understand the concept.


text:
Q: Firebase List view is not displayed in real-time while adding data I am storing Contact information on Firebase real-time DB after picking a contact from the phone.
When I add the data which is displayed using ListView and DataSnapshot the data is not refreshed in real-time until I restart the Activity. The ListView loads and displays all the data without any problem. How do I resolve this issue?
My screen looks like this:

Code for Screen:
import 'package:epicare/CaregiverClass.dart';
import 'package:epicare/Homepage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:contact_picker/contact_picker.dart';

//Check contacts permission
Future<PermissionStatus> _getPermission() async {
  final PermissionStatus permission = await Permission.contacts.status;
  if (permission != PermissionStatus.granted &&
      permission != PermissionStatus.denied) {
    final Map<Permission, PermissionStatus> permissionStatus =
        await [Permission.contacts].request();
    return permissionStatus[Permission.contacts] ??
        PermissionStatus.undetermined;
  } else {
    return permission;
  }
}

class CaregiverScreen extends StatefulWidget {
  @override
  _CaregiverScreenState createState() => _CaregiverScreenState();
}

class _CaregiverScreenState extends State<CaregiverScreen> {
  //Firebase
  FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  final ref = FirebaseDatabase.instance.reference();
  User cuser = FirebaseAuth.instance.currentUser;
  final fb = FirebaseDatabase.instance.reference().child("User_data");
  List <CaregiverList> list = List();

  // Adding data into Firebase
  void addData(String name, String number) {
    print("Saving data to firebase");
    ref.child('User_data').child(cuser.uid).child("caregivers").push().set({'Caregiver_Name': name, 'Caregiver_Number': number});
  }

  // Get location
  Position _currentPosition;
  String _currentAddress;
  final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
  @override
  void initState() {
    // Firebase
    fb.child(cuser.uid).child("caregivers").once().then((DataSnapshot snapshot)
    {
      var data = snapshot.value;
      list.clear();
      data.forEach((key,value){
        print(value['Caregiver_Name']);
        CaregiverList contact_list = new CaregiverList(
          name: value['Caregiver_Name'],
          phone_number: value['Caregiver_Number'],
          isActive: true,
          key: key,
        );
        list.add(contact_list);
        });
      setState(() {

      });
    }
    );
    super.initState();
  }

  final ContactPicker _contactPicker = new ContactPicker();

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    //Size size = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: const Color(0xffE5E0A1),
        elevation: 0,
        centerTitle: true,
        title: Text(
          "Add Caregiver",
          style: TextStyle(
            fontSize: 15.0,
            color: Colors.black,
            fontFamily: 'Montserrat',
            fontWeight: FontWeight.normal,
          ),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return Homepage();
                },
              ),
            );
          },
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 40),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  MaterialButton(
                    onPressed: () async {
                      final PermissionStatus permissionStatus =
                          await _getPermission();
                      if (permissionStatus == PermissionStatus.granted) {
                        //We can now access our contacts here
                        Contact contact = await _contactPicker.selectContact();
                        print("Contact name: ${contact.fullName}");
                        print("Contact number: ${contact.phoneNumber}");
                        List<String> num =
                            contact.phoneNumber.toString().split('(Work)');
                        print(num);
                        print(num[0]);
                        final pattern = RegExp('\\s+');
                        num[0].replaceAll(pattern, '');
                        num[0].replaceAll(new RegExp('-'),'');
                        addData(contact.fullName.toString(),num[0]);

                      } else {
                        //If permissions have been denied show standard cupertino alert dialog
                        showDialog(
                            context: context,
                            builder: (BuildContext context) =>
                                CupertinoAlertDialog(
                                  title: Text('Permissions error'),
                                  content: Text('Please enable contacts access '
                                      'permission in system settings'),
                                  actions: <Widget>[
                                    CupertinoDialogAction(
                                      child: Text('OK'),
                                      onPressed: () =>
                                          Navigator.of(context).pop(),
                                    )
                                  ],
                                ));
                      }
                    },
                    color: const Color(0xffd4d411),
                    textColor: Colors.white,
                    child: Icon(
                      Icons.add,
                      size: 32,
                    ),
                    padding: EdgeInsets.all(3),
                    shape: CircleBorder(),
                  ),
                  Text(
                    'Add a Caregiver',
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        fontSize: 13,
                        color: const Color(0xff000000),
                        height: 1.5384615384615385,
                        fontWeight: FontWeight.w600),
                    textHeightBehavior:
                        TextHeightBehavior(applyHeightToFirstAscent: false),
                    textAlign: TextAlign.left,
                  )
                ],
              ),
              list.length == 0 ? Center(child: Text("Please add Caregivers"))
              : ListView.separated(
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  primary: false,
                  itemBuilder: (context, index) {
                    return _caregiverWidget(list[index].name,list[index].phone_number,list[index].isActive,list[index].key

                    );
                  },
                  separatorBuilder: (_, __) => Container(),
                  itemCount: list.length),
              // _contact == null ? Container() : CaregiversList(_contact.fullName),
            ],
          ),
        ),
      ),
    );
  }

  Widget _caregiverWidget( String name, String phone_number, bool isActive, String key

  ) {

    print(name);
    var c = name.split(' ');
    print(c[0]);
    var caregiver = c[0];
    var output = getInitials(string: caregiver, limitTo: 1);
    print(output);
    return GestureDetector(
      onLongPress: (){},
      onTap: (){},
      child: Card(
        elevation: 0,
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10, horizontal: 27),
          child: Row(
            //crossAxisAlignment: CrossAxisAlignment.center,
            //mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              CircleAvatar(
                radius: 24,
                backgroundColor: const Color(0xffd4d411),
                child: CircleAvatar(
                  radius: 22,
                  backgroundColor: Colors.white,
                  child: Text(
                    output,
                    style: TextStyle(
                      fontFamily: 'Segoe UI',
                      fontSize: 20,
                      color: const Color(0xff000000),
                    ),
                  ),
                ),
              ),
              SizedBox(width: 19),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    caregiver,
                    style: TextStyle(
                        fontFamily: 'Montserrat',
                        fontSize: 13,
                        color: const Color(0xff000000),
                        height: 1.5384615384615385,
                        fontWeight: FontWeight.w600),
                    textHeightBehavior:
                        TextHeightBehavior(applyHeightToFirstAscent: false),
                    textAlign: TextAlign.left,
                  ),
                  isActive
                      ? Text(
                          "Activated",
                          style: TextStyle(
                              fontFamily: 'Montserrat',
                              fontSize: 10,
                              color: const Color(0x80232425),
                              fontWeight: FontWeight.w500),
                          textAlign: TextAlign.left,
                        )
                      : Text(
                          "Disabled",
                          style: TextStyle(
                              fontFamily: 'Montserrat',
                              fontSize: 10,
                              color: const Color(0x80232425),
                              fontWeight: FontWeight.w500),
                          textAlign: TextAlign.left,
                        ),
                ],
              ),
              SizedBox(width: 143),
              FlutterSwitch(
                width: 40.0,
                height: 20.0,
                value: isActive,
                toggleSize: 15,
                borderRadius: 40.0,
                padding: 2.0,
                showOnOff: false,
                activeColor: const Color(0xffd4d411),
                activeToggleColor: Colors.white,
                inactiveColor: const Color(0xffDDDBAF),
                inactiveToggleColor: Colors.white,
                onToggle: (value) {
                  print(value);
                  setState(() {
                    isActive = value;
                    // _careList.removeAt(index);
                    // _careList.insert(index, _caregiver);
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  String getInitials({String string, int limitTo}) {
    var buffer = StringBuffer();
    var split = string.split(' ');
    for (var i = 0; i < (limitTo ?? split.length); i++) {
      buffer.write(split[i][0]);
    }
    return buffer.toString();
  }
}

A: The issue is that this part:
fb.child(cuser.uid).child("caregivers").once()..

is only getting the value once.
To se realtime updates you should either use a listener like here:
CollectionReference reference = Firestore.instance.collection('caregivers');
reference.snapshots().listen((querySnapshot) {
  querySnapshot.documentChanges.forEach((change) {
    // Do something with change
  });
});

or a StreamBuilder like here:
StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('caregivers').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return new Text('Loading...');
    return new ListView(
      children: snapshot.data.documents.map((DocumentSnapshot document) {
        return new ListTile(
          title: new Text(document['name']),
        );
      }).toList(),
    );
  },
);

for the RTDB the StreamBuilder would look like this:
StreamBuilder(
      stream: _database.reference().child('caregivers').onValue,
      builder: (context, event) {
        if (event.hasData &&
            !event.hasError &&
            event.data.snapshot.value != null) {
          DataSnapshot snapshot = event.data.snapshot;
       }

})

the listener would be like:
_database.reference().child('caregivers').onValue.listen((event){

})

onValue will give you everytime the whole list so you need to empty it before you add again every item:
 var data = event.snapshot.value;
 list= List(); //Clear the list here

 data.forEach((key, value) {
          print(value['Caregiver_Name']);

          CaregiverList contact_list = new CaregiverList(
            name: value['Caregiver_Name'],
            phone_number: value['Caregiver_Number'],
            isActive: true,
            key: key,
          );
          list.add(contact_list);
        });


text:
Q: How to escape hash symbol(#) in netsh command Our company main Wifi ssid is called "#TestRIG". I need to switch SSIDs during the automation test frequently.
I tried the command as below.
netsh wlan connect name="#TestRIG"
netsh wlan connect name=^#TestRIG
netsh wlan connect name=\#TestRIG

None of them worked.

C:\Users\admin>netsh wlan connect name=^#TestRIG
There is no profile "" assigned to the specified interface.

C:\Users\admin>netsh wlan connect name="#TestRIG"
There is no profile "" assigned to the specified interface.

Can anyone help to get the command to escape hash symbol?

A: Not an elegant solution, but you could utilize the built-in "exec" command in netsh referring to a file. Example in PowerShell:
@"
wlan connect name="#TestRIG"
"@ | out-file c:\temp\netsh.txt -encoding ascii

netsh exec c:\temp\netsh.txt

A: I had a similar issue this week and I couldn't find any reference about which escape character to use. I solved using wildcards. It is possible to use '*' or '?' wildcards:
e.g:
netsh wlan connect name="*#TestRIG"
netsh wlan connect name="?TestRIG"


text:
Q: Count occurance of specific words in a text file in vb.net I'm trying to count the number of an item in a text file, by counting each instance the item was entered into the file earlier on in the program.
I already have the text read from the file and in a text box. The problem is that my current code was just counting the characters in the textbox and not the number of times my desired word was in the file.
For Each desiredword As String In txtContentofFile.Text
        intdesiredword = intdesiredword + 1
        txtdesiredwordcount.Text = intdesiredword
Next

This counts the characters in the textbox instead of counting the number of desired words. I tried repeatedly before asking help and searched extensively, but I just don't understand what's wrong with my code. Please help :)

A: You can use Split Function :
C#:
int count = txtContentofFile.Text.Split(desiredword).Length - 1;

VB.net:
Dim count As Integer = txtContentofFile.Text.Split(desiredword).Length - 1

A: I prefer to use Regular Expressions in this type of situation.  They are very tricky to understand but they are extremely powerful and typically faster than other string manipulation techniques.
Dim AllMatchResults As MatchCollection
Try
    Dim RegexObj As New Regex(desiredword)
    AllMatchResults = RegexObj.Matches(txtContentofFile.Text)
    If AllMatchResults.Count > 0 Then
        ' Access individual matches using AllMatchResults.Item[]
    Else
        ' Match attempt failed
    End If
Catch ex As ArgumentException
    'Syntax error in the regular expression
End Try

In your case you are looking for the value from AllMatchResults.Count.
Using a great Regular Expression tool like RegexBuddy to build and test the expressions is a great help too. (The above code snippet was generated by RegexBuddy!)

A: Try this:
Dim text As String = IO.File.ReadAllText("C:\file.txt")
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))

'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))

findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)

Function used:
Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
    Dim dResult As New Dictionary(Of String, List(Of Integer))()
    Dim i As Integer = 0

    For Each s As String In wordsToSearch
        dResult.Add(s, New List(Of Integer))

        While i >= 0 AndAlso i < allWords.Count
            i = allWords.IndexOf(s, i)
            If i >= 0 Then dResult(s).Add(i)
            i += 1
        End While
    Next

    Return dResult
End Function

You will have not only the number of occurances, but the index positions in the file, grouped easily in a Dictionary.

A: Try the following code
Function word_frequency(word_ As String, input As String) As Integer
    Dim ct = 0
    Try
        Dim wLEN = word_.Length
        Do While input.IndexOf(word_) <> -1
            Dim idx = input.IndexOf(word_) + wLEN
            ct += 1
            input = input.Substring(idx)
        Loop
    Catch ex As Exception

    End Try
    Return ct
End Function


text:
Q: How to change colour of selected cell in UITableView? I am making an app in which I am showing my data in a UITableView. I am stuck. I want to change the colour of the selected cell. How to do this?
Below is my code in -didSelectRowAtIndexPath
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"the messageid==%@",[[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:@"messageId"]);
    manage.messageid=[[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:@"messageId"];  // here i pass the value to singleton class
    [self performSegueWithIdentifier:@"segueIdentifier" sender:tableView];
}

A: Update your code as mentioned below:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"the messageid==%@",[[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:@"messageId"]);

    manage.messageid = [[self.inboxmessagesarray objectAtIndex:indexPath.row ] objectForKey:@"messageId"];  // here i pass the value to singleton class

    [self performSegueWithIdentifier:@"segueIdentifier" sender:tableView];

    // Add this line to set selected default gray style
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
}

Use selectionStyle property to get cell highlighed. For more details refer UITableViewCellSelectionStyle

A: May be this will be useful to u...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   UIView *selectedRowColor = [[UIView alloc] init];
   selectedRowColor.backgroundColor = [UIColor redColor];
   cell.selectedBackgroundView = selectedRowColor;
}

A: in your cellForRowAtIndexPath has two options for selection only Blue and another one is Gray
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{

   /// here your cell identifier name and details
 UIView *changeselectionColor = [[UIView alloc] init];
changeselectionColor.backgroundColor = [UIColor colorWithRed:(245.0/255.0) green:(245.0/255.0) blue:(245.0/255.0) alpha:1];   // change the RGB as you like
cell.selectedBackgroundView = changeselectionColor;

//...... here add your cell details.. //

}

or in another choice no 2 call this method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
 UIView * changeselectionColor = [[UIView alloc] init];
 changeselectionColor.backgroundColor = [UIColor GreenColor];
 cell.selectedBackgroundView = changeselectionColor;
}


text:
Q: react: functional component that ignores prop changes until callback is triggered I have a controlled component that I want to use to trigger an optimistic update, and, while the update is being performed, it should use it's internal state and ignore all changes to it's main prop, and once a callback is executed then it can again use the provided prop as values.
I tried to encode this logic on a hook using useMemo, useRef, and different setStates but without success. I think it is because the used ref does not survive long enough (the component is re-rendered like 3 times between the update trigger and the callback execution) and at some point it gets re-created with the new value coming from props.
Here is the hook that I done so far:
function useOptimistic(incoming) {
  const [state, setState] = useState('INITIAL')
  const ref = useRef(incoming)
  const value = useMemo(() => ref.current, [state])
  const setUpdating = (value) => {
    setState('UPDATING')
    ref.current = value
  }
  const setUpdated = () => setState('UPDATED')
  return { state: value, setUpdating, setUpdated }
}

The reason is because I am using graphql and a toggle component. When I click on the toggle component I trigger the graphql request and you can see the change with the local state, but while the query is being executed the component is re-rendered 3 or 4 times, and the toggle shows the state from the "old-data", when the request completes then it comes back to the correct state. What I want is to avoid this intermediary weird changes.

A: I think that this should do it:
const initialState = { updating: false }

function useOptimistic(incoming) {
  const [innerState, setInnerState] = useState(initialState)

  const setUpdating = (value) => setInnerState({ updating: true, value })
  const setUpdated = () => setInnerState(initialState)
  const state = innerState.updating ? innerState.value : incoming

  return { state, setUpdating, setUpdated }
}

Live Example (based on T.J. Crowder's answer), just to show that it's not really necessary to have stable functions for something like this ;-).

const { useState, useRef } = React;

const initialState = { updating: false }

function useOptimistic(incoming) {
  const [innerState, setInnerState] = useState(initialState)

  const setUpdating = (value) => setInnerState({ updating: true, value })
  const setUpdated = () => setInnerState(initialState)
  const state = innerState.updating ? innerState.value : incoming

  return { state, setUpdating, setUpdated }
}

function Example() {
    const [value, setValue] = useState(1);
    const {state, setUpdating, setUpdated} = useOptimistic(value);
    const triggerUpdate = () => {
        const newValue = value + 1;
        setUpdating(newValue);
        setTimeout(() => {
            setValue(newValue);
            setUpdated(); // <=== Note that despite the fact that this function
                          // is not stable, this still works perfectly fine ;-)
        }, 1000);
    };
    return (

value: {value}

state: {state}

            <input type="button" onClick={triggerUpdate} value="Trigger Update" />

    );
}

ReactDOM.render(<Example />, document.getElementById("root"));

A: A ref will only be created once, when the component using the hook is first mounted, so you were right to try to store the pending state in a ref (although it could also be stored in state). You'd also probably be best off putting the state setters in a ref as well, since making them stable (like useState does) is useful to consumers of the hook, so I'll use the ref for the pending value as well.
The main problem with your hook, I think, is that it always uses the value from ref.current, but it only sets ref.current to incoming when the component using the hook is first mounted. So it ignores subsequent changes to incoming (whether or not it's in the updating state).
The change I'd make (other than using a boolean rather than strings for the flag) is to use your "updating" flag to choose what to return as state, returning the then-current incoming when not updating, or the optimistic pending value if updating. See comments:
function useOptimistic(incoming) {
    // A flag for whether we're in the "udating" state
    const [updatingFlag, setUpdatingFlag] = useState(false)
    // Our instance data
    const instance = useRef(null);
    if (!instance.current) {
        // Only happens on first call, this object is created once
        instance.current = {
            // The pending value
            pendingValue: null,
            // Set the pending value and go into the updating state
            setUpdating: (value) => {
                instance.current.pendingValue = value;
                setUpdatingFlag(true);
            },
            // Exit the updating state
            setUpdated: () => {
                setUpdatingFlag(false);
                instance.current.pendingValue = null;
            },
        };
    }
    // The state value we'll return: the input prop, or the one from our
    // instance data
    const state = updatingFlag ? instance.current.pendingValue : incoming;

    // Grab our setters and return them with the state
    const { setUpdating, setUpdated } = instance.current;
    return { state, setUpdating, setUpdated };
}

Live Example:

const { useState, useRef } = React;

function useOptimistic(incoming) {
    // A flag for whether we're in the "udating" state
    const [updatingFlag, setUpdatingFlag] = useState(false)
    // Our instance data
    const instance = useRef(null);
    if (!instance.current) {
        // Only happens on first call, this object is created once
        instance.current = {
            // The pending value
            pendingValue: null,
            // Set the pending value and go into the updating state
            setUpdating: (value) => {
                instance.current.pendingValue = value;
                setUpdatingFlag(true);
            },
            // Exit the updating state
            setUpdated: () => {
                setUpdatingFlag(false);
                instance.current.pendingValue = null;
            },
        };
    }
    // The state value we'll return: the input prop, or the one from our
    // instance data
    const state = updatingFlag ? instance.current.pendingValue : incoming;

    // Grab our setters and return them with the state
    const { setUpdating, setUpdated } = instance.current;
    return { state, setUpdating, setUpdated };
}

function Example() {
    const [value, setValue] = useState(1);
    const {state, setUpdating, setUpdated} = useOptimistic(value);
    const triggerUpdate = () => {
        const newValue = value + 1;
        setUpdating(newValue);
        setTimeout(() => {
            setValue(newValue);
            setUpdated(); // <=== Note that the stability of the setters is what
                          // lets me use this here, it wouldn't be correct if
                          // the setters weren't stable
        }, 1000);
    };
    return (

value: {value}

state: {state}

            <input type="button" onClick={triggerUpdate} value="Trigger Update" />

    );
}

ReactDOM.render(<Example />, document.getElementById("root"));


text:
Q: How to get 16 byte aligned address in assembly I have to save floating-point registers into the stack.
I tried to use fsave instruction.
I do the following:
fsave (%esp)

But as an argument fsave uses 16 byte aligned address.
I don't have an idea how to make address in %esp be 16 byte aligned.

A: Using intel style syntax:
    push    ebp             ;save ebp
    mov     ebp,esp         ;save esp in ebp
    and     esp,0fffffff0h  ;round esp down to 16 byte boundary
    sub     esp,128         ;allocate multiple of 16 bytes


text:
Q: SQL (Presto): Return Date when Sum of x equals some threshold I have a table the one below. I want to return the Date when the sum of Result not equal to 'na' is equal to 4

Date
ID
Result

12-01-21
a
Negative

12-01-21
b
Negative

12-02-21
b
Negative

12-02-21
c
na

12-03-21
d
Positive

Desired output:
Date
2021-03-21

What is the most efficient way to do this?
I have an idea of some elements people use from quickly searching, such as some combination rank functions, inner queries, or WITH, but I do not know the structure or format in which to arrange.
For example, logically I was thinking, rank the table by date, when pull the Date when count(Date) = 4 ,but I'm not sure of the structure. I can come up with logic, it's the structure that is the hard part for me.
Thank you for your patience and time :)

A: You can use SUM() OVER () window function along with a conditional such as
WITH tt AS
(
 SELECT t.*,
        SUM(CASE WHEN Result!='na' THEN 1 END) OVER (ORDER BY Date) AS rnk
   FROM t
)
SELECT Date
  FROM tt
 WHERE rnk = 4

or ROW_NUMBER()
WITH tt AS
(
 SELECT *, ROW_NUMBER() OVER (ORDER BY Date) AS rnk
   FROM t
  WHERE Result!='na'
)
SELECT Date
  FROM tt
 WHERE rnk = 4


text:
Q: How to decode data encrypted using AES-256 in CBC mode and PKCS7 padding? We are using below java code to decrypt the data which is encrypted using AES-256 in CBC mode and PKCS7 padding.
Java Code:
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class AES256 {

    private static byte[] initVector = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    public String decrypt (String encryptedDataBase64, String keyBase64)
    {
       try {
           Security.setProperty("crypto.policy", "unlimited");
           IvParameterSpec ivSpec = new IvParameterSpec(initVector);  // Get the init vector

           // Get the Base64-encoded key
           byte[] key = Base64.decodeBase64(keyBase64.getBytes("UTF-8"));
           Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");  // AES / CBC / PKCS5 padding
           SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
           cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
           byte[] encryptedData = Base64.decodeBase64(encryptedDataBase64.getBytes("UTF-8"));
           byte[] decryptedData = cipher.doFinal(encryptedData);

           return new String(decryptedData);
       }
       catch (Exception e) {
           logger.error("AES256 Decrypt: Decryption exception: "+ e.getMessage());
           return null;
       }
    }
}

Now we need to convert this decryption logic to Javascript as our app is sending the encrypted data in the headers while requesting for index.html from server. I tried to decrypt using Crypto.js but I am getting decoded string as empty. Below is the Javascript code I was trying to use.
var key = CryptoJS.enc.Base64.parse(keyBase64);
var data = CryptoJS.enc.Base64.parse(encryptedDataBase64);
var dec_data = CryptoJS.AES.decrypt(data, key);

dec_data is coming as empty.

I tried this after reading some of stack over flow questions. Can any one please let me know if there is any error in the code.

A: Unfortunately you didn't provide any sample data to test with your environment so I setup my own values. Using this values:
ciphertext = rjygE0TjIqiQ4ETnpszoieRWzaSD+9oINf1c748VcL/3zD5AazSFomx4paeanihz
keyBase64 = MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=
ivBase =  AAAAAAAAAAAAAAAAAAAAAA==

I'm getting this decrypt-result on Java:
The quick brown fox jumps over the lazy dog

On Javascript-side I receive the same results with my code:
decrypted (str): The quick brown fox jumps over the lazy dog

A live test can be done here - Java: https://paiza.io/projects/e/dHG73CRgJojOOfLxtvJjtg and Javascript: https://playcode.io/672463.
Please note that my code has no exception handling and is for educational purpose only. Additionally - your code is UNSECURE as it uses a static (fixed) key and initialization vector.
Java code (slightly changed as I'm using the Java 11 built in Base64 encoder):
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Base64;

public class Main {

    private static byte[] initVector = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("How to decode data encrypted using AES-256 in CBC mode and PKCS7 padding");
        String plaintext = "The quick brown fox jumps over the lazy dog";
        byte[] key = "12345678901234567890123456789012".getBytes("UTF-8");
        String keyBase64 = Base64.getEncoder().encodeToString(key);
        System.out.println("keyBase64: " + keyBase64);
        String ivBase64 = Base64.getEncoder().encodeToString(initVector);
        System.out.println("initVector: " + ivBase64);
        String ciphertext = "rjygE0TjIqiQ4ETnpszoieRWzaSD+9oINf1c748VcL/3zD5AazSFomx4paeanihz";
        System.out.println("ciphertext: " + ciphertext);
        String decryptedtext = decrypt(ciphertext, Base64.getEncoder().encodeToString(key));
        System.out.println("decryptedtext: " + decryptedtext);
    }

    public static String decrypt (String encryptedDataBase64, String keyBase64)
    {
        try {
            Security.setProperty("crypto.policy", "unlimited");
            IvParameterSpec ivSpec = new IvParameterSpec(initVector);  // Get the init vector
            // Get the Base64-encoded key
            byte[] key = Base64.getDecoder().decode(keyBase64.getBytes("UTF-8"));
            //byte[] key = Base64.decodeBase64(keyBase64.getBytes("UTF-8"));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");  // AES / CBC / PKCS5 padding
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
            byte[] encryptedData = Base64.getDecoder().decode(encryptedDataBase64.getBytes("UTF-8"));
            //byte[] encryptedData = Base64.decodeBase64(encryptedDataBase64.getBytes("UTF-8"));
            byte[] decryptedData = cipher.doFinal(encryptedData);
            return new String(decryptedData);
        }
        catch (Exception e) {
            System.out.println("AES256 Decrypt: Decryption exception: "+ e.getMessage());
            //logger.error("AES256 Decrypt: Decryption exception: "+ e.getMessage());
            return null;
        }
    }
}

Javascript code:
let keyBase64 = 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=';
let ivBase64 = 'AAAAAAAAAAAAAAAAAAAAAA==';
let iv = CryptoJS.enc.Base64.parse(ivBase64);
let secret_key = CryptoJS.enc.Base64.parse(keyBase64);
ciphertext = 'rjygE0TjIqiQ4ETnpszoieRWzaSD+9oINf1c748VcL/3zD5AazSFomx4paeanihz';
console.log('ciphertext: ', ciphertext);
var decrypted = CryptoJS.AES.decrypt(ciphertext, secret_key,{
  iv: iv,
  padding: CryptoJS.pad.Pkcs7,
  mode: CryptoJS.mode.CBC,
});
console.log('decrypted (str): ', CryptoJS.enc.Utf8.stringify(decrypted).toString());


text:
Q: Tcp/IP socket programming in python I am currently involved in a project where we performed some computer vision object recognition and classification using python. It is necessary to use photos taken from an Android phone (photos should be automatically sent from android to python). I actually don't know how should I connect both applications (android and python) together. I thought of using TCP Server, but I am new to socket programming and don't know how and where to start.
Any one can help?

A: Android gives you options to connect via HTTP.
http://developer.android.com/guide/topics/connectivity/index.html
So I would probably go with a REST type implementation
https://en.wikipedia.org/wiki/Representational_state_transfer
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
Here is a tutorial for Android and REST
http://www.majidkhosravi.com/android-rest/
But you are dealing with pictures.  Here is a SO talking about that.
POSTing image from Android to WCF Rest Service
On the Python side you have multiple choices, but the main ones I would consider:
Twisted (or maybe Tornado) if you want Asynch.
http://twistedmatrix.com/trac/wiki/WebDevelopmentWithTwisted
http://zenmachine.wordpress.com/web-services-and-twisted/
Flask for Synch.
http://flask-restful.readthedocs.org/en/latest/quickstart.html
Maybe Nginx/Apache + Django
http://django-rest-framework.org/
SO post about Python and REST
Recommendations of Python REST (web services) framework?
If you want to implement this at the socket level, this book would be a great resource:
http://www.amazon.com/Foundations-Python-Network-Programming-Goerzen/dp/1590593715
Hope this helps provide you some directions to explore.

A: poof's answer is a good overview, but here are some notes on the various options:
Option 1: Have your Android get the picture and do a HTTP POST to a Python application running a framework such as Django.  It should be 1 line of code on Android, and only a few lines of code on Python (around your existing code).
The upside is that the low-level "Glue" is written for you, and it scales easily. The downside is that HTTP has some overhead.
Option 2: Have your Android talk a custom TCP protocol to a custom TCP application.
This is more work, so you should avoid it unless you need it. It will be more efficient and have lower latency, especially if you're sending multiple pictures. The response can also be much smaller without HTTP headers.
In either option, you don't have to send a JPEG, you could send any custom format you want (there is a trade-off between compression on Android and size of file).

I thought of using TCP Server, but I am new to socket programming and don't know how and where to start.

Start where everyone else started - by reading a lot and playing a lot. You can find plenty of introductions to Socket programming in Python on the web. Go thru the tutorials, and start modifying them to see how they work.  Read up on TCP/IP itself -- there are a lot of dark corners (Nagel, fragmentation, slow start) that can affect how you write the app when you get to a low level.


text:
Q: mongodb find.count({}) showing less data than find({}) I am facing a very strange issue in mongoDB.
I have a collection and was trying to find the count of collection:
db.getCollection('inventory_items').find({}).count

db.getCollection('inventory_items').count()

Above 2 queries returns value: 4847604
And below query return count: 4847790
(I found 185 extra records with below query)
db.getCollection('inventory_items').find({ "inventoryItemId" :
        { "$lte" : 347429803.0}}).count()

Is find({}).count() has any restrictions?
why is it not showing me an entire collection count?

A: A broken index may cause that difference. Can you try this?
db.getCollection('inventory_items').reIndex()

Here the docs:
https://docs.mongodb.com/manual/reference/method/db.collection.reIndex/


text:
Q: UIScrollView animation to targetContentOffset erratic I've implemented a UIScrollView within a UITableViewCell that enables the user to scroll left and right to reveal buttons in the same fashion as the iOS Mail app. The original implementation that set frames and positions explicitly worked well but I've refactored the code to use autolayout throughout. Animation to hide/reveal the 'container' for the buttons on the left (accessory buttons) works well but the animation that brings the scrollview to rest when the right container (edit buttons) slows just before reaching the desired offset before jerking into its final position.
All calculations use the same math just transformed (e.g. + rather than - value, > rather than < in tests) depending on the side the container is located and the values displayed by logging are correct. I can't see any obvious code errors and there are no constraints for the cells set up in IB. Is this a bug or is there something obvious I've missed through staring at the code for the last hour?
class SwipeyTableViewCell: UITableViewCell {

    // MARK: Constants
    private let thresholdVelocity = CGFloat(0.6)
    private let maxClosureDuration = CGFloat(40)

    // MARK: Properties
    private var buttonContainers = [ButtonContainerType: ButtonContainer]()
    private var leftContainerWidth: CGFloat {
        return buttonContainers[.Accessory]?.containerWidthWhenOpen ?? CGFloat(0)
    }
    private var rightContainerWidth: CGFloat {
        return buttonContainers[.Edit]?.containerWidthWhenOpen ?? CGFloat(0)
    }
    private var buttonContainerRightAnchor = NSLayoutConstraint()
    private var isOpen = false

    // MARK: Subviews
    private let scrollView = UIScrollView()

    // MARK: Lifecycle methods
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        scrollView.delegate = self
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        contentView.addSubview(scrollView)
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true
        scrollView.leftAnchor.constraintEqualToAnchor(contentView.leftAnchor).active = true
        scrollView.rightAnchor.constraintEqualToAnchor(contentView.rightAnchor).active = true
        scrollView.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true

        let scrollContentView = UIView()
        scrollContentView.backgroundColor = UIColor.cyanColor()
        scrollView.addSubview(scrollContentView)
        scrollContentView.translatesAutoresizingMaskIntoConstraints = false
        scrollContentView.topAnchor.constraintEqualToAnchor(scrollView.topAnchor).active = true
        scrollContentView.leftAnchor.constraintEqualToAnchor(scrollView.leftAnchor).active = true
        scrollContentView.rightAnchor.constraintEqualToAnchor(scrollView.rightAnchor).active = true
        scrollContentView.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor).active = true
        scrollContentView.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor, constant: 10).active = true
        scrollContentView.heightAnchor.constraintEqualToAnchor(contentView.heightAnchor).active = true

        buttonContainers[.Accessory] = ButtonContainer(type: .Accessory, scrollContentView: scrollContentView)
        buttonContainers[.Edit] = ButtonContainer(type: .Edit, scrollContentView: scrollContentView)
        for bc in buttonContainers.values {
            scrollContentView.addSubview(bc)
            bc.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor).active = true
            bc.heightAnchor.constraintEqualToAnchor(scrollContentView.heightAnchor).active = true
            bc.topAnchor.constraintEqualToAnchor(scrollContentView.topAnchor).active = true
            bc.containerToContentConstraint.active = true
        }

        scrollView.contentInset = UIEdgeInsetsMake(0, leftContainerWidth, 0, rightContainerWidth)
    }

    func closeContainer() {
        scrollView.contentOffset.x = CGFloat(0)
    }

}

extension SwipeyTableViewCell: UIScrollViewDelegate {

    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint,
        targetContentOffset: UnsafeMutablePointer<CGPoint>) {
            let xOffset: CGFloat = scrollView.contentOffset.x
            isOpen = false
            for bc in buttonContainers.values {
                if bc.isContainerOpen(xOffset, thresholdVelocity: thresholdVelocity, velocity: velocity) {
                    targetContentOffset.memory.x = bc.offsetRequiredToOpenContainer()
                    NSLog("Target offset \(targetContentOffset.memory.x)")
                    isOpen = true
                    break /// only one container can be open at a time so cn exit here
                }
            }
            if !isOpen {
                NSLog("Closing container")
                targetContentOffset.memory.x = CGFloat(0)
                let ms: CGFloat = xOffset / velocity.x  /// if the scroll isn't on a fast path to zero, animate it closed
                if (velocity.x == 0 || ms < 0 || ms > maxClosureDuration) {
                    NSLog("Animating closed")
                    dispatch_async(dispatch_get_main_queue()) {
                        scrollView.setContentOffset(CGPointZero, animated: true)
                    }
                }
            }
    }

/**
Defines the position of the container view for buttons assosicated with a SwipeyTableViewCell

- Edit:      Identifier for a UIView that acts as a container for buttons to the right of the cell
- Accessory: Identifier for a UIView that acts as a container for buttons to the left of the vell
*/
enum ButtonContainerType {
    case Edit, Accessory
}

extension ButtonContainerType {
    func getConstraints(scrollContentView: UIView, buttonContainer: UIView) -> NSLayoutConstraint {
        switch self {
        case Edit:
            return buttonContainer.leftAnchor.constraintEqualToAnchor(scrollContentView.rightAnchor)
        case Accessory:
            return buttonContainer.rightAnchor.constraintGreaterThanOrEqualToAnchor(scrollContentView.leftAnchor)
        }
    }

    func containerOpenedTest() -> ((scrollViewOffset: CGFloat, containerFullyOpenWidth: CGFloat, thresholdVelocity: CGFloat, velocity: CGPoint) -> Bool) {
        switch self {
        case Edit:
            return {(scrollViewOffset: CGFloat, containerFullyOpenWidth: CGFloat, thresholdVelocity: CGFloat, velocity: CGPoint) -> Bool in
                (scrollViewOffset > containerFullyOpenWidth || (scrollViewOffset > 0 && velocity.x > thresholdVelocity))
            }
        case Accessory:
            return {(scrollViewOffset: CGFloat, containerFullyOpenWidth: CGFloat, thresholdVelocity: CGFloat, velocity: CGPoint) -> Bool in
                (scrollViewOffset < -containerFullyOpenWidth || (scrollViewOffset < 0 && velocity.x < -thresholdVelocity))
            }
        }
    }

    func transformOffsetForContainerSide(containerWidthWhenOpen: CGFloat) -> CGFloat {
        switch self {
        case Edit:
            return containerWidthWhenOpen
        case Accessory:
            return -containerWidthWhenOpen
        }
    }
}

/// A UIView subclass that acts as a container for buttongs associated with a SwipeyTableCellView
class ButtonContainer: UIView {

    private let scrollContentView: UIView
    private let type: ButtonContainerType

    private let maxNumberOfButtons = 3
    let buttonWidth = CGFloat(65)
    private var buttons = [UIButton]()
    var containerWidthWhenOpen: CGFloat {
//        return CGFloat(buttons.count) * buttonWidth
        return buttonWidth // TODO: Multiple buttons not yet implements - this will cause a bug!!
    }
    var containerToContentConstraint: NSLayoutConstraint {
        return type.getConstraints(scrollContentView, buttonContainer: self)
    }
    var offsetFromContainer = CGFloat(0) {
        didSet {
            let delta = abs(oldValue - offsetFromContainer)
            containerToContentConstraint.constant = offsetFromContainer
            if delta > (containerWidthWhenOpen * 0.5) { /// this number is arbitary - can it be more formal?
                animateConstraintWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, completion: nil) /// ensure large changes are animated rather than snapped
            }
        }
    }

    // MARK: Initialisers

    init(type: ButtonContainerType, scrollContentView: UIView) {
        self.type = type
        self.scrollContentView = scrollContentView
        super.init(frame: CGRectZero)
        backgroundColor = UIColor.blueColor()
        translatesAutoresizingMaskIntoConstraints = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: Public methods

    func isContainerOpen(scrollViewOffset: CGFloat, thresholdVelocity: CGFloat, velocity: CGPoint) -> Bool {
        let closure = type.containerOpenedTest()
        return closure(scrollViewOffset: scrollViewOffset, containerFullyOpenWidth: containerWidthWhenOpen, thresholdVelocity: thresholdVelocity, velocity: velocity)
    }

    func offsetRequiredToOpenContainer() -> CGFloat {
        return type.transformOffsetForContainerSide(containerWidthWhenOpen)
    }
}

A: OK - found the error and it was a typo left from earlier experimentation with UIScrollView. The clue was in my earlier comment about the 'snap' occurring within 10pt of the desired targetContentOffset...
The scrollContentView width constraint was set incorrectly as follows:
scrollContentView.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor, constant: 10).active = true

Before I found out that I could force a UIScrollView to scroll by setting its contentInset, I just made the subview larger that the cell's contentView that the UIScrollView was pinned to. As I've been refactoring code verbatim to use the new anchor properties, the old code propagated and I got my bug!
So, not iOS at fault...just me not paying attention. Lesson learnt! I now have some other ideas on how to implement things that might be a little tidier.


text:
Q: How to get past/ended public events from facebook using graph api/FQL? I tried using the since and until parameters to get past events but it doesnt seem to work. The results from using since and until parameters give only events that have an end date in the future and a start date within the specified time limit. But however i would like to retrieve a list of all public events within the specified limit irrespective of whether it is still active or not. Is this possible?
Thanks for your help

A: You can use FQL for that:
select eid, name, start_time from event where creator = {page_id} and start_time >= "2014-05-01T00:00:00+0200" and start_time <= "2014-05-31T23:59:59+0200"

Make sure that {page_id} is a valid Page ID (or User ID). See https://developers.facebook.com/docs/reference/fql/event/ as reference.


text:
Q: seeking bidirectional map with non-unique keys or values I need a bidirectional container with non-unique keys or values. multimap doesn't work, because it's unidirectional and boost>::bimap only allows unique keys and values. Any such container in the standard or boost libs? Otherwise: any pointers/articles to implement such a structure would be appreciated. Only up to 100 or so element-pairs are expected. Any help appreciated, thanks, Jeanette

A: You could use a vector of pairs. If you only have 100 elements, linear search is perfectly adequate for lookup on both pair elements. If you have larger collections, or if you frequently need equal-ranges on either pair element, you can maintain separate index structures.
(This is basically how boost.bimap is implemented anyway.)

A: Actually boost::bimap does allow non-unique keys:
http://www.boost.org/doc/libs/release/libs/bimap/doc/html/boost_bimap/the_tutorial/differences_with_standard_maps.html
Example:
#include <boost/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <string>
#include <iostream>

namespace bm = boost::bimaps;

int main()
{
    using mybimap = bm::bimap< bm::multiset_of<std::string>, int >;
    mybimap map;

    map.left.insert( mybimap::left_value_type( "orange", 1 ) );
    map.left.insert( mybimap::left_value_type( "apple", 42 ) );
    map.left.insert( mybimap::left_value_type( "orange", 7 ) );

    auto rng = map.left.equal_range( "orange" );
    for( auto it = rng.first; it != rng.second; ++it )
        std::cout << it->first << ": " << it->second << "\n";
}

Live Demo:
http://coliru.stacked-crooked.com/a/2efdc80cde5f2933


text:
Q: jQuery draggable moves when dropped I have set up a simple drag and drop interface which implements the clone functionality. The issue I have is that when the element is dragged to the main canvas and then dropped, it suddenly shifts to the right, rather than dropping exactly where I drag it.
Here is the javascript:
$(function() {
  var x = null;

  $("#draggable").draggable({
    helper: 'clone',
    cursor: 'move',
    snap: '.snap-target'
  });

  $("#canvas").droppable({
    drop: function(e, ui) {
      if ($(ui.draggable)[0].id != "") {
        x = ui.helper.clone();
        ui.helper.remove();
        x.draggable({
          helper: 'original',
          containment: '#canvas',
          snap: '.snap-target'
        });
        x.appendTo('#canvas');
      }
    }
  });

});

I have created a jsfiddle:
https://jsfiddle.net/kuyn6gmc/
If you try and drag the blue box into the main canvas then release the mouse you will see how the box "pops" to the right slightly. When you move the box within the canvas, it works fine. On the fiddle it's not as bad as when it's full width on a browser, I think it's relative to the total width of the viewport.
If anyone knows why this may be happening I would appreciate it :)
Thank you
Michael

A: The reason this is occuring is because the draggable element is absolutely positioned relative to the viewport while it is being dragged. Once the element is appended, the positioning is relative to the #canvas element (because of position: relative), which is why the element moves when you drop it.
As the other answer suggests, you could remove position: relative from the element, however, that probably won't work in all cases. I'd suggest taking the positioning of the element into account before appending the element.
Updated Example
For instance, you could subtract the offset top/left positioning, as well as the width of the border. In doing so, the #canvas element can still be relatively positioned.
var canvasOffset = {
  'top': parseInt($(this).offset().top, 10) + parseInt($(this).css('border-top-width'), 10),
  'left': parseInt($(this).offset().left, 10) + parseInt($(this).css('border-left-width'), 10)
}

$draggble.css({
  "top": parseInt($draggble.css('top'), 10) - canvasOffset.top + 'px',
  "left": parseInt($draggble.css('left'), 10) - canvasOffset.left + 'px'
}).appendTo('#canvas');

A: You have to put position: relative to the body instead of the canvas.
    .draggable { padding: 5px; float: left; margin: 0 10px 10px 0; font-size: .9em; position: relative; }
    .small { border: 1px solid slateblue; width: 115px; height: 115px; background: #c5cae9 }
    .ui-widget-header p, .ui-widget-content p { margin: 0; }
    .text-box { text-align: center; vertical-align: middle; }
    body { font-family: 'Helvetica Neue', Helvetica, Arial, serif; font-size: 13px }
    #canvas { width: 600px; height: 300px; border: 1px solid #cccccc; margin: auto;
        clear: both; }
    .draggable-selectors { margin: 10px auto; width: 1000px; }
    body { position: relative; margin: 0; }

<body class='snap-target'>


text:
Q: How patching an object with an array of objects I have a many-to-many relationship between Ticket and ProductList . Here's is what I have for a Ticket :
// INIT MODEL
                    var ticketModel = new Ticket
                    {
                        Customer = new Customer(),
                        Seller = new Seller(),
                        AddressInvoice = new Address(),
                        ProductList = new List<Product>()
                    };
                    JsonPatchDocument model = new JsonPatchDocument();

                    // FOR EACH COLUMN
                    foreach (var map in mapList)
                    {
                        if (map.FieldName.Contains("List"))
                            model.Add(map.FieldName, fields[map.ColumnIndex]);
                        else
                            model.Add(map.FieldName, fields[map.ColumnIndex]);
                    }
                    model.ApplyTo(ticketModel);

I'm using JsonPatch to PATCH my objects. I'm trying to add to the collection of Product, just to the end of the collection with this JSON Patch:
[
  {
    "op": "add",
    "path": "/ProductList/-",
    "value":"POWER TETRIS  3P FTTX"
  }
]

It works with simple sub properties like : Customer, Seller. But when I want to add a product in the list object, it doesn't work


text:
Q: How to Block Spammy Accept-Language in either Apache or Nginx Stevie-Ray has create a neat Nginx Referral Spam configuration file to block out known referrer spam on Google Analytics.
https://github.com/Stevie-Ray/referrer-spam-blocker
Sure it's a cat and mouse game, but it definitely does help.
Now it seems that the spammer are using the Accept-Language header to spam Google's overview page with things like:
Secret.ɢoogle.com You are invited! Enter only with this ticket URL. Copy it. Vote for Trump!

And
o-o-8-o-o.com search shell is much better than google!

Is there a way, either in Nginx or Apache, that you could block out Accept-Language headers that do not match the Language Tag pattern defined by W3?


text:
Q: Ending imap-simple connection within recursion I currently have a script that checks for an incoming email (in a mailbox) every 30 seconds, using a recursion.
The package I'm using for this testing is imap-simple.
The below script currently does this as required;
var imaps = require('imap-simple');
const { connect } = require('net');
var config = {
    imap: {
        user: 'qatestspecialist@outlook.com',
        password: 'specialistQa',
        host: 'imap-mail.outlook.com',
        port: 993,
        tls: true,
        authTimeout: 30000
    }
};

module.exports = {

    'delete any existing emails...': function () {
        imaps.connect(config).then(function (connection) {
            connection.openBox('INBOX').then(function () {
                var searchCriteria = ['ALL'];
                var fetchOptions = { bodies: ['TEXT'], struct: true };
                return connection.search(searchCriteria, fetchOptions);
            //Loop over each message
            }).then(function (messages) {
                let taskList = messages.map(function (message) {
                    return new Promise((res, rej) => {
                        var parts = imaps.getParts(message.attributes.struct);
                        parts.map(function (part) {
                            return connection.getPartData(message, part)
                            .then(function (partData) {
                                //Display e-mail body
                                if (part.disposition == null && part.encoding != "base64"){
                                    console.log(partData);
                                }
                                //Mark message for deletion
                                connection.addFlags(message.attributes.uid, "\Deleted", (err) => {
                                    if (err){
                                        console.log('Problem marking message for deletion');
                                        rej(err);
                                    }
                                    res(); //Final resolve
                                });
                            });
                        });
                    });
                });
                return Promise.all(taskList).then(() => {
                    connection.imap.closeBox(true, (err) => { //Pass in false to avoid delete-flagged messages being removed
                        if (err){
                            console.log(err);
                        }
                    });
                    connection.end();
                });
            });
        });
    },

    'send email to seller and wait for mailbox notification': function (browser) {
        // script to send an email to the mailbox...
    },

    'get new email info': function(browser) {
        const createPromise = ms => new Promise((resolve, reject) => {
                setTimeout(() => resolve(ms), ms)
            });
            function findUnseenEmails(connection) {
                return connection.openBox('INBOX').then(function () {
                    var searchCriteria = ['UNSEEN'];
                    var fetchOptions = {
                        bodies: ['HEADER', 'TEXT'],
                        markSeen: false
                    };
                    return connection.search(searchCriteria, fetchOptions).then(function (results) {
                        var subjects = results.map(function (res) {
                            return res.parts.filter(function (part) {
                                return part.which === 'HEADER';
                            })
                            [0].body.subject[0];
                        });
                        return subjects.length > 0 ? subjects : createPromise(30000).then(function() { return findUnseenEmails(connection);
                    });
                });
            });
        }

        imaps.connect(config).then(function (connection) {
            return findUnseenEmails(connection)
        })

        .then((subjects) => console.log(JSON.stringify(subjects)));
    },

    'Closing the browser': function (browser) {
        browser.browserEnd();
    }

};

This waits for an email and then displays the email 'header'.
However, the imap connection does not close, and stays open which is stopping my test suite from completing as the associated test never actually finishes.
I've tried adding the imap-simple command connection.end() in several places after the
imaps.connect(config).then(function (connection) {
     return findUnseenEmails(connection)
})

part of the script, but it doesn't work.
So I'm just wondering if anyone knows where I should be adding this connection.end() command in order for the connection to be closed once an email has been received?
Any help would be greatly appreciated.

A: This has now been resolved in another post, using the following;
if (subjects.length > 0) {
    connection.end();
    return subjects;
} else {
    return createPromise(5000).then(function() { return findUnseenEmails(connection)});
}


text:
Q: Are 'should' and 'be supposed to' interchangeable?
Possible Duplicate:
Why do we say "supposed to" for "should have"?

I guess I really can't tell if 'should' and 'be supposed to' are interchangeable from the definitions of the dictionaries. Can anyone prove they are synonymous or not, with evidence?

A: Should in the modern sense means "ought" or that you would do something, but are unable to. As in, "I should clean my room, but I'm tired." The archaic sense, as in owing an obligation, has mostly been replaced with the singular simple present: shall.
The phrase "supposed to," when paired with an infinitive suggests an obligation or an intended purpose. Such as, "I'm supposed to clean my room," or "A clean room is supposed to look nice."
So, in modern usage, "supposed to" suggests owing an obligation as opposed to "should" which, in itself, has become a suggestion.

A: "should" or "ought to" in linguistic roots stems from the Indo-European optative mood, indicating a wish or hope - "we should make it home by morning", whereas "supposed to" is in the indicative mood, stating fact - "I am supposed to be at work in the morning".


text:
Q: Return a value from stored procedure classic asp As a noob to stored procedures, I can't get my head around how to get a classic ASP (vbscript) page to return a value from a stored procedure. I can write data to a table ok, it's just retrieving stuff that has me stuck.
If I use a very basic example. This is a stored procedure that should return a count of the records in a table:
CREATE PROCEDURE [dbo].[SP_RecordCount]

AS

SELECT COUNT(*) FROM MyTable

What Classic ASP code (and what changes to the SPROC) would I need to write to be able to display the value in a browser?
Once I understand how to get a basic output such as this, I should hopefully(!) be able to build on the knowledge.
Thanks.

A: Probably the cleanest way is to modify your stored procedure like this:
CREATE PROCEDURE [dbo].[SP_RecordCount]
@CountResult int OUTPUT
AS

SELECT @CountResult = COUNT(*) FROM MyTable

... and this is the server-side code to call it and read the value:
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")

Set cmd.ActiveConnection = .... previously opened ADO connection here
cmd.CommandType = adCmdStoredProc  'be sure adCmdStoredProc constant is set in scope, or hardcode relevant integer instead'
cmd.CommandText = "SP_RecordCount"
cmd.Parameters.Refresh

cmd.Execute
Dim count
count = cmd.Parameters(1)

A: See How to call SQL Server stored procedures from ASP
 <%@ LANGUAGE="VBSCRIPT" %>

   <TITLE>Place Document Title Here</TITLE>

   This first method queries the data source about the parameters
   of the stored procedure. This is the least efficient method of calling
   a stored procedure.

   <%
   Set cn = Server.CreateObject("ADODB.Connection")
   Set cmd = Server.CreateObject("ADODB.Command")
   cn.Open "data source name", "userid", "password"
   Set cmd.ActiveConnection = cn
   cmd.CommandText = "sp_test"
   cmd.CommandType = adCmdStoredProc
   ' Ask the server about the parameters for the stored proc
   cmd.Parameters.Refresh
   ' Assign a value to the 2nd parameter.
   ' Index of 0 represents first parameter.
   cmd.Parameters(1) = 11
   cmd.Execute
   %>
   Calling via method 1

   ReturnValue = <% Response.Write cmd.Parameters(0) %>

   Method 2 declares the stored procedure, and then explicitly declares
   the parameters.

   <%
   Set cn = Server.CreateObject("ADODB.Connection")
   cn.Open "data source name", "userid", "password"
   Set cmd = Server.CreateObject("ADODB.Command")
   Set cmd.ActiveConnection = cn
   cmd.CommandText = "sp_test"
   cmd.CommandType = adCmdStoredProc
   cmd.Parameters.Append cmd.CreateParameter("RetVal", adInteger, _
      adParamReturnValue)
   cmd.Parameters.Append cmd.CreateParameter("Param1", adInteger, _
      adParamInput)
   ' Set value of Param1 of the default collection to 22
   cmd("Param1") = 22
   cmd.Execute
   %>
   Calling via method 2

   ReturnValue = <% Response.Write cmd(0) %>

   Method 3 is probably the most formal way of calling a stored procedure.
   It uses the canocial
   <%
   Set cn = Server.CreateObject("ADODB.Connection")
   cn.Open "data source name", "userid", "password"
   Set cmd = Server.CreateObject("ADODB.Command")
   Set cmd.ActiveConnection = cn
   ' Define the stored procedure's inputs and outputs
   ' Question marks act as placeholders for each parameter for the
   ' stored procedure
   cmd.CommandText = "{?=call sp_test(?)}"
   ' specify parameter info 1 by 1 in the order of the question marks
   ' specified when we defined the stored procedure
   cmd.Parameters.Append cmd.CreateParameter("RetVal", adInteger, _
   adParamReturnValue)
   cmd.Parameters.Append cmd.CreateParameter("Param1", adInteger, _
     adParamInput)
   cmd.Parameters("Param1") = 33
   cmd.Execute
   %>
   Calling via method 3

   ReturnValue = <% Response.Write cmd("RetVal") %>

A: Add the command SET NOCOUNT ON in your procedure
CREATE PROCEDURE [dbo].[SP_RecordCount]

AS

SET NOCOUNT ON

SELECT COUNT(*) FROM MyTable


text:
Q: Problem with a TikZ/Geogebra plot of an exponential function (even if using CVS version definition) I wanted to graph the function f(x)=(-1+4x^2)*e^2 in a coordinate system. Using "Export Graphics View as pgf/TikZ" in Geogebra  I got the following code (here shown after I did some minor changes regarding color and arrow style).
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
[scale=2,line cap=round,line join=round,x=1.0cm,y=1.0cm]
\draw [color=black!70,dash pattern=on 1pt off 1pt, xstep=0.5cm,ystep=0.5cm] (-1.45,-1.28) grid (1.45,2.48);
\draw[->,line width=1,color=black] (-1.45,0) -- (1.45,0);
\foreach \x in {-1,1}
\draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {\footnotesize $\x$};
\draw[color=black] (1.31,0.04) node [anchor=south west] { x};
\draw[->,line width=1,color=black] (0,-1.28) -- (0,2.48);
\foreach \y in {-1,1,2}
\draw[shift={(0,\y)},color=black] (2pt,0pt) -- (-2pt,0pt) node[left] {\footnotesize $\y$};
\draw[color=black] (0.05,2.28) node [anchor=west] { y};
\clip(-1.45,-1.28) rectangle (1.45,2.48);
\draw[line width=1,color=black!80,fill=black!80,fill opacity=0.6, smooth,samples=50,domain=0.0:0.5] plot(\x,{(4*\x^2-1)*2.7183^\x}) -- (0.5,0) -- (0,0) -- cycle;
\draw[line width=1,smooth,samples=100,domain=-1.5:1.5] plot(\x,{(-1+4*\x^2)*2.7183^\x});
\end{tikzpicture}
\end{document}

The code above gave me this result:

I tried installing TikZ CSV from this page  following steps given here  but this only flooded the log in "Undefined control sequence" messages.
Instead I tried using Jake's answer code to improve the exp-function. Then the result looked a bit better but still not correct:

Here is how the original graph is shown in Geogebra (Wolfram Alpha shows similar results):

Obviously the exp-code is not helping enough, so maybe there still is a bug in that? Can someone help me with this? Would it be possible to plot the graph correctly in some other way? If so, what would that code look like?

A: GeoGebra is a wonderful tool for creating interactive tools for students, and while the code it produces using its export feature is pretty impressive, it can usually not beat a hand-made solution, especially for readability and cleanness.
Here's a hand-made solution using pgfplots

% arara: pdflatex
% !arara: indent: {overwrite: true, trace: on}
\documentclass{standalone}

\usepackage{pgfplots}

% axis style
\pgfplotsset{every axis/.append style={
              axis x line=middle,
              axis y line=middle,
              axis line style={<->},
              xlabel={$x$},
              ylabel={$y$},
              },
              framed/.style={axis background/.style ={draw=black}},
                    }

% arrow style
\tikzset{>=stealth}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[framed,
            xmin=-5,xmax=5,
            ymin=-5,ymax=5,
            minor xtick={-3,-1,...,3},
            minor ytick={-3,-1,...,3},
            grid=both
        ]
        \addplot[-] expression[domain=-2.3:2.3,samples=50]{(-1+4*x^2)*exp(x)};
        \addplot[fill] expression[domain=0:0.5]{(-1+4*x^2)*exp(x)}\closedcycle;
    \end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Stack Overflow in serializing to JSON an Object with double members Trying to run this code to serialize an object in JSON using dartson generates a Stack Overflow exception when using a double value in a member.
How can i solve this problem?
 import 'package:dartson/dartson.dart';

    @MirrorsUsed(targets:const['example'], override:'*')
    import 'dart:mirrors';

    @Entity()
    class GeoFence {
      String label;
      num latitude;
      num longitude;
      num radius;
    }

    main(List<String> args) {
      var dson = new Dartson.JSON();

      GeoFence object = new GeoFence()
        ..label = "test"
        ..latitude = 46.2
        ..longitude = 12
        ..radius = 10;

      String jsonString = dson.encode(object);
      print(jsonString);
    }

A: It's a closed issue, but the serialization of double doesn't work yet GitHub issue

A: I tried your example and it looks like there's an issue with doubles used in "num" defined properties. Please try:
import 'package:dartson/dartson.dart';

@Entity()
class GeoFence {
  String label;
  double latitude;
  double longitude;
  double radius;
}

main(List<String> args) {
  var dson = new Dartson.JSON();

  GeoFence object = new GeoFence()
    ..label = "test"
    ..latitude = 46.2
    ..longitude = 12
    ..radius = 10;

  String jsonString = dson.encode(object);
  print(jsonString);
}

Also please notice that @MirrorUsed annotation is no longer required when using dartson. I'll update the issue on github and take a look at it asap.


text:
Q: How to extract X509 Certificate fields in Java I am currently working on an application that will process certain fields of a X509 Certificate, and I cannot seem to figure out how to extract certain parts of the certificate for debugging purposes. So far I have only been able to figure out how to read a certificate from a file based on the Javadoc for java.security.cert.Certificate, using this code:
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);

CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
    Certificate cert = cf.generateCertificate(bis);
System.out.println(cert.toString());
}

Assuming that no exceptions are thrown, and that cert is a valid certificate, how would I do this?
Sidenote I am using Bouncy Castle in this project

A: Cast it to an X509Certificate:
X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);
System.out.println(cert.getSubjectDN());


text:
Q: mysql on SonarQube is bloated I am using SonarQube 4.5 with mysql.
Here's the part in the system information:
   Version  4.5
   Database MySQL 5.5.40
   Database URL jdbc:mysql://localhost:3306/sonar?   useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance
   Database Login   sonar
   Database Driver  MySQL Connector Java mysql-connector-java-5.1.27 ( Revision: alexander.soklakov@oracle.com-20131021093118-gtm1bh1vb450xipt )

When running the Hudson build I get an exception, which among other says:

SQL: select           c.id,     c.kee as kee,     c.issue_key as issueKey,     c.user_login as userLogin,     c.change_type as changeType,     c.change_data as changeData,     c.created_at as createdAt,     c.updated_at as updatedAt,     c.issue_change_creation_date as issueChangeCreationDate         from issue_changes c     inner join issues i on i.kee = c.issue_key     inner join (select p.id,p.kee from projects p where (p.root_id=? and p.qualifier <> 'BRC') or (p.id=?)) p on p.id=i.component_id      WHERE  c.change_type=?       and i.status <> 'CLOSED'      order by c.issue_change_creation_date asc
Cause: java.sql.SQLException: Got error 28 from storage engine

I have set up the Delete all snapshots after to 10.
When I go to sonar-home/data, I see a huge file sonar.h2.db

*

*can I delete it?

*Where's the mySQL data located?

Thanks,

A: If you're using MySQL, you should not have sonar.h2.db files in $SONAR_HOME/data folder (this is only when you run SonarQube with the built-in H2 DB for test purposes).
The error you get from MySQL tells you that you don't have enough space, see 1030 Got error 28 from storage engine.