问:
NFC Tag becomes "corrupted" after writeNdefMessage interrupted I/O
We have an Android application that communicates with an NFC tag on a custom hardware device. The hardware device can also communicate and perform operations on the tag mounted to it.

The Android application communicates with the NFC tag in two ways:

IsoDep#transceive(byte[]) for triggering a power cycle of the hardware device.

Ndef#writeNdefMessage(NdefMessage) for writing an NdefMessage/NdefRecord with some user data.

Functionally, these operations look something akin to:

```<code>private static final byte[] NDEF_SELECT_APP_FRAME = new byte[] {
    (byte) 0x00, (byte) 0xA4, (byte) 0x04,
    (byte) 0x00, (byte) 0x07, (byte) 0xD2,
    (byte) 0x76, (byte) 0x00, (byte) 0x00,
    (byte) 0x85, (byte) 0x01, (byte) 0x01
};

private static final byte[] SYSTEM_FILE_SELECT = new byte[] {
    (byte) 0x00, (byte) 0xA4, (byte) 0x00,
    (byte) 0x0C, (byte) 0x02, (byte) 0xE1,
    (byte) 0x01
};

private static final byte[] TOGGLE_GPO = new byte[] {
    (byte) 0xA2, (byte) 0xD6, (byte) 0x00,
    (byte) 0x1F, (byte) 0x01, (byte) 0x00
};

boolean recordSuccess = writeRecord(tag, intent, context);
if (recordSuccess) {
    boolean success = transceive(NDEF_SELECT_APP_FRAME, tag, context)
            && transceive(SYSTEM_FILE_SELECT, tag, context)
            && transceive(TOGGLE_GPO, tag, context);
    if (success) {
        // Success!
    } else {
        // Error!
    }
}
</code>```

We've found that, very occasionally, it seems possible that I/O can be interrupted while the Ndef data is being written (we're not sure why, but we presume pulling the phone away from the tag at just the right time is the reason). This seems to result in the tag being in a "corrupted"-like state, where the previous Ndef data can no longer be found on the tag. In fact, tag.getTechList() won't even list Ndef as an available technology on the tag, though it was originally available.

All further attempts to write Ndef data to the tag will then fail because Ndef.get(tag) will return null.

As far as I'm aware, the normal procedure from this point would be to reformat the tag using NdefFormatable. However, NdefFormatable is not listed as a technology type in tag.getTechList(), and so NdefFormatable.get(tag) also returns null.

Questions:

Why is the tag seemingly becoming corrupted/erased?

Why is Ndef not listed as a tag technology after corruption, even though the tag originally supported it?

How can we recover from this state, given that NdefFormatable.get(tag) seems to return null?

EDIT: The NFC chip appears to be a M24SR04-Y. The specification sheet can be found here: https://www.st.com/resource/en/datasheet/m24sr04-g.pdf.

Capability Container contents shown by TagInfo app:

```<code># Capability Container (CC) file content:
Mapping version 2.0
CC length: 15 bytes
Maximum Le value: 246 bytes
Maximum Lc value: 246 bytes
NDEF File Control TLV:
* Length: 6 bytes
* NDEF file ID: 0x0001
* Maximum NDEF data size: 512 bytes
* NDEF access: Read & Write
[0] 00 0F 20 00 F6 00 F6 04 06 00 01 02 00 00 00    |.. ............ |
</code>```

答:
After having a glance at the datasheet shared by you, following are my observations:

0xE103 : CC File

0x0001 : NDEF File

CC File is Read-Only from both RF and I2C

Max NDEF File Size: 512 bytes

Read and Write : Free Access

Max No of bytes can be read or write in one operation : 246 bytes

Assuming that CC content has never changed:
00 0F 20 00 F6 00 F6 04 06 00 01 02 00 00 00 : 15bytes

With reference to the code snippet of operations shared by you:

What is it that you are doing in TOGGLE_GPO? Session Open, WIP or  MIP?

I suspect that the card is going in corrupted-like state, when it is interrupted during this phase

Assuming that you are not modifying the CC file content in writeRecord().

If possible, share the low-level details of every steps that you are performing, which will help understand better.

Update:

Now that the possibility of Corrupted CC is ruled out, the next step would be to do the same for NDEF TLV, especially the V block where the NDEF File ID, Max. NDEF size and Read/Write Access of NDEF File are stored, by comparing Working and Corrupted state values.

Identify the step, where upon occurring error the card goes to corrupted state. This could be achieved by logging every step. If the card gets corrupted on interruption at a specific step consistently, then it will narrow down the hunt.

Try to SET the StateControl, when the card is in corrupted state. This is just a random thought, but might help.

Cheers!

Body:
We have an Android application that communicates with an NFC tag on a custom hardware device. The hardware device can also communicate and perform operations on the tag mounted to it.

The Android application communicates with the NFC tag in two ways:

IsoDep#transceive(byte[]) for triggering a power cycle of the hardware device.

Ndef#writeNdefMessage(NdefMessage) for writing an NdefMessage/NdefRecord with some user data.

Functionally, these operations look something akin to:

private static final byte[] NDEF_SELECT_APP_FRAME = new byte[] {
    (byte) 0x00, (byte) 0xA4, (byte) 0x04,
    (byte) 0x00, (byte) 0x07, (byte) 0xD2,
    (byte) 0x76, (byte) 0x00, (byte) 0x00,
    (byte) 0x85, (byte) 0x01, (byte) 0x01
};

private static final byte[] SYSTEM_FILE_SELECT = new byte[] {
    (byte) 0x00, (byte) 0xA4, (byte) 0x00,
    (byte) 0x0C, (byte) 0x02, (byte) 0xE1,
    (byte) 0x01
};

private static final byte[] TOGGLE_GPO = new byte[] {
    (byte) 0xA2, (byte) 0xD6, (byte) 0x00,
    (byte) 0x1F, (byte) 0x01, (byte) 0x00
};

boolean recordSuccess = writeRecord(tag, intent, context);
if (recordSuccess) {
    boolean success = transceive(NDEF_SELECT_APP_FRAME, tag, context)
            && transceive(SYSTEM_FILE_SELECT, tag, context)
            && transceive(TOGGLE_GPO, tag, context);
    if (success) {
        // Success!
    } else {
        // Error!
    }
}

We've found that, very occasionally, it seems possible that I/O can be interrupted while the Ndef data is being written (we're not sure why, but we presume pulling the phone away from the tag at just the right time is the reason). This seems to result in the tag being in a "corrupted"-like state, where the previous Ndef data can no longer be found on the tag. In fact, tag.getTechList() won't even list Ndef as an available technology on the tag, though it was originally available.

All further attempts to write Ndef data to the tag will then fail because Ndef.get(tag) will return null.

As far as I'm aware, the normal procedure from this point would be to reformat the tag using NdefFormatable. However, NdefFormatable is not listed as a technology type in tag.getTechList(), and so NdefFormatable.get(tag) also returns null.

Questions:

Why is the tag seemingly becoming corrupted/erased?

Why is Ndef not listed as a tag technology after corruption, even though the tag originally supported it?

How can we recover from this state, given that NdefFormatable.get(tag) seems to return null?

EDIT: The NFC chip appears to be a M24SR04-Y. The specification sheet can be found here: https://www.st.com/resource/en/datasheet/m24sr04-g.pdf.

Capability Container contents shown by TagInfo app:

# Capability Container (CC) file content:
Mapping version 2.0
CC length: 15 bytes
Maximum Le value: 246 bytes
Maximum Lc value: 246 bytes
NDEF File Control TLV:
* Length: 6 bytes
* NDEF file ID: 0x0001
* Maximum NDEF data size: 512 bytes
* NDEF access: Read & Write
[0] 00 0F 20 00 F6 00 F6 04 06 00 01 02 00 00 00    |.. ............ |


来源: stackexchange

问:
Samsung TV Duplicates Permission Websocket
I am developing a samsung remote app and using websockets to connect to the samsung tv. I am opening socket through this url "wss://ip:8002/api/v2/channels/samsung.remote.control?name=". All of this works fine but there is an issue that the TV asks for the permission everytime I try to open connection through websocket. I have seen other competitor apps and in these apps the TV only asks for permission for the first time.

Can anyone help me with this ?

答:
I have figured this out. All you have to do is add a token in the socket URL. When you connect to the TV for the first time or without having any token in the URL, the TV responds with a dictionary having that "Token" as a key/Value pair.
Just use that token while connecting to the TV.

SAMPLE URL:-
wss://ip:8002/api/v2/channels/samsung.remote.control?name=someName&token=tokenValue

ContentLicense: CC BY-SA 4.0


问:
redis Python catching exception that doesn't inherit from BaseException
We're seeing exceptions in our log like the following:

```<code>ERROR Exception ignored in: <function Connection.__del__ at 0x7f9b70a5cc20>
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.7/site-packages/redis/connection.py", line 537, in __del__
File "/app/.heroku/python/lib/python3.7/site-packages/redis/connection.py", line 667, in disconnect
TypeError: catching classes that do not inherit from BaseException is not allowed
</code>```

According to the Redis source code, the offending line is the except in the following snippet:

```<code>try:
    if os.getpid() == self.pid:
        shutdown(self._sock, socket.SHUT_RDWR)
    self._sock.close()
except socket.error:
    pass
</code>```

Which would indicate that socket.exception doesn't inherit from BaseException. However, as far as I can tell (based on the docs and the mro class method), socket.exception does inherit from BaseException.

Why is this happening? What can I do to prevent it?

By the way, our code doesn't call Redis directly. We are using Redis Queue (rq), which is implemented using Redis.

答:
This would happen if you didn't close the redis client explicitly. That's why you saw __del__ in the traceback.

I'm not using rq but I'll take celery as an example, yet the idea could also be applied to rq.

# tasks/__init__.py
from celeryapp import redis_client

@worker_shutdown.connect # this signal means it's about to shut down the worker
def cleanup(**kwargs):
    redis_client.close() # without this you may see error

# celeryapp.py
from celery import Celery
import redis

app = Celery(config_source="celeryconfig")
redis_client = redis.StrictRedis()
```

Body:
We're seeing exceptions in our log like the following:

ERROR Exception ignored in: <function Connection.__del__ at 0x7f9b70a5cc20>
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.7/site-packages/redis/connection.py", line 537, in __del__
File "/app/.heroku/python/lib/python3.7/site-packages/redis/connection.py", line 667, in disconnect
TypeError: catching classes that do not inherit from BaseException is not allowed

According to the Redis source code, the offending line is the except in the following snippet:

try:
    if os.getpid() == self.pid:
        shutdown(self._sock, socket.SHUT_RDWR)
    self._sock.close()
except socket.error:
    pass

Which would indicate that socket.exception doesn't inherit from BaseException. However, as far as I can tell (based on the docs and the mro class method), socket.exception does inherit from BaseException.

Why is this happening? What can I do to prevent it?

By the way, our code doesn't call Redis directly. We are using Redis Queue (rq), which is implemented using Redis.


问:
I have a problem with getting a geolocation on flutter
I' am trying to get geolocation and then push it on other route, but it returns me smth like:

W/ActivityThread(27303): SCHED: razewp.covid19_20/.MainActivity [81, r=36ms, a=8ms, w=31795ms]

here's code:
its my first file loc_get.dart

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

class LocationGetter {
  var test;

  LocationGetter({
    this.test,
  });

  Future<void> getLoc() async {
    final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }
}
</code>```

this is my loc.dart:

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

class Location extends StatefulWidget {
  @override
  _LocationState createState() => _LocationState();
}

class _LocationState extends State<Location> {

  void setupLoc() async {
    LocationGetter location = LocationGetter(
      test: '',
    );

    await location.getLoc();

    Navigator.pushReplacementNamed(context, '/loading', arguments: {
      'test': location.test,
    });
  }

  @override
  void initState() {
    super.initState();
    setupLoc();
  }

  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Center(
          child: Text('Getting location...')
        ),
      )
    );
  }
}

</code>```

How can I fix it? Is there any ways? I'm debugging on my MI 8 SE phone

答:
Try to change

```<code>  Future<void> getLoc() async {
final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
</code>```

}

to

```<code>      Future<void> getLoc() async {
final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
this.test=position;
  }
</code>```

Body:
I' am trying to get geolocation and then push it on other route, but it returns me smth like:

W/ActivityThread(27303): SCHED: razewp.covid19_20/.MainActivity [81, r=36ms, a=8ms, w=31795ms]

here's code:
its my first file loc_get.dart

import 'package:geolocator/geolocator.dart';

class LocationGetter {
  var test;

  LocationGetter({
    this.test,
  });

  Future<void> getLoc() async {
    final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }
}

this is my loc.dart:

import 'package:flutter/material.dart';
import 'package:covid19_20/pages/loc_get.dart';

class Location extends StatefulWidget {
  @override
  _LocationState createState() => _LocationState();
}

class _LocationState extends State<Location> {

  void setupLoc() async {
    LocationGetter location = LocationGetter(
      test: '',
    );

    await location.getLoc();

    Navigator.pushReplacementNamed(context, '/loading', arguments: {
      'test': location.test,
    });
  }

  @override
  void initState() {
    super.initState();
    setupLoc();
  }

  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Center(
          child: Text('Getting location...')
        ),
      )
    );
  }
}

How can I fix it? Is there any ways? I'm debugging on my MI 8 SE phone

Body:
Try to change

  Future<void> getLoc() async {
final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

}

to

      Future<void> getLoc() async {
final position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
this.test=position;
  }


问:
Sorting std::unordered_map by key
How can I sort an unordered_map by key? I need to print an unordered_map sorted by key.

答:
```<code>std::unordered_map<int, int> unordered;

std::map<int, int> ordered(unordered.begin(), unordered.end());
for(auto it = ordered.begin(); it != ordered.end(); ++it)
     std::cout << it->second;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sorting std::unordered_map by key


问:
Why doesn't SQL Server allow me to enable the mixed authentication mode so I can use the sa user to assign roles to the other users?
I am trying to install TFS on the server but it requires to have the user SYSADMIN role which can only be assigned using the sa user login.

I am using SQL Server 2014 Express. To enable the sa user, I tried enabling the mixed mode authentication but I get this error:

The EXECUTE permission was denied on the object 'xp_instance_regwrite', database 'mssqlsystemresource', schema 'sys'. (Microsoft SQL Server, Error: 229)

How do I fix that?

Update:

The problem is that I am Windows User and logging in with windows authentication. So using that user I am not able to assign any roles to myself or other user.

答:
You can use an existing installation of SQL Server for Azure DevOps Server/TFS. To do so, you need administrative credentials granted by the SQL Server administrator. You must be a member of the sysadmin server role in SQL Server to install and configure Azure DevOps Server/TFS. So you need to contact SQL Server administrator and grant your account appropriate permission to install Azure DevOps Server/TFS.

If you want to start a new installation of SQL Server, you could refer to the following link:

https://learn.microsoft.com/en-us/azure/devops/server/install/sql-server/install-sql-server?view=azure-devops


问:
Windows service does not capture shutdown event C/C++
I created a small windows service to capture some events, including the system shutdown. Every time I turn off the computer, the service event is not called. But when I restart the computer the event works normally.

I already tried to use: SERVICE_ACCEPT_PRESHUTDOWN + SERVICE_CONTROL_PRESHUTDOWN and was not successful.

How could I catch the computer shutdown event?

Ps: After compiling I register the service with the following command: sc.exe create "ZSimpleService" binPath = "C:\path\ZSimpleService.exe"

Edit 1: I'm using windows 10

Code:

```<code>SERVICE_STATUS g_ServiceStatus = { 0 };
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam);
DWORD WINAPI CtrlHandlerEx(DWORD CtrlCode, DWORD eventType, LPVOID eventData, LPVOID context);

#define SERVICE_NAME _T("ZSimpleService")

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv) {

    g_StatusHandle = RegisterServiceCtrlHandlerEx(SERVICE_NAME, CtrlHandlerEx,
    NULL);

    if (g_StatusHandle == NULL) {
        goto EXIT;
    }

    // Tell the service controller we are starting
    ZeroMemory( & g_ServiceStatus, sizeof(g_ServiceStatus));

    g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
            | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_SESSIONCHANGE
            | SERVICE_ACCEPT_SHUTDOWN;
    g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwServiceSpecificExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        //...
    }

    g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (g_ServiceStopEvent == NULL) {
        //...
        goto EXIT;
    }

    g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        //...
    }

    HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);

    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(g_ServiceStopEvent);

    g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 3;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {

    }

    EXIT: return;
}

void suspending() {
    FILE *file = fopen("C:\\test\\suspending.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void logoff() {
    FILE *file = fopen("C:\\test\\logoff.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void lock_session() {
    FILE *file = fopen("C:\\test\\lock_session.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void poweroff() {
    FILE *file = fopen("C:\\test\\poweroff.txt", "w+");
    if (file)
        fprintf(file, "...");
}

DWORD WINAPI CtrlHandlerEx(DWORD CtrlCode, DWORD eventType, LPVOID eventData,
        LPVOID context) {
    switch (CtrlCode) {

    case SERVICE_CONTROL_STOP: {
        g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
        g_ServiceStatus.dwWin32ExitCode = 0;
        g_ServiceStatus.dwCheckPoint = 0;
        g_ServiceStatus.dwWaitHint = 0;

        if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
            //...
        }

        SetEvent(g_ServiceStopEvent);

        return NO_ERROR;
    }
    case SERVICE_CONTROL_POWEREVENT: {
        if (eventType == PBT_APMQUERYSUSPEND) {
            //Computer is suspending
            suspending();

        }
        return NO_ERROR;
    }
    case SERVICE_CONTROL_SESSIONCHANGE: {
        switch (eventType) {
        case WTS_SESSION_LOGOFF:
            //User is logging off
            logoff();
            break;
        case WTS_SESSION_LOCK:
            //User locks the session
            lock_session();
            break;
        }
        return NO_ERROR;
    }
    case SERVICE_CONTROL_SHUTDOWN: {
        //Computer is shutting down
        poweroff();

        return NO_ERROR;
    }
    default:
        return ERROR_CALL_NOT_IMPLEMENTED;
    }

}

DWORD WINAPI ServiceWorkerThread(LPVOID lpParam) {

    while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0) {

        //many cool code....

        Sleep(3000);
    }

    return 0;
}

DWORD RunService() {
    SERVICE_TABLE_ENTRY serviceTable[] = { { SERVICE_NAME, ServiceMain },
            { 0, 0 } };

    if (StartServiceCtrlDispatcher(serviceTable)) {
        return 0;
    } else {
        DWORD erro = GetLastError();

        //handler erro...

        return 1;
    }
}

int _tmain(int argc, TCHAR *argv[]) {
    RunService();
    return 0;
}
</code>```

答:
When the fast startup option enabled, click start menu -> shutdown will put the machine into sleep mode/hibernation instead of shutdown. But restart menu isn't affected. (And shuting down from command line isn't affected too as we already found.)

So you can disable fast startup to solve this issue.

Body:
I created a small windows service to capture some events, including the system shutdown. Every time I turn off the computer, the service event is not called. But when I restart the computer the event works normally.

I already tried to use: SERVICE_ACCEPT_PRESHUTDOWN + SERVICE_CONTROL_PRESHUTDOWN and was not successful.

How could I catch the computer shutdown event?

Ps: After compiling I register the service with the following command: sc.exe create "ZSimpleService" binPath = "C:\path\ZSimpleService.exe"

Edit 1: I'm using windows 10

Code:

SERVICE_STATUS g_ServiceStatus = { 0 };
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
DWORD WINAPI ServiceWorkerThread(LPVOID lpParam);
DWORD WINAPI CtrlHandlerEx(DWORD CtrlCode, DWORD eventType, LPVOID eventData, LPVOID context);

#define SERVICE_NAME _T("ZSimpleService")

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv) {

    g_StatusHandle = RegisterServiceCtrlHandlerEx(SERVICE_NAME, CtrlHandlerEx,
    NULL);

    if (g_StatusHandle == NULL) {
        goto EXIT;
    }

    // Tell the service controller we are starting
    ZeroMemory( & g_ServiceStatus, sizeof(g_ServiceStatus));

    g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP
            | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_SESSIONCHANGE
            | SERVICE_ACCEPT_SHUTDOWN;
    g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwServiceSpecificExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        //...
    }

    g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (g_ServiceStopEvent == NULL) {
        //...
        goto EXIT;
    }

    g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        //...
    }

    HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);

    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(g_ServiceStopEvent);

    g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 3;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {

    }

    EXIT: return;
}

void suspending() {
    FILE *file = fopen("C:\\test\\suspending.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void logoff() {
    FILE *file = fopen("C:\\test\\logoff.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void lock_session() {
    FILE *file = fopen("C:\\test\\lock_session.txt", "w+");
    if (file)
        fprintf(file, "...");
}

void poweroff() {
    FILE *file = fopen("C:\\test\\poweroff.txt", "w+");
    if (file)
        fprintf(file, "...");
}

DWORD WINAPI CtrlHandlerEx(DWORD CtrlCode, DWORD eventType, LPVOID eventData,
        LPVOID context) {
    switch (CtrlCode) {

    case SERVICE_CONTROL_STOP: {
        g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
        g_ServiceStatus.dwWin32ExitCode = 0;
        g_ServiceStatus.dwCheckPoint = 0;
        g_ServiceStatus.dwWaitHint = 0;

        if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
            //...
        }

        SetEvent(g_ServiceStopEvent);

        return NO_ERROR;
    }
    case SERVICE_CONTROL_POWEREVENT: {
        if (eventType == PBT_APMQUERYSUSPEND) {
            //Computer is suspending
            suspending();

        }
        return NO_ERROR;
    }
    case SERVICE_CONTROL_SESSIONCHANGE: {
        switch (eventType) {
        case WTS_SESSION_LOGOFF:
            //User is logging off
            logoff();
            break;
        case WTS_SESSION_LOCK:
            //User locks the session
            lock_session();
            break;
        }
        return NO_ERROR;
    }
    case SERVICE_CONTROL_SHUTDOWN: {
        //Computer is shutting down
        poweroff();

        return NO_ERROR;
    }
    default:
        return ERROR_CALL_NOT_IMPLEMENTED;
    }

}

DWORD WINAPI ServiceWorkerThread(LPVOID lpParam) {

    while (WaitForSingleObject(g_ServiceStopEvent, 0) != WAIT_OBJECT_0) {

        //many cool code....

        Sleep(3000);
    }

    return 0;
}

DWORD RunService() {
    SERVICE_TABLE_ENTRY serviceTable[] = { { SERVICE_NAME, ServiceMain },
            { 0, 0 } };

    if (StartServiceCtrlDispatcher(serviceTable)) {
        return 0;
    } else {
        DWORD erro = GetLastError();

        //handler erro...

        return 1;
    }
}

int _tmain(int argc, TCHAR *argv[]) {
    RunService();
    return 0;
}


问:
Using Luhn's module I am having a problem with IF statements
```<code>import luhn
from luhn import *

#BIN Must Be 6-Digits Long.
def gen():
  BIN = input("Enter A BIN Number: ")
  output = []
  for number in BIN:
    output.append(number)
  output = [int(num) for num in output]
  return (output)
BIN = gen()
if BIN <6 and len(BIN) is not 8:
    print('Invalid BIN!')
else:
    print('BIN Added To Directory!')

gen()
</code>```

Specifically in the 'if' part my intention is that the 'BIN' which should be an integer is less than or greater than 6 print 'invalid' else print 'added to directory'.  In addition, overall what Im looking for is if the BIN is not 6 digits long or greater than 6 digits long print 'error'.

答:
I think the problem is that you expect BIN to be a number and a list at the same time. So, in the if condition you are checking whether BIN is a number less than 6 and at the same time checking the length of it.

I figured you might want to perform both operations on the same line. So, here is what I suggest; there is no need to change the type of BIN. It's better to use it as a str just like so:

```<code>BIN = input("Enter A BIN Number: ")
if eval(BIN) <6 and len(BIN) != 8:
    print('Invalid BIN!')
else:
    print('BIN Added To Directory!')
</code>```

Body:
import luhn
from luhn import *

#BIN Must Be 6-Digits Long.
def gen():
  BIN = input("Enter A BIN Number: ")
  output = []
  for number in BIN:
    output.append(number)
  output = [int(num) for num in output]
  return (output)
BIN = gen()
if BIN <6 and len(BIN) is not 8:
    print('Invalid BIN!')
else:
    print('BIN Added To Directory!')

gen()

Specifically in the 'if' part my intention is that the 'BIN' which should be an integer is less than or greater than 6 print 'invalid' else print 'added to directory'.  In addition, overall what Im looking for is if the BIN is not 6 digits long or greater than 6 digits long print 'error'.

Body:
I think the problem is that you expect BIN to be a number and a list at the same time. So, in the if condition you are checking whether BIN is a number less than 6 and at the same time checking the length of it.

I figured you might want to perform both operations on the same line. So, here is what I suggest; there is no need to change the type of BIN. It's better to use it as a str just like so:

BIN = input("Enter A BIN Number: ")
if eval(BIN) <6 and len(BIN) != 8:
    print('Invalid BIN!')
else:
    print('BIN Added To Directory!')


问:
JS function that compare today date to array of birthdays
I'm trying to create a JS function that compares today's date to an array of birthdays and alert users if today is someone's birthday. Below is my code;</p>

```<code>const birthdays = [
  { name: "Bob Marley", birthmonth: "06", birthdate: "01" },
  { name: "Peter Pan", birthmonth: "08", birthdate: "04" },
];

const today = new Date();

if (
  today.getDate() === birthdays.birthdate &&
  today.getMonth() === birthdays.birthmonth
) {
  alert("Happy Birthday!" + birthdays.name);
} else {
  alert("Have a nice day!");
}
</code>```

答:
birtdays its array for solutions in task

```<code>const birthdays = [
  { name: "Bob Marley", birthmonth: 5, birthdate: 1 },
  { name: "Peter Pan", birthmonth: 7, birthdate: 4 },
];

const today = new Date();

  birthdays.find((it) => {
    if(it.birthdate === today.getDay() && it.birthmonth === today.getMonth())
    {
      return alert("Happy Birthday!" + it.name)
    } else {
    alert("Have a nice day!");
    }
})
</code>```

and for your comments

```<code>const newB = birthdays.reduce((acc, rec) => {
  if (rec.birthdate === today.getDay() && rec.birthmonth === today.getMonth()){
    return acc.concat(rec.name)
  } return acc
},[])

if (newB.length > 0){
  alert("Happy Birthday!" + newB)
} else (
  alert("Have a nice day!")
)
</code>```

Body:
I'm trying to create a JS function that compares today's date to an array of birthdays and alert users if today is someone's birthday. Below is my code;

const birthdays = [
  { name: "Bob Marley", birthmonth: "06", birthdate: "01" },
  { name: "Peter Pan", birthmonth: "08", birthdate: "04" },
];

const today = new Date();

if (
  today.getDate() === birthdays.birthdate &&
  today.getMonth() === birthdays.birthmonth
) {
  alert("Happy Birthday!" + birthdays.name);
} else {
  alert("Have a nice day!");
}

Body:
birtdays its array for solutions in task

const birthdays = [
  { name: "Bob Marley", birthmonth: 5, birthdate: 1 },
  { name: "Peter Pan", birthmonth: 7, birthdate: 4 },
];

const today = new Date();

  birthdays.find((it) => {
    if(it.birthdate === today.getDay() && it.birthmonth === today.getMonth())
    {
      return alert("Happy Birthday!" + it.name)
    } else {
    alert("Have a nice day!");
    }
})

and for your comments

const newB = birthdays.reduce((acc, rec) => {
  if (rec.birthdate === today.getDay() && rec.birthmonth === today.getMonth()){
    return acc.concat(rec.name)
  } return acc
},[])

if (newB.length > 0){
  alert("Happy Birthday!" + newB)
} else (
  alert("Have a nice day!")
)


问:
creating SQL CREATE TABLE query in R
I have two vectors of column names and column types for SQL table. I would like to parse these to CREATE TABLE query and run it from R to automatically create tables. Here is example:

```<code>DATA:
    col_names <- c("id", "integer", "decimal", "varchar", "logical")
    col_types <- c("int", "int", "decimal(10,4)", "varchar(255)", "int")
</code>```

SQL CREATE TABLE query looks like following:

```<code>"CREATE TABLE test_tbl ( colname1 coltype1, colname2 coltype2, ... )"
</code>```

This can then be run with dbSendQuery from odbc package.

My solution but cumbersome is following and I would like to find easier way to parse names and types to that query format. My tables are getting larger and I don't think it is smart to do my solution for 50+ columns.

```<code>paste0("CREATE TABLE db_tbl ( ",
                        col_names[1], " ", col_types[1], ", ",
                        col_names[2], " ", col_types[2], ", ",
                        col_names[3], " ", col_types[3], ", ",
                        col_names[4], " ", col_types[4], ", ",
                        col_names[5], " ", col_types[5], " )")

"CREATE TABLE db_tbl ( id int, integer int, decimal decimal(10,4), varchar varchar(255), logical int )"
</code>```

答:
You can use paste within paste0

```<code>paste0("CREATE TABLE db_tbl ( ",paste(col_names, col_types, collapse = ","), ')')

#[1] "CREATE TABLE db_tbl ( id int,integer int,decimal decimal(10,4),varchar varchar(255),logical int)"
</code>```

Title: creating SQL CREATE TABLE query in R

Body:
I have two vectors of column names and column types for SQL table. I would like to parse these to CREATE TABLE query and run it from R to automatically create tables. Here is example:

DATA:
    col_names <- c("id", "integer", "decimal", "varchar", "logical")
    col_types <- c("int", "int", "decimal(10,4)", "varchar(255)", "int")

SQL CREATE TABLE query looks like following:

"CREATE TABLE test_tbl ( colname1 coltype1, colname2 coltype2, ... )"

This can then be run with dbSendQuery from odbc package.

My solution but cumbersome is following and I would like to find easier way to parse names and types to that query format. My tables are getting larger and I don't think it is smart to do my solution for 50+ columns.

paste0("CREATE TABLE db_tbl ( ",
                        col_names[1], " ", col_types[1], ", ",
                        col_names[2], " ", col_types[2], ", ",
                        col_names[3], " ", col_types[3], ", ",
                        col_names[4], " ", col_types[4], ", ",
                        col_names[5], " ", col_types[5], " )")

"CREATE TABLE db_tbl ( id int, integer int, decimal decimal(10,4), varchar varchar(255), logical int )"

Body:
You can use paste within paste0

paste0("CREATE TABLE db_tbl ( ",paste(col_names, col_types, collapse = ","), ')')

#[1] "CREATE TABLE db_tbl ( id int,integer int,decimal decimal(10,4),varchar varchar(255),logical int)"


问:
Number splitting
So, my question is how to split the number into vector of its parts?

Example: n = 1000 => vector(1,0,0,0)

I came to this option:

```<code>#include <vector>
#include <cmath>
std::vector<int> split(int number)
{
    int n = number;
    int length = 0;
    while (n > 0)
    {
        length++;
        n /= 10;
    }
    std::vector<int> vec;
    for (int i = 0; i < length; ++i)
    {
        int degree1 = pow(10, length - i);
        int degree2 = pow(10, length - i - 1);
        vec.push_back(number % degree1 / degree2);
    }
    return vec;
}
</code>```

However, I think there is a more appropriate way to do it

答:
A simpler way would be to push the digits into the vector in reverse order (using the n % 10 and n /= 10 operations), then call std::reverse() on the vector when done:

#include <vector>
#include <algorithm>

std::vector<int> split(int number)
{
    std::vector<int> vec;
    while (number > 0) {
        vec.push_back(number % 10);
        number /= 10;
    }
    std::reverse(vec.begin(), vec.end());
    return vec;
}
```

Title: Number splitting

Body:
So, my question is how to split the number into vector of its parts?

Example: n = 1000 => vector(1,0,0,0)

I came to this option:

#include <vector>
#include <cmath>
std::vector<int> split(int number)
{
    int n = number;
    int length = 0;
    while (n > 0)
    {
        length++;
        n /= 10;
    }
    std::vector<int> vec;
    for (int i = 0; i < length; ++i)
    {
        int degree1 = pow(10, length - i);
        int degree2 = pow(10, length - i - 1);
        vec.push_back(number % degree1 / degree2);
    }
    return vec;
}

However, I think there is a more appropriate way to do it


问:
how to check if goBack() function is doable in react navigation?
I have a back button that takes the user a screen back, but when there are no screens left to go back, I want it to do something else so this is my code:

```<code><Button onPress={()=>{
   if(CanGoBack){ // imaginary 'CanGoBack' variable
     this.props.navigation.goBack()
   }else{
     this.doSomething()
   }
}}/>
</code>```

how can I achieve this?

答: On React navigation 5, there is a canGoBack() function which is super helpful in this case.

Body:
I have a back button that takes the user a screen back, but when there are no screens left to go back, I want it to do something else so this is my code:

<Button onPress={()=>{
   if(CanGoBack){ // imaginary 'CanGoBack' variable
     this.props.navigation.goBack()
   }else{
     this.doSomething()
   }
}}/>

how can I achieve this?


问:
Avoiding Global State
Currently I'm writing an app. If I want to avoid Singletons, do I have to simply pass references of everything around?

For example,

I have a "main" class.

Class: Main

+---- Screen

+---- Camera

+---- Terrain

+---- Vehicle

+---- PhysicsWorld

It contains my Camera, Terrain, and Vehicle,etc classes.  Now, I have issues when I'm creating say, the Terrain object.  Terrain wants to access Main classes Screen object so it can add its Terrain Graphics to the screen.  It also wants to know about the Camera object for when it is drawing so it knows what scale to draw it.  It also wants to know about my PhysicsWorld object so it can add itself to the physics engine.

Do I have to always lug these objects back and forth between constructors?  I mean, when I create a Terrain object, do I simply have to pass around my screen object, my physicsWorld, camera, etc?

Another random scenario I have, is now.. inside my Vehicle class I need to call a Restart() method on my Main class.  Does this mean I have to pass an instance of main to Vehicle?  Really??

It feels cumbersome to constantly have to pass 4-5 things to my classes, especially in my scenario now where almost every in-game object I have needs a screen, physics, camera info, etc.

Any suggestions?

答:
I have the exact same problem (also in actionscript 3, coincidentally).

I have been working on an RTS for flash and had found myself needing to pass around large numbers of references to each new class (e.g., gameGrid, currentSelection, visibleUnits, etc.).

I eventually realised that what I really should be doing is to have every class maintain it's own properties, and instead pass around references to these classes, (well objects).

But anyway, now what I'm doing is having static variables containing references to commonly used objects such as the main stage, interface, engine and display area inside a class called RTSGlobals. I'm also putting constants such as the screen size in there.

I know this doesn't really answer your question, but I figure sometimes it is worth ignoring a bit of OOP good practice in favour of an efficient solution.

If someone has a does have a good practice solution though, please tell :)

OwnerDisplayName: KingNestor

ContentLicense: CC BY-SA 2.5

Title: Avoiding Global State

LastEditorDisplayName: KingNestor

OwnerDisplayName: Aaron Cowie


问:
Is there a way to compare the fields from two different queries in TFS?
I have a requirement where I need to compare two different Queries related to Different Area Path (Different Projects).

Both the projects are working on the same application and to avoid any object conflict, we are updating UDF field with the Integration# (Example INT-XXX), as part of this comparison, we need to see if there are any INT# where both the projects have some stories logged.

We are using TFS 2017. Please advise.

答:
There is no such way to achieve this in TFS.

You may build an application to do it through Work item rest API.

Another workaround is exporting all queries and related fields to Excel. Finally use Excel to handle the comparison.

You can export the query result to Excel from Team Explorer:

Another way is saving the query from Web Portal, then create report
from Excel directly by clicking Team tab and go to New List to
connect the team project and select the saved query result:


问:
Anaconda: Despite of installing can't import ibm_db
I am able to install ibm_dbpackage in order to access DB2 from Jupyter notebook:

```<code>!pip install ibm_db
Requirement already satisfied: ibm_db in /anaconda2/lib/python2.7/site-packages (2.0.9)
</code>```

but while trying to import there's an error:

```<code>import ibm_db

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-2-fe3bb08c8a05> in <module>()
----> 1 import ibm_db

ModuleNotFoundError: No module named 'ibm_db'
</code>```

Restarted the Kernel couple of times but it also had no impact.
Anything that I am missing here?

Update:

Was able to resolve the issue by executing the below in Jupyter:

```<code>!pip uninstall ibm_db
</code>```

and then

```<code>!conda install ibm_db -c anacharsis
</code>```

答:
You need to enter into the environment where you have Python3.7 installed.

Once inside

pip uninstall ibm_db
        once ibm_db is uninstalled

conda install -c conda-forge ibm_db
      This will download and install the packages from Anaconda site

navigate to site-packages- open terminal

cd /opt/anaconda3/lib/python3.7/site-packages
        change name for the lib
        install_name_tool -change libdb2.dylib /opt/anaconda3/lib/python3.7/site-packages/clidriver/lib/libdb2.dylib ibm_db.cpython-37m-darwin.so

ln -s clidriver/lib/libdb2.dylib libdb2.dylib

Restart terminal and run

import ibm_db

voila!!!

Body:
I am able to install ibm_dbpackage in order to access DB2 from Jupyter notebook:

!pip install ibm_db
Requirement already satisfied: ibm_db in /anaconda2/lib/python2.7/site-packages (2.0.9)

but while trying to import there's an error:

import ibm_db

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-2-fe3bb08c8a05> in <module>()
----> 1 import ibm_db

ModuleNotFoundError: No module named 'ibm_db'

Restarted the Kernel couple of times but it also had no impact.
Anything that I am missing here?

Update:

Was able to resolve the issue by executing the below in Jupyter:

!pip uninstall ibm_db

and then

!conda install ibm_db -c anacharsis


问:
Avoid multiple calls to database with C# & EF Core
I have a requirement where I need to display a value based on Id. For that, I am making multiple calls to the database, to different tables. Is it possible to reduce the number of calls?

I have switch conditions based on which call to DB occurs. Below is sample

```<code>foreach (var items in table1)
{
    foreach (var item in items.List)
    {
         switch (item.condition)
         {
             case condition1:
             case condition2:
                 item.nvalue= string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
                 break;

             case condition3:
                 item.nvalue= string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
                 break;

             case condition4:
                 item.nvalue= string.Join(",", _context.tabl3.Where(x => someIds.Contains(x.Id)).Select(x => x.oldvalue));
                 break;

             case condition5:
                 item.nvalue= string.Join(",", _context.tabl4.Where(x=>textIds.Contains(x.Id)).Select(x => x.note));
                 break;

             default:
                 item.nvalue= "";
                 break;
         }
     }
 }
</code>```

Thanks in advance

答:
If you want to reduce your database calls, and if your tables are not too large or they are fundamental tables, you can cache the tables in the memory with Caching Data.
Full Documentation is over here: Documentation or Working with Cache

I hope it will help you to solve your problem. Good luck.

Body:
I have a requirement where I need to display a value based on Id. For that, I am making multiple calls to the database, to different tables. Is it possible to reduce the number of calls?

I have switch conditions based on which call to DB occurs. Below is sample

foreach (var items in table1)
{
    foreach (var item in items.List)
    {
         switch (item.condition)
         {
             case condition1:
             case condition2:
                 item.nvalue= string.Join(",", _context.table1.Where(x => ids.Contains(x.Id)).Select(x => x.Title));
                 break;

             case condition3:
                 item.nvalue= string.Join(",", _context.tabl2.Where(x => secondIds.Contains(x.Id)).Select(x => x.newvalu));
                 break;

             case condition4:
                 item.nvalue= string.Join(",", _context.tabl3.Where(x => someIds.Contains(x.Id)).Select(x => x.oldvalue));
                 break;

             case condition5:
                 item.nvalue= string.Join(",", _context.tabl4.Where(x=>textIds.Contains(x.Id)).Select(x => x.note));
                 break;

             default:
                 item.nvalue= "";
                 break;
         }
     }
 }

Thanks in advance


问:
Storage in laravel says symlink - no such file
I deployed laravel app on shared hosting in public_html/app folder. Here is everything from public folder. In /../../files I have rest of files. When I do php artisan storage:link in files folder my console says

```<code>[ErrorException]
  symlink(): No such file or directory
</code>```

On localhost I upload files to storage/uploads folder. What to do now? I tried to change links but nothing works for me...

答:
Go to config/filesystem.php  in the symbolic links section in my case I removed public_path  function and wrote my own path in it  then run php artisan storage:link command again.

```<code> 'links' => [
    '/var/www/storage' => storage_path('app/public'),
],
</code>```

Worked for me.

Body:
I deployed laravel app on shared hosting in public_html/app folder. Here is everything from public folder. In /../../files I have rest of files. When I do php artisan storage:link in files folder my console says

[ErrorException]
  symlink(): No such file or directory

On localhost I upload files to storage/uploads folder. What to do now? I tried to change links but nothing works for me...

Body:
Go to config/filesystem.php  in the symbolic links section in my case I removed public_path  function and wrote my own path in it  then run php artisan storage:link command again.

 'links' => [
    '/var/www/storage' => storage_path('app/public'),
],

Worked for me.


问:
Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

```<code>//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}
</code>```

With clang++ (version 9.0.1-10) I can compile my code without problem:

```<code>clang++ -Wall prog.cpp
</code>```

but with g++ (version 9.2.1)

```<code>g++ -Wall prog.cpp
</code>```

I get this warning:

```<code>prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^
</code>```

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

答:
A practical solution is to use /* multi-line comments. So code

```<code>/***
 \begin{eqnarray*}
   y_1 &=& x_1 \\
   y_2 &=& x_2
 \end{eqnarray*}
***/
</code>```

You should be interested by literate programming techniques, and by tools like Doxygen.

My recommendation is to try Nuweb (at least if you code on Linux), in particular for your public (and LaTeX documented) header files. You'll code a Nuweb source file (some *.nw file) which would generate LaTeX on one hand, and C code on another (e.g. some header file).

Be aware that using literate programming techniques takes a lot of time.  My personal but limited experience is that they are worth using more on public header files than on implementation details and entire translation units.

Of course, you need to learn more about build automation tools (such as GNU make or ninja) and configure them explicitly for running your nuweb or doxygen executable appropriately.

Body:
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}

With clang++ (version 9.0.1-10) I can compile my code without problem:

clang++ -Wall prog.cpp

but with g++ (version 9.2.1)

g++ -Wall prog.cpp

I get this warning:

prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

Body:
A practical solution is to use /* multi-line comments. So code

/***
 \begin{eqnarray*}
   y_1 &=& x_1 \\
   y_2 &=& x_2
 \end{eqnarray*}
***/

You should be interested by literate programming techniques, and by tools like Doxygen.

My recommendation is to try Nuweb (at least if you code on Linux), in particular for your public (and LaTeX documented) header files. You'll code a Nuweb source file (some *.nw file) which would generate LaTeX on one hand, and C code on another (e.g. some header file).

Be aware that using literate programming techniques takes a lot of time.  My personal but limited experience is that they are worth using more on public header files than on implementation details and entire translation units.

Of course, you need to learn more about build automation tools (such as GNU make or ninja) and configure them explicitly for running your nuweb or doxygen executable appropriately.


问:
how to show only two text boxes at a time
how to show only two textbox only by next and previous button </p>

<p>this is my code,in this code when i click the next button show two textbox and aging when i click show the next two textbox..totally four textbox..i want only two text box per each click.......how can I achieve that ?

    </p>

```<code><script type="text/javascript">
var max=2;//highest number to go to
var currentIndex=0;
function Previous(){
  if(currentIndex>0){
    currentIndex--;
    postClick();
  }
}
function Next(){
  if(currentIndex<max){
    currentIndex++;
    document.getElementById("div").style.display="none"
    postClick();
  }
}
function postClick(){//whatever you want to happen goes here
  var sahan =new Array();
  sahan[currentIndex]==d;
  var d=document.getElementById("div");
  d.innerHTML+="<p><input type='text' name='name"+currentIndex+"[]'>";
  d.innerHTML+="<p><input type='text' name='topic"+currentIndex+"[]'>";
  form1.text1.value=currentIndex;
}
</script>

<form name="form1">
  <input type="button" value="Previous" onclick="Previous()"/>

  <input type="button" value="Next" onclick="Next()"/>

</form>
<div id="div"></div>
</body>
</html>
</code>```

答:
try like this</p>

```<code><script type="text/javascript">
        var max = 1; //highest number to go to
        var currentIndex = 0;
        function btnClick() {
            if (currentIndex == 0) {
                currentIndex++;
                postClick();
            }
        }

        function postClick() {//whatever you want to happen goes here

            var sahan = new Array();
            sahan[currentIndex] == d;
            var d = document.getElementById("div");
            d.innerHTML += "<p><input type='text' name='name" + currentIndex + "[]'>";
            d.innerHTML += "<p><input type='text' name='topic" + currentIndex + "[]'>";
            document.getElementById("div").style.display = "";
        }
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input type="button" value="Previous" onclick="btnClick()" />
        <input type="button" value="Next" onclick="btnClick()" />
        <div id="div">
        </div>
    </div>
    </form>
</code>```

Body:
how to show only two textbox only by next and previous button

this is my code,in this code when i click the next button show two textbox and aging when i click show the next two textbox..totally four textbox..i want only two text box per each click.......how can I achieve that ?

<form name="form1">
  <input type="button" value="Previous" onclick="Previous()"/>

  <input type="button" value="Next" onclick="Next()"/>

</form>

Body:
try like this

<script type="text/javascript">
        var max = 1; //highest number to go to
        var currentIndex = 0;
        function btnClick() {
            if (currentIndex == 0) {
                currentIndex++;
                postClick();
            }
        }

        function postClick() {//whatever you want to happen goes here

            var sahan = new Array();
            sahan[currentIndex] == d;
            var d = document.getElementById("div");
            d.innerHTML += "<p><input type='text' name='name" + currentIndex + "[]'>";
            d.innerHTML += "<p><input type='text' name='topic" + currentIndex + "[]'>";
            document.getElementById("div").style.display = "";
        }
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input type="button" value="Previous" onclick="btnClick()" />
        <input type="button" value="Next" onclick="btnClick()" />
        <div id="div">
        </div>
    </div>
    </form>


问:
Creating widgets using textual templates or a DSL [e.g. YAML or JSX]
Is there a standard flutter pattern / package to instantiate components of UIs by means of specifications stored in YAML-like files?

While I could certainly write this:

```<code>   Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text(
</code>```

I'd probably prefer to load some YAML-like description, which in turn would create this widget hierarchy.

The template/DSL would need to have slots where other widgets could be inserted programmatically and would have to hook up to logic written in code.

Q: Does something like this exist?

答:
There's a substitute for your issue, try here.

With dynamic widget package,you can create dynamic widgets by defining a json string, and also you can add custom click event for the custom widgets.

Hope this helps.

Body:
Is there a standard flutter pattern / package to instantiate components of UIs by means of specifications stored in YAML-like files?

While I could certainly write this:

   Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text(

I'd probably prefer to load some YAML-like description, which in turn would create this widget hierarchy.

The template/DSL would need to have slots where other widgets could be inserted programmatically and would have to hook up to logic written in code.

Q: Does something like this exist?


问:
Receive Response from pop navigator in Flutter
Here is a simple example of code that navigator push for a form called. and pop for an answer.
my goal is to make a pop of an object, not a string, but keeping it that simple still doesn't work.

main.dart:

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

import 'answer.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  String stateData;
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }
</code>```

}

answer.dart:

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

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed: (){
          String holder =  getFormData(context);
          setState(() {
            data = holder;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  String getFormData(BuildContext context) {
    final Future<String> answer =  Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
    answer.then((String value) {
        return value != null? value: 'empty';
      }
    );
  }
}
</code>```

when returning from the form error message is :

'package:flutter/src/widgets/text.dart': Failed assertion: line ...
  pos... 'data!=null': A non-null String must be provided to a Text
  widget.

答:
And here is a code if you want to pass a data object and not a String:

main.dart:

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

import 'answer.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  Data stateData = Data();
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData.load = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Data {
  String load;
}
</code>```

answer.dart:

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

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed:   () async {
          final holder = await  getFormData(context);
          setState(() {
            data = holder.load;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  Future<Data> getFormData(BuildContext context) async {
    final answer =  await Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
        return (Future.value(answer));
  }
}
</code>```

Body:
Here is a simple example of code that navigator push for a form called. and pop for an answer.
my goal is to make a pop of an object, not a string, but keeping it that simple still doesn't work.

main.dart:

import 'package:flutter/material.dart';

import 'answer.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  String stateData;
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }

}

answer.dart:

import 'package:flutter/material.dart';

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed: (){
          String holder =  getFormData(context);
          setState(() {
            data = holder;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  String getFormData(BuildContext context) {
    final Future<String> answer =  Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
    answer.then((String value) {
        return value != null? value: 'empty';
      }
    );
  }
}

when returning from the form error message is :

'package:flutter/src/widgets/text.dart': Failed assertion: line ...
  pos... 'data!=null': A non-null String must be provided to a Text
  widget.

Body:
And here is a code if you want to pass a data object and not a String:

main.dart:

import 'package:flutter/material.dart';

import 'answer.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  Data stateData = Data();
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData.load = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Data {
  String load;
}

answer.dart:

import 'package:flutter/material.dart';

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed:   () async {
          final holder = await  getFormData(context);
          setState(() {
            data = holder.load;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  Future<Data> getFormData(BuildContext context) async {
    final answer =  await Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
        return (Future.value(answer));
  }
}


答:
An even simpler way is to "print" the number into a std::string (e.g. with std::ostringstream or std::to_string()) and copy the characters one by one into your std::vector.

```<code>#include <iostream>
#include <sstream>
#include <vector>

std::vector<int> split(int number)
{
  std::vector<int> vec;
  if (number < 0) return vec;
  std::string text = std::to_string(number);
  for (char c : text) vec.push_back(c - '0');
  return vec;
}

std::ostream& operator<<(std::ostream &out, const std::vector<int> &vec)
{
  for (int i : vec) out << ' ' << i;
  return out;
}

int main()
{
  std::cout << "split(1000):" << split(1000) << '\n';
}
</code>```

Output:

split(1000): 1 0 0 0
```

<p><strong>Live Demo on coliru</strong></p>

<p>Another way is to use <code>operator %</code> (modulo, remainder). With <code>% 10</code> you get the last digit. So, you can separate the digits from right to left. Either insert digits at beginning of vector or (better) push them back and <code>std::reverse</code> the final result.</p>

<p>Sample:</p>

```#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int> split(int number)
{
  std::vector<int> vec;
  if (number >= 0) {
    do {
      vec.push_back(number % 10);
      number /= 10;
    } while (number);
    std::reverse(vec.begin(), vec.end());
  }
  return vec;
}

std::ostream& operator<<(std::ostream &out, const std::vector<int> &vec)
{
  for (int i : vec) out << ' ' << i;
  return out;
}

int main()
{
  std::cout << "split(1000):" << split(1000) << '\n';
}
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>split(1000): 1 0 0 0
</code>```

Live Demo on coliru

Title: Number splitting

Body:
An even simpler way is to "print" the number into a std::string (e.g. with std::ostringstream or std::to_string()) and copy the characters one by one into your std::vector.

#include <iostream>
#include <sstream>
#include <vector>

std::vector<int> split(int number)
{
  std::vector<int> vec;
  if (number < 0) return vec;
  std::string text = std::to_string(number);
  for (char c : text) vec.push_back(c - '0');
  return vec;
}

std::ostream& operator<<(std::ostream &out, const std::vector<int> &vec)
{
  for (int i : vec) out << ' ' << i;
  return out;
}

int main()
{
  std::cout << "split(1000):" << split(1000) << '\n';
}

Output:

split(1000): 1 0 0 0

Live Demo on coliru

Another way is to use operator % (modulo, remainder). With % 10 you get the last digit. So, you can separate the digits from right to left. Either insert digits at beginning of vector or (better) push them back and std::reverse the final result.

Sample:

#include <algorithm>
#include <iostream>
#include <vector>

std::vector<int> split(int number)
{
  std::vector<int> vec;
  if (number >= 0) {
    do {
      vec.push_back(number % 10);
      number /= 10;
    } while (number);
    std::reverse(vec.begin(), vec.end());
  }
  return vec;
}

std::ostream& operator<<(std::ostream &out, const std::vector<int> &vec)
{
  for (int i : vec) out << ' ' << i;
  return out;
}

int main()
{
  std::cout << "split(1000):" << split(1000) << '\n';
}

Output:

split(1000): 1 0 0 0

Live Demo on coliru


问:
Counter not increasing in async map function
I am working with mongodb and nodejs. I have an array of customers I have to create each inside database.

```<code>const promises2 = customers.map(async customer => {
      if (!customer.customerId) {
        const counter = await Counter.findOne({ type: "Customer" });
        console.log({counter});
        const payload = {
          customerId: counter.sequence_value,
        };
        await Customer.create(payload);
        await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
      }
    });
    await Promise.all([...promises2]);
</code>```

The issue is counter is not increasing every time. I am getting same counter in all the created customers. What is the issue here?

Issue is something like this but don't have an answer.

答:
Your map function is not returning a promise.

Try this :

```<code>const promises2 = [];

customers.map((customer) => {
  return new Promise(async (resolve) => {
    if (!customer.customerId) {
      const counter = await Counter.findOne({ type: 'Customer' });
      console.log({ counter });
      const payload = {
        customerId: counter.sequence_value,
      };
      await Customer.create(payload);
      await Counter.findOneAndUpdate({ type: 'Customer' }, { $inc: { sequence_value: 1 } });
    }
    resolve();
  });
});

await Promise.all(promises2);
</code>```

Body:
I am working with mongodb and nodejs. I have an array of customers I have to create each inside database.

const promises2 = customers.map(async customer => {
      if (!customer.customerId) {
        const counter = await Counter.findOne({ type: "Customer" });
        console.log({counter});
        const payload = {
          customerId: counter.sequence_value,
        };
        await Customer.create(payload);
        await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
      }
    });
    await Promise.all([...promises2]);

The issue is counter is not increasing every time. I am getting same counter in all the created customers. What is the issue here?

Issue is something like this but don't have an answer.

Body:
Your map function is not returning a promise.

Try this :

const promises2 = [];

customers.map((customer) => {
  return new Promise(async (resolve) => {
    if (!customer.customerId) {
      const counter = await Counter.findOne({ type: 'Customer' });
      console.log({ counter });
      const payload = {
        customerId: counter.sequence_value,
      };
      await Customer.create(payload);
      await Counter.findOneAndUpdate({ type: 'Customer' }, { $inc: { sequence_value: 1 } });
    }
    resolve();
  });
});

await Promise.all(promises2);


问:
makeStyles show a div when hovering over nested a link
So I am trying to show a div box when a user hovers over the link.

For example:
Say I have an image inside the a href I want a div to float above that and say click here.

React Style code.

```<code>a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },
</code>```

React code

                  Stuff shown on hover

Full code

```<code>import React from 'react';
import clsx from 'clsx';
import { makeStyles,styled } from '@material-ui/core/styles';
//import Typography from '@material-ui/core/Typography';
import { Container, Button, Grid } from '@material-ui/core';
import comedynight from '../images/shows/PrideInjulyFridaynightcomedy2020.png';
import dragnight from '../images/shows/PrideInjulySaturdaynightDrag2020.png';

const drawerWidth = 240;
const DonateButton = styled(Button)({
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
  border: 0,
  borderRadius: 3,
  boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
  color: 'white',
  height: 48,
  width: '100%',
  fontWeight: 'Bold',
  padding: '0 30px',
});

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
  },
  appBar: {
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  hide: {
    display: 'none',
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
  },
  drawerPaper: {
    width: drawerWidth,
  },
  drawerHeader: {
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-end',
  },
  content: {
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: 0,
  },
  contentShift: {
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
    marginLeft: 0,
  },
  a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },
}));

export default function Home() {

    const classes = useStyles();
    const [open] = React.useState(false);

    return(
        <Container>
        <main
        className={clsx(classes.content, {
          [classes.contentShift]: open,
        })}
      >
          <Grid container spacing={3}>
            <Grid item lg={12}>
              <DonateButton>Click here to donate now to support WAAids Council</DonateButton>
            </Grid>
            <Grid item md={6}>
              <a href="/shows/comedy" alt="Friday Comedy Night" className={classes.a}>
              <img src={comedynight} alt="Friday Night Comedy" style={{width:"100%"}}/>
              </a>
              <div id="show" style={{display:'none'}}>Stuff shown on hover</div>
            </Grid>
            <Grid item md={6}>
            <img src={dragnight} alt="Saturday Night Drag" style={{width:"100%"}}/>
            </Grid>
          </Grid>
      </main>
      </Container>
    )
}
</code>```

答:
You can make it using state, but if you want to make it with css then you can use it like this</p>

```<code>a + #show: {
    display: 'none'
}
a:hover + #show: {
    display: 'block'
}
</code>```

Body:
So I am trying to show a div box when a user hovers over the link.

For example:
Say I have an image inside the a href I want a div to float above that and say click here.

React Style code.

a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },

React code

                  Stuff shown on hover

Full code

import React from 'react';
import clsx from 'clsx';
import { makeStyles,styled } from '@material-ui/core/styles';
//import Typography from '@material-ui/core/Typography';
import { Container, Button, Grid } from '@material-ui/core';
import comedynight from '../images/shows/PrideInjulyFridaynightcomedy2020.png';
import dragnight from '../images/shows/PrideInjulySaturdaynightDrag2020.png';

const drawerWidth = 240;
const DonateButton = styled(Button)({
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
  border: 0,
  borderRadius: 3,
  boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
  color: 'white',
  height: 48,
  width: '100%',
  fontWeight: 'Bold',
  padding: '0 30px',
});

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
  },
  appBar: {
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  appBarShift: {
    width: `calc(100% - ${drawerWidth}px)`,
    marginLeft: drawerWidth,
    transition: theme.transitions.create(['margin', 'width'], {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  hide: {
    display: 'none',
  },
  drawer: {
    width: drawerWidth,
    flexShrink: 0,
  },
  drawerPaper: {
    width: drawerWidth,
  },
  drawerHeader: {
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(0, 1),
    // necessary for content to be below app bar
    ...theme.mixins.toolbar,
    justifyContent: 'flex-end',
  },
  content: {
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: 0,
  },
  contentShift: {
    transition: theme.transitions.create('margin', {
      easing: theme.transitions.easing.easeOut,
      duration: theme.transitions.duration.enteringScreen,
    }),
    marginLeft: 0,
  },
  a: {

    '& :hover':{
        '& div#show':{
          display:'block'
        }
    }
  },
}));

export default function Home() {

    const classes = useStyles();
    const [open] = React.useState(false);

    return(
        <Container>

          <Grid container spacing={3}>
            <Grid item lg={12}>
              <DonateButton>Click here to donate now to support WAAids Council</DonateButton>
            </Grid>
            <Grid item md={6}>

Stuff shown on hover

            </Grid>
            <Grid item md={6}>

            </Grid>
          </Grid>

      </Container>
    )
}

Body:
You can make it using state, but if you want to make it with css then you can use it like this

a + #show: {
    display: 'none'
}
a:hover + #show: {
    display: 'block'
}


问:
Displaying UTF-8 Emoji in Java
Say I have the  (devil) emoji.

In 4-byte UTF-8, it's represented like so: \u00f0\u009f\u0098\u0088

However, in Java, it will only print correctly like so: \ud83d\ude08

How would I convert from the first to the second?

UPDATE 2

MNEMO's answer is much simpler, and answers my question, so it's probably better to go with his solution.

UPDATE

Thanks Basil Bourque for the write-up.  It was very interesting.

I found a good reference here: https://github.com/pRizz/Unicode-Converter/blob/master/conversionfunctions.js (particularly the convertUTF82Char() function).

For anyone wandering by here in the future, here's what that looks like in Java:

```<code>public static String fromCharCode(int n) {
    char c = (char)n;
    return Character.toString(c);
}

public static String decToChar(int n) {
    // converts a single string representing a decimal number to a character
    // note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
    // dec: string, the dec codepoint to be converted
    String result = "";
    if (n <= 0xFFFF) {
        result += fromCharCode(n);
    } else if (n <= 0x10FFFF) {
        n -= 0x10000;
        result += fromCharCode(0xD800 | (n >> 10)) + fromCharCode(0xDC00 | (n & 0x3FF));
    } else {
        result += "dec2char error: Code point out of range: " + decToHex(n);
    }

    return result;
}

public static String decToHex(int n) {
    return Integer.toHexString(n).toUpperCase();
}

public static String convertUTF8_toChar(String str) {
    // converts to characters a sequence of space-separated hex numbers representing bytes in utf8
    // str: string, the sequence to be converted
    var outputString = "";
    var counter = 0;
    var n = 0;

    // remove leading and trailing spaces
    str = str.replaceAll("/^\\s+/", "");
    str = str.replaceAll("/\\s+$/", "");
    if (str.length() == 0) {
        return "";
    }

    str = str.replaceAll("/\\s+/g", " ");

    var listArray = str.split(" ");
    for (var i = 0; i < listArray.length; i++) {
        int b = parseInt(listArray[i], 16); // alert('b:'+dec2hex(b));
        switch (counter) {
            case 0:
                if (0 <= b && b <= 0x7F) { // 0xxxxxxx
                    outputString += decToChar(b);
                } else if (0xC0 <= b && b <= 0xDF) { // 110xxxxx
                    counter = 1;
                    n = b & 0x1F;
                } else if (0xE0 <= b && b <= 0xEF) { // 1110xxxx
                    counter = 2;
                    n = b & 0xF;
                } else if (0xF0 <= b && b <= 0xF7) { // 11110xxx
                    counter = 3;
                    n = b & 0x7;
                } else {
                    outputString += "convertUTF82Char: error1 " + decToHex(b) + "! ";
                }
                break;
            case 1:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error2 " + decToHex(b) + "! ";
                }
                counter--;
                outputString += decToChar((n << 6) | (b - 0x80));
                n = 0;
                break;
            case 2:
            case 3:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error3 " + decToHex(b) + "! ";
                }
                n = (n << 6) | (b - 0x80);
                counter--;
                break;
        }
    }

    return outputString.replaceAll("/ $/", "");
}
</code>```

Pretty much a 1-for-1 copy, but it accomplishes my goal.

答:
The SMILING FACE WITH HORNS character () is assigned to code point 128,520 decimal (1F608 hexadecimal) in Unicode.

You have a choice in how to represent that number with a series of octets.

UTF-8 is one way to represent that number with a variable length, using 1-4 octets.

UTF-8 is becoming the dominant encoding in many spheres.

Java source code files are usually written in UTF-8, in my experience, and as discussed here.

UTF-16 is another way, also variable-length, but using either 2 octets or 4.

The Java language uses UTF-16 internally.

UTF-8 is generally preferred over UTF-16, as discussed here.

In most text-editors, you can simply paste the single character  into your source code. When written to a UTF-8 file, the editor will create the necessary series of octets.

When writing this character to a text file, or otherwise serializing to a stream of octets, you can choose to use either UTF-8 or UTF-16. See:

How to write a UTF-8 file with Java?

How to Open File in UTF-8 and Write in Another File in UTF-16

The following are a couple of trials. You can examine the resulting files with a hex editor to see the octets.

UTF-8

This code generates a file in UTF-8 encoding. We find four octets, hex values F0 9F 98 88, decimal values 240 159 152 136.

You can find this code discussed at the Oracle Java Tutorial.

Notice how we specify an encoding for our file, StandardCharsets.UTF_8.

```<code>Path file = Paths.get( "/Users/basilbourque/devil_utf-8.txt" );
Charset charset = StandardCharsets.UTF_8;
String s = "";
try ( BufferedWriter writer = Files.newBufferedWriter( file , charset ) )
{
    writer.write( s , 0 , s.length() );
}
catch ( IOException e )
{
    e.printStackTrace();
}
</code>```

UTF-16

This code generates a file in UTF-16 encoding. We find 6 octets, 4 octets for our single character, plus a prefix of 2 octets for a BOM (FE FF). Our four octets in decimal are 216 061 222 008, in hex are D8 3D DE 08.

Same code as above, but we switched the Charset to StandardCharsets.UTF_16.

```<code>Path file = Paths.get( "/Users/basilbourque/devil_utf-16.txt" );
Charset charset = StandardCharsets.UTF_16;
String s = "";
try ( BufferedWriter writer = Files.newBufferedWriter( file , charset ) )
{
    writer.write( s , 0 , s.length() );
}
catch ( IOException e )
{
    e.printStackTrace();
}
</code>```

About Unicode and encodings

To learn the basics of Unicode and encodings, read the post, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

Title: Displaying UTF-8 Emoji in Java

Body:
Say I have the  (devil) emoji.

In 4-byte UTF-8, it's represented like so: \u00f0\u009f\u0098\u0088

However, in Java, it will only print correctly like so: \ud83d\ude08

How would I convert from the first to the second?

UPDATE 2

MNEMO's answer is much simpler, and answers my question, so it's probably better to go with his solution.

UPDATE

Thanks Basil Bourque for the write-up.  It was very interesting.

I found a good reference here: https://github.com/pRizz/Unicode-Converter/blob/master/conversionfunctions.js (particularly the convertUTF82Char() function).

For anyone wandering by here in the future, here's what that looks like in Java:

public static String fromCharCode(int n) {
    char c = (char)n;
    return Character.toString(c);
}

public static String decToChar(int n) {
    // converts a single string representing a decimal number to a character
    // note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
    // dec: string, the dec codepoint to be converted
    String result = "";
    if (n <= 0xFFFF) {
        result += fromCharCode(n);
    } else if (n <= 0x10FFFF) {
        n -= 0x10000;
        result += fromCharCode(0xD800 | (n >> 10)) + fromCharCode(0xDC00 | (n & 0x3FF));
    } else {
        result += "dec2char error: Code point out of range: " + decToHex(n);
    }

    return result;
}

public static String decToHex(int n) {
    return Integer.toHexString(n).toUpperCase();
}

public static String convertUTF8_toChar(String str) {
    // converts to characters a sequence of space-separated hex numbers representing bytes in utf8
    // str: string, the sequence to be converted
    var outputString = "";
    var counter = 0;
    var n = 0;

    // remove leading and trailing spaces
    str = str.replaceAll("/^\\s+/", "");
    str = str.replaceAll("/\\s+$/", "");
    if (str.length() == 0) {
        return "";
    }

    str = str.replaceAll("/\\s+/g", " ");

    var listArray = str.split(" ");
    for (var i = 0; i < listArray.length; i++) {
        int b = parseInt(listArray[i], 16); // alert('b:'+dec2hex(b));
        switch (counter) {
            case 0:
                if (0 <= b && b <= 0x7F) { // 0xxxxxxx
                    outputString += decToChar(b);
                } else if (0xC0 <= b && b <= 0xDF) { // 110xxxxx
                    counter = 1;
                    n = b & 0x1F;
                } else if (0xE0 <= b && b <= 0xEF) { // 1110xxxx
                    counter = 2;
                    n = b & 0xF;
                } else if (0xF0 <= b && b <= 0xF7) { // 11110xxx
                    counter = 3;
                    n = b & 0x7;
                } else {
                    outputString += "convertUTF82Char: error1 " + decToHex(b) + "! ";
                }
                break;
            case 1:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error2 " + decToHex(b) + "! ";
                }
                counter--;
                outputString += decToChar((n << 6) | (b - 0x80));
                n = 0;
                break;
            case 2:
            case 3:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error3 " + decToHex(b) + "! ";
                }
                n = (n << 6) | (b - 0x80);
                counter--;
                break;
        }
    }

    return outputString.replaceAll("/ $/", "");
}

Pretty much a 1-for-1 copy, but it accomplishes my goal.

Body:
The SMILING FACE WITH HORNS character () is assigned to code point 128,520 decimal (1F608 hexadecimal) in Unicode.

You have a choice in how to represent that number with a series of octets.

UTF-8 is one way to represent that number with a variable length, using 1-4 octets.

UTF-8 is becoming the dominant encoding in many spheres.

Java source code files are usually written in UTF-8, in my experience, and as discussed here.

UTF-16 is another way, also variable-length, but using either 2 octets or 4.

The Java language uses UTF-16 internally.

UTF-8 is generally preferred over UTF-16, as discussed here.

In most text-editors, you can simply paste the single character  into your source code. When written to a UTF-8 file, the editor will create the necessary series of octets.

When writing this character to a text file, or otherwise serializing to a stream of octets, you can choose to use either UTF-8 or UTF-16. See:

How to write a UTF-8 file with Java?

How to Open File in UTF-8 and Write in Another File in UTF-16

The following are a couple of trials. You can examine the resulting files with a hex editor to see the octets.

UTF-8

This code generates a file in UTF-8 encoding. We find four octets, hex values F0 9F 98 88, decimal values 240 159 152 136.

You can find this code discussed at the Oracle Java Tutorial.

Notice how we specify an encoding for our file, StandardCharsets.UTF_8.

Path file = Paths.get( "/Users/basilbourque/devil_utf-8.txt" );
Charset charset = StandardCharsets.UTF_8;
String s = "";
try ( BufferedWriter writer = Files.newBufferedWriter( file , charset ) )
{
    writer.write( s , 0 , s.length() );
}
catch ( IOException e )
{
    e.printStackTrace();
}

UTF-16

This code generates a file in UTF-16 encoding. We find 6 octets, 4 octets for our single character, plus a prefix of 2 octets for a BOM (FE FF). Our four octets in decimal are 216 061 222 008, in hex are D8 3D DE 08.

Same code as above, but we switched the Charset to StandardCharsets.UTF_16.

Path file = Paths.get( "/Users/basilbourque/devil_utf-16.txt" );
Charset charset = StandardCharsets.UTF_16;
String s = "";
try ( BufferedWriter writer = Files.newBufferedWriter( file , charset ) )
{
    writer.write( s , 0 , s.length() );
}
catch ( IOException e )
{
    e.printStackTrace();
}

About Unicode and encodings

To learn the basics of Unicode and encodings, read the post, The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).


问:
Effective use of a DLL
Up until now I've only used DLL's as a source for plugins in my applications.

But I know that using DLL's will allow me to update my program "client side" a lot easier the re-downloading the main EXE all time.

The problem is, I cant seem to find an effective way to use dll's in my application, or to use them in a way that would impact the program, but not force me to change the way the entire program works.

The "application" in this instance is an XNA Game.

So for example, I have three main classes (excluding the main game Class)

Units
Players
Networking.

I would like to have the Units/Players in one DLL, and the Networking in another DLL, or at least move the networking to a separate DLL, But the way the networking class works and is coded would require the DLL to have a reference to the Game, and the Game to have a reference to the DLL, which is prevented in Visual Studio to prevent circular dependencies.

My question, is how can I effectively use a DLL to store my networking class, I have a couple of ideas, but I'm not sure how feasible any of them is yet.

What I would like, if possible, would be to have the entire networking instance running from the dll, sending receiving, and updating the game data as needed.

But so far I have only been able to come up with a way to have the receiving and sending in the Main game.exe and move the handling functions into the dll, and even then, the handling functions cannot (easily) communicate with the game.

I also thought of using the Plugin System, but that requires me to use Delegates for all my functions that I want to use in the Networking DLL, and seems very inefficient in the long run.

If this sort of thing cant be done with DLL's (back and forth communication between the Host program and dll), then what use are they anyway?

Sure I can have simple functions, like my "Color" class, to parse and return color codes, but simple things aren't going to change, and need to be updated.

Anyway, I always tend to ramble about things that don't matter (for the most part), so thanks for taking a look, and for any responses :)

答: Actually, not using DLLs simplifies things a great deal. In this age of fast downloads I would rather update a program by downloading a single executable, rather than a bunch of DLLs that often get installed in distinctly dubious locations.</p>

Title: Effective use of a DLL


问:
Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"
I am using Android studio 1.0.1. I have a java module referred by other modules in my project. I have checked it out from SVN But now every

Unsupported Modules Detected: Compilation is not supported for following modules: . Unfortunately you can't have non-Gradle Java modules and Android-Gradle modules in one project.

After getting this error AS stop compilation of this module so that I am not able to compile/run my project any more.

答:
Delete .idea/modules.xml

Reload All Gradle Projects

You do not want to remove entire .idea directory, because it contains e.g. dictionaries and shelved changes.


问:
Is BsonRepresentation(BsonType.ObjectId) always unique?
Just a straight forward question is

```<code>[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
</code>```

always unique? If not is there a way to generate a unique id for my user?

答:
The rule formation for a objectid is:

The 12-byte ObjectId value consists of:

a 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch

a 5-byte random value

a 3-byte incrementing counter, initialized to a random value

If you want to know more, there is this article that explains in detail how to avoid that situation.

Body:
Just a straight forward question is

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]

always unique? If not is there a way to generate a unique id for my user?