问:
Javascript typeof throws referenceerror
lets get right into it.

I am using typeof to check if a variable API exists.
I learned that typeof returns "undefined" if the variable does not exist.

function exitApplication() {
    let typeOfApi = typeof API;
    if (typeOfApi !== "undefined") {
        API.close(() => {
            strip.shutdown();
            ...
            ...
            ...
        });
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}
```

<p>If I now run my program with test data that leads into a call to <code>exitApplication</code> when API is not yet defined I get a ReferenceError: </p>

```    let typeOfApi = typeof API;
                    ^

ReferenceError: API is not defined
```

<p>Because I am using Webpack I changed the output file and replaced API with anything else that was not defined and voila it works and <code>typeOfApi</code> is "undefined" (the code I pasted is the Webpack outup).</p>

<p>API is a const value and I only use let and const in my code. I read something about Temporal Dead Zones, but typeof should still return "undefined" if a let variable is not defined?</p>

<p>I also read this Why does typeof only sometimes throw ReferenceError? but I am not using a expression.</p>

<p>Oh and my code is written in typescript. But I am not that "good" at it and don't really know how to get the types for restify, so <code>API</code> is of type <code>any</code>. (I know that typeof and the typescript type are completely different things :D). But the code seems to be translated 1 to 1 anyways.
<br><br><br></p>

<p>Edit:
So I made this little example. This is the Webpack output</p>

```#!/usr/local/bin/node
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/test.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./src/test.ts":
/*!*********************!*\
  !*** ./src/test.ts ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

exitApplication();
const API = {};
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

/***/ })

/******/ });
//# sourceMappingURL=LED-Controller.js.map
```

And this will also throw a referenceerror

Edit: Here are my TS and Webpack configs.
https://gist.github.com/Lucarus/ebbfab5cc6560094a292ba86557ffd1d

For the example I replaced Applications.ts with test.ts but it used the same config.

答:
You're calling a function that references the const API = {} variable BEFORE that variable has been initialized, but inside the scope where it will be declared.  With const and let, that is not allowed.  You have this:

```<code>exitApplication();
const API = {};
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}
</code>```

The function is hoisted to the top of that scope so that's why you can call exitApplication(), but you have not yet executed the line of code that initializes API.  But, the intrepreter knows it's there and not yet initialized and it's a ReferenceError in Javascript to attempt to access a const or let defined variable in the scope where it is defined before it the line containing its declaration runs.

When I run this in Chrome, the exact error I get is:

```<code>Uncaught ReferenceError: Cannot access 'API' before initialization
</code>```

which is telling you exactly what the problem is.  In the first pass of the interpreter, it has parsed the code and it knows that const API = {} is there, so its illegal to access it until it reaches that line of code that initializes it.  If you really want to get around this, then change const to var, but there's likely just a better way to write your code that doesn't need to use var.

Of course, if you just move the declaration of API up one line, no problem:

```<code>const API = {};
exitApplication();
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}
</code>```

For a good article on this topic, you can read this article: Why typeof is no longer safe.

Title: Javascript typeof throws referenceerror

Body:
lets get right into it.

I am using typeof to check if a variable API exists.
I learned that typeof returns "undefined" if the variable does not exist.

function exitApplication() {
    let typeOfApi = typeof API;
    if (typeOfApi !== "undefined") {
        API.close(() => {
            strip.shutdown();
            ...
            ...
            ...
        });
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

If I now run my program with test data that leads into a call to exitApplication when API is not yet defined I get a ReferenceError:

    let typeOfApi = typeof API;
                    ^

ReferenceError: API is not defined

Because I am using Webpack I changed the output file and replaced API with anything else that was not defined and voila it works and typeOfApi is "undefined" (the code I pasted is the Webpack outup).

API is a const value and I only use let and const in my code. I read something about Temporal Dead Zones, but typeof should still return "undefined" if a let variable is not defined?

I also read this Why does typeof only sometimes throw ReferenceError? but I am not using a expression.

Oh and my code is written in typescript. But I am not that "good" at it and don't really know how to get the types for restify, so API is of type any. (I know that typeof and the typescript type are completely different things :D). But the code seems to be translated 1 to 1 anyways.

Edit:
So I made this little example. This is the Webpack output

#!/usr/local/bin/node
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/        }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/        if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/            Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/        }
/******/        Object.defineProperty(exports, '__esModule', { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave like require
/******/    __webpack_require__.t = function(value, mode) {
/******/        if(mode & 1) value = __webpack_require__(value);
/******/        if(mode & 8) return value;
/******/        if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/        var ns = Object.create(null);
/******/        __webpack_require__.r(ns);
/******/        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/        if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/        return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/test.ts");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./src/test.ts":
/*!*********************!*\
  !*** ./src/test.ts ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

exitApplication();
const API = {};
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

/***/ })

/******/ });
//# sourceMappingURL=LED-Controller.js.map

And this will also throw a referenceerror

Edit: Here are my TS and Webpack configs.
https://gist.github.com/Lucarus/ebbfab5cc6560094a292ba86557ffd1d

For the example I replaced Applications.ts with test.ts but it used the same config.

Body:
You're calling a function that references the const API = {} variable BEFORE that variable has been initialized, but inside the scope where it will be declared.  With const and let, that is not allowed.  You have this:

exitApplication();
const API = {};
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

The function is hoisted to the top of that scope so that's why you can call exitApplication(), but you have not yet executed the line of code that initializes API.  But, the intrepreter knows it's there and not yet initialized and it's a ReferenceError in Javascript to attempt to access a const or let defined variable in the scope where it is defined before it the line containing its declaration runs.

When I run this in Chrome, the exact error I get is:

Uncaught ReferenceError: Cannot access 'API' before initialization

which is telling you exactly what the problem is.  In the first pass of the interpreter, it has parsed the code and it knows that const API = {} is there, so its illegal to access it until it reaches that line of code that initializes it.  If you really want to get around this, then change const to var, but there's likely just a better way to write your code that doesn't need to use var.

Of course, if you just move the declaration of API up one line, no problem:

const API = {};
exitApplication();
function exitApplication() {
    let typeOfApi = typeof API;
    console.log(typeOfApi);
    if (typeOfApi !== "undefined") {
        console.log("Bye!");
        process.exit(0);
    }
    else {
        console.log("Bye!");
        process.exit(0);
    }
}

For a good article on this topic, you can read this article: Why typeof is no longer safe.


来源: stackexchange

问:
How to remove the error "TypeError: can't concat str to bytes"
I tried the GitHub code to make a USB connection with an iOS device and Python on a PC.

The above code was created in Python2, so I ran 2to3 -w usbmux.py to convert it to Python3 code.

The Python3 code is as follows.

```<code>import socket, struct, select, sys

try:
    import plistlib
    haveplist = True
except:
    haveplist = False

class MuxError(Exception):
    pass

class MuxVersionError(MuxError):
    pass

class SafeStreamSocket:
    def __init__(self, address, family):
        self.sock = socket.socket(family, socket.SOCK_STREAM)
        self.sock.connect(address)
    def send(self, msg):
        totalsent = 0
        while totalsent < len(msg):
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise MuxError("socket connection broken")
            totalsent = totalsent + sent
    def recv(self, size):
        msg = ''
        while len(msg) < size:
            chunk = self.sock.recv(size-len(msg))
            if chunk == '':
                raise MuxError("socket connection broken")
            msg = msg + chunk
        return msg

class MuxDevice(object):
    def __init__(self, devid, usbprod, serial, location):
        self.devid = devid
        self.usbprod = usbprod
        self.serial = serial
        self.location = location
    def __str__(self):
        return "<MuxDevice: ID %d ProdID 0x%04x Serial '%s' Location 0x%x>"%(self.devid, self.usbprod, self.serial, self.location)

class BinaryProtocol(object):
    TYPE_RESULT = 1
    TYPE_CONNECT = 2
    TYPE_LISTEN = 3
    TYPE_DEVICE_ADD = 4
    TYPE_DEVICE_REMOVE = 5
    VERSION = 0
    def __init__(self, socket):
        self.socket = socket
        self.connected = False

    def _pack(self, req, payload):
        if req == self.TYPE_CONNECT:
            return struct.pack("IH", payload['DeviceID'], payload['PortNumber']) + "\x00\x00"
        elif req == self.TYPE_LISTEN:
            return ""
        else:
            raise ValueError("Invalid outgoing request type %d"%req)

    def _unpack(self, resp, payload):
        if resp == self.TYPE_RESULT:
            return {'Number':struct.unpack("I", payload)[0]}
        elif resp == self.TYPE_DEVICE_ADD:
            devid, usbpid, serial, pad, location = struct.unpack("IH256sHI", payload)
            serial = serial.split("\0")[0]
            return {'DeviceID': devid, 'Properties': {'LocationID': location, 'SerialNumber': serial, 'ProductID': usbpid}}
        elif resp == self.TYPE_DEVICE_REMOVE:
            devid = struct.unpack("I", payload)[0]
            return {'DeviceID': devid}
        else:
            raise MuxError("Invalid incoming request type %d"%req)

    def sendpacket(self, req, tag, payload={}):
        payload = self._pack(req, payload)
        if self.connected:
            raise MuxError("Mux is connected, cannot issue control packets")
        length = 16 + len(payload)
        data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
        self.socket.send(data)
    def getpacket(self):
        if self.connected:
            raise MuxError("Mux is connected, cannot issue control packets")
        dlen = self.socket.recv(4)
        dlen = struct.unpack("I", dlen)[0]
        body = self.socket.recv(dlen - 4)
        version, resp, tag = struct.unpack("III",body[:0xc])
        if version != self.VERSION:
            raise MuxVersionError("Version mismatch: expected %d, got %d"%(self.VERSION,version))
        payload = self._unpack(resp, body[0xc:])
        return (resp, tag, payload)

class PlistProtocol(BinaryProtocol):
    TYPE_RESULT = "Result"
    TYPE_CONNECT = "Connect"
    TYPE_LISTEN = "Listen"
    TYPE_DEVICE_ADD = "Attached"
    TYPE_DEVICE_REMOVE = "Detached" #???
    TYPE_PLIST = 8
    VERSION = 1
    def __init__(self, socket):
        if not haveplist:
            raise Exception("You need the plistlib module")
        BinaryProtocol.__init__(self, socket)

    def _pack(self, req, payload):
        return payload

    def _unpack(self, resp, payload):
        return payload

    def sendpacket(self, req, tag, payload={}):
        payload['ClientVersionString'] = 'usbmux.py by marcan'
        if isinstance(req, int):
            req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2]
        payload['MessageType'] = req
        payload['ProgName'] = 'tcprelay'
        BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
    def getpacket(self):
        resp, tag, payload = BinaryProtocol.getpacket(self)
        if resp != self.TYPE_PLIST:
            raise MuxError("Received non-plist type %d"%resp)
        payload = plistlib.readPlistFromString(payload)
        return payload['MessageType'], tag, payload

class MuxConnection(object):
    def __init__(self, socketpath, protoclass):
        self.socketpath = socketpath
        if sys.platform in ['win32', 'cygwin']:
            family = socket.AF_INET
            address = ('127.0.0.1', 27015)
        else:
            family = socket.AF_UNIX
            address = self.socketpath
        self.socket = SafeStreamSocket(address, family)
        self.proto = protoclass(self.socket)
        self.pkttag = 1
        self.devices = []

    def _getreply(self):
        while True:
            resp, tag, data = self.proto.getpacket()
            if resp == self.proto.TYPE_RESULT:
                return tag, data
            else:
                raise MuxError("Invalid packet type received: %d"%resp)
    def _processpacket(self):
        resp, tag, data = self.proto.getpacket()
        if resp == self.proto.TYPE_DEVICE_ADD:
            self.devices.append(MuxDevice(data['DeviceID'], data['Properties']['ProductID'], data['Properties']['SerialNumber'], data['Properties']['LocationID']))
        elif resp == self.proto.TYPE_DEVICE_REMOVE:
            for dev in self.devices:
                if dev.devid == data['DeviceID']:
                    self.devices.remove(dev)
        elif resp == self.proto.TYPE_RESULT:
            raise MuxError("Unexpected result: %d"%resp)
        else:
            raise MuxError("Invalid packet type received: %d"%resp)
    def _exchange(self, req, payload={}):
        mytag = self.pkttag
        self.pkttag += 1
        self.proto.sendpacket(req, mytag, payload)
        recvtag, data = self._getreply()
        if recvtag != mytag:
            raise MuxError("Reply tag mismatch: expected %d, got %d"%(mytag, recvtag))
        return data['Number']

    def listen(self):
        ret = self._exchange(self.proto.TYPE_LISTEN)
        if ret != 0:
            raise MuxError("Listen failed: error %d"%ret)
    def process(self, timeout=None):
        if self.proto.connected:
            raise MuxError("Socket is connected, cannot process listener events")
        rlo, wlo, xlo = select.select([self.socket.sock], [], [self.socket.sock], timeout)
        if xlo:
            self.socket.sock.close()
            raise MuxError("Exception in listener socket")
        if rlo:
            self._processpacket()
    def connect(self, device, port):
        ret = self._exchange(self.proto.TYPE_CONNECT, {'DeviceID':device.devid, 'PortNumber':((port<<8) & 0xFF00) | (port>>8)})
        if ret != 0:
            raise MuxError("Connect failed: error %d"%ret)
        self.proto.connected = True
        return self.socket.sock
    def close(self):
        self.socket.sock.close()

class USBMux(object):
    def __init__(self, socketpath=None):
        if socketpath is None:
            if sys.platform == 'darwin':
                socketpath = "/var/run/usbmuxd"
            else:
                socketpath = "/var/run/usbmuxd"
        self.socketpath = socketpath
        self.listener = MuxConnection(socketpath, BinaryProtocol)
        try:
            self.listener.listen()
            self.version = 0
            self.protoclass = BinaryProtocol
        except MuxVersionError:
            self.listener = MuxConnection(socketpath, PlistProtocol)
            self.listener.listen()
            self.protoclass = PlistProtocol
            self.version = 1
        self.devices = self.listener.devices
    def process(self, timeout=None):
        self.listener.process(timeout)
    def connect(self, device, port):
        connector = MuxConnection(self.socketpath, self.protoclass)
        return connector.connect(device, port)

if __name__ == "__main__":
    mux = USBMux()
    print("Waiting for devices...")
    if not mux.devices:
        mux.process(0.1)
    while True:
        print("Devices:")
        for dev in mux.devices:
            print(dev)
        mux.process()
</code>```

I ran the above code in Python 3.7 and got the error.
The details of the error are as follows.

```<code>  File "C:\Users\taichi\Documents\usbmux.py", line 81, in sendpacket
    data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
TypeError: can't concat str to bytes
</code>```

How can I rewrite this code to get rid of the error?

答:
The line:

```<code>data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
</code>```

is causing the trouble. According to the struct.pack() docs, the method returns bytes.  You need to convert your payload also into bytes so that the two can be concatenated, making the error go away.

Not sure what your payload is, but encoding the payload using something like 'utf-8' might do the trick. I believe a simple payload.encode() will work, since 'utf-8' is the default encoding.  So, try:

```<code>data = struct.pack("IIII", length, self.VERSION, req, tag) + payload.encode()
#                                                          add this ^^^^^^^^^
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried the GitHub code to make a USB connection with an iOS device and Python on a PC.

The above code was created in Python2, so I ran 2to3 -w usbmux.py to convert it to Python3 code.

The Python3 code is as follows.

import socket, struct, select, sys

try:
    import plistlib
    haveplist = True
except:
    haveplist = False

class MuxError(Exception):
    pass

class MuxVersionError(MuxError):
    pass

class SafeStreamSocket:
    def __init__(self, address, family):
        self.sock = socket.socket(family, socket.SOCK_STREAM)
        self.sock.connect(address)
    def send(self, msg):
        totalsent = 0
        while totalsent < len(msg):
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise MuxError("socket connection broken")
            totalsent = totalsent + sent
    def recv(self, size):
        msg = ''
        while len(msg) < size:
            chunk = self.sock.recv(size-len(msg))
            if chunk == '':
                raise MuxError("socket connection broken")
            msg = msg + chunk
        return msg

class MuxDevice(object):
    def __init__(self, devid, usbprod, serial, location):
        self.devid = devid
        self.usbprod = usbprod
        self.serial = serial
        self.location = location
    def __str__(self):
        return "<MuxDevice: ID %d ProdID 0x%04x Serial '%s' Location 0x%x>"%(self.devid, self.usbprod, self.serial, self.location)

class BinaryProtocol(object):
    TYPE_RESULT = 1
    TYPE_CONNECT = 2
    TYPE_LISTEN = 3
    TYPE_DEVICE_ADD = 4
    TYPE_DEVICE_REMOVE = 5
    VERSION = 0
    def __init__(self, socket):
        self.socket = socket
        self.connected = False

    def _pack(self, req, payload):
        if req == self.TYPE_CONNECT:
            return struct.pack("IH", payload['DeviceID'], payload['PortNumber']) + "\x00\x00"
        elif req == self.TYPE_LISTEN:
            return ""
        else:
            raise ValueError("Invalid outgoing request type %d"%req)

    def _unpack(self, resp, payload):
        if resp == self.TYPE_RESULT:
            return {'Number':struct.unpack("I", payload)[0]}
        elif resp == self.TYPE_DEVICE_ADD:
            devid, usbpid, serial, pad, location = struct.unpack("IH256sHI", payload)
            serial = serial.split("\0")[0]
            return {'DeviceID': devid, 'Properties': {'LocationID': location, 'SerialNumber': serial, 'ProductID': usbpid}}
        elif resp == self.TYPE_DEVICE_REMOVE:
            devid = struct.unpack("I", payload)[0]
            return {'DeviceID': devid}
        else:
            raise MuxError("Invalid incoming request type %d"%req)

    def sendpacket(self, req, tag, payload={}):
        payload = self._pack(req, payload)
        if self.connected:
            raise MuxError("Mux is connected, cannot issue control packets")
        length = 16 + len(payload)
        data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
        self.socket.send(data)
    def getpacket(self):
        if self.connected:
            raise MuxError("Mux is connected, cannot issue control packets")
        dlen = self.socket.recv(4)
        dlen = struct.unpack("I", dlen)[0]
        body = self.socket.recv(dlen - 4)
        version, resp, tag = struct.unpack("III",body[:0xc])
        if version != self.VERSION:
            raise MuxVersionError("Version mismatch: expected %d, got %d"%(self.VERSION,version))
        payload = self._unpack(resp, body[0xc:])
        return (resp, tag, payload)

class PlistProtocol(BinaryProtocol):
    TYPE_RESULT = "Result"
    TYPE_CONNECT = "Connect"
    TYPE_LISTEN = "Listen"
    TYPE_DEVICE_ADD = "Attached"
    TYPE_DEVICE_REMOVE = "Detached" #???
    TYPE_PLIST = 8
    VERSION = 1
    def __init__(self, socket):
        if not haveplist:
            raise Exception("You need the plistlib module")
        BinaryProtocol.__init__(self, socket)

    def _pack(self, req, payload):
        return payload

    def _unpack(self, resp, payload):
        return payload

    def sendpacket(self, req, tag, payload={}):
        payload['ClientVersionString'] = 'usbmux.py by marcan'
        if isinstance(req, int):
            req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2]
        payload['MessageType'] = req
        payload['ProgName'] = 'tcprelay'
        BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
    def getpacket(self):
        resp, tag, payload = BinaryProtocol.getpacket(self)
        if resp != self.TYPE_PLIST:
            raise MuxError("Received non-plist type %d"%resp)
        payload = plistlib.readPlistFromString(payload)
        return payload['MessageType'], tag, payload

class MuxConnection(object):
    def __init__(self, socketpath, protoclass):
        self.socketpath = socketpath
        if sys.platform in ['win32', 'cygwin']:
            family = socket.AF_INET
            address = ('127.0.0.1', 27015)
        else:
            family = socket.AF_UNIX
            address = self.socketpath
        self.socket = SafeStreamSocket(address, family)
        self.proto = protoclass(self.socket)
        self.pkttag = 1
        self.devices = []

    def _getreply(self):
        while True:
            resp, tag, data = self.proto.getpacket()
            if resp == self.proto.TYPE_RESULT:
                return tag, data
            else:
                raise MuxError("Invalid packet type received: %d"%resp)
    def _processpacket(self):
        resp, tag, data = self.proto.getpacket()
        if resp == self.proto.TYPE_DEVICE_ADD:
            self.devices.append(MuxDevice(data['DeviceID'], data['Properties']['ProductID'], data['Properties']['SerialNumber'], data['Properties']['LocationID']))
        elif resp == self.proto.TYPE_DEVICE_REMOVE:
            for dev in self.devices:
                if dev.devid == data['DeviceID']:
                    self.devices.remove(dev)
        elif resp == self.proto.TYPE_RESULT:
            raise MuxError("Unexpected result: %d"%resp)
        else:
            raise MuxError("Invalid packet type received: %d"%resp)
    def _exchange(self, req, payload={}):
        mytag = self.pkttag
        self.pkttag += 1
        self.proto.sendpacket(req, mytag, payload)
        recvtag, data = self._getreply()
        if recvtag != mytag:
            raise MuxError("Reply tag mismatch: expected %d, got %d"%(mytag, recvtag))
        return data['Number']

    def listen(self):
        ret = self._exchange(self.proto.TYPE_LISTEN)
        if ret != 0:
            raise MuxError("Listen failed: error %d"%ret)
    def process(self, timeout=None):
        if self.proto.connected:
            raise MuxError("Socket is connected, cannot process listener events")
        rlo, wlo, xlo = select.select([self.socket.sock], [], [self.socket.sock], timeout)
        if xlo:
            self.socket.sock.close()
            raise MuxError("Exception in listener socket")
        if rlo:
            self._processpacket()
    def connect(self, device, port):
        ret = self._exchange(self.proto.TYPE_CONNECT, {'DeviceID':device.devid, 'PortNumber':((port<<8) & 0xFF00) | (port>>8)})
        if ret != 0:
            raise MuxError("Connect failed: error %d"%ret)
        self.proto.connected = True
        return self.socket.sock
    def close(self):
        self.socket.sock.close()

class USBMux(object):
    def __init__(self, socketpath=None):
        if socketpath is None:
            if sys.platform == 'darwin':
                socketpath = "/var/run/usbmuxd"
            else:
                socketpath = "/var/run/usbmuxd"
        self.socketpath = socketpath
        self.listener = MuxConnection(socketpath, BinaryProtocol)
        try:
            self.listener.listen()
            self.version = 0
            self.protoclass = BinaryProtocol
        except MuxVersionError:
            self.listener = MuxConnection(socketpath, PlistProtocol)
            self.listener.listen()
            self.protoclass = PlistProtocol
            self.version = 1
        self.devices = self.listener.devices
    def process(self, timeout=None):
        self.listener.process(timeout)
    def connect(self, device, port):
        connector = MuxConnection(self.socketpath, self.protoclass)
        return connector.connect(device, port)

if __name__ == "__main__":
    mux = USBMux()
    print("Waiting for devices...")
    if not mux.devices:
        mux.process(0.1)
    while True:
        print("Devices:")
        for dev in mux.devices:
            print(dev)
        mux.process()

I ran the above code in Python 3.7 and got the error.
The details of the error are as follows.

  File "C:\Users\taichi\Documents\usbmux.py", line 81, in sendpacket
    data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
TypeError: can't concat str to bytes

How can I rewrite this code to get rid of the error?

Body:
The line:

data = struct.pack("IIII", length, self.VERSION, req, tag) + payload

is causing the trouble. According to the struct.pack() docs, the method returns bytes.  You need to convert your payload also into bytes so that the two can be concatenated, making the error go away.

Not sure what your payload is, but encoding the payload using something like 'utf-8' might do the trick. I believe a simple payload.encode() will work, since 'utf-8' is the default encoding.  So, try:

data = struct.pack("IIII", length, self.VERSION, req, tag) + payload.encode()
#                                                          add this ^^^^^^^^^


问:
Add Javascript to down ARROW BUTTON to open and close sub menu
I've been trying for hours with this javascript navigation, I've researched many sites, including w3schools, codepen, and css tricks, and many others, I've spent hours reading through stack, and everything has helped a lot, now I'm almost finished, and I need some help making this menu work.

Essentially, it is a sub navigation menu that stays open when you click the down ARROW BUTTON and closes when you click anywhere on the page. Sometimes it works, and sometimes it doesn't.

The menu has two links:
Forum 1 / down ARROW BUTTON and
Forum 2 / down ARROW BUTTON

I can get Forum 1 down ARROW BUTTON to open the subnavigation sometimes, by clicking the down ARROW BUTTON, but I cannot get Forum 2 down ARROW BUTTON to trigger sub navigation at all.

I'm not sure if it is the way I have the css, or what.

I'm providing the full menu with css, html, and javascript,

Like I said, I can get the first down ARROW BUTTON to open the sub navigation sometimes, but that is about it. Can you help me get this working please?

Here is the styling for the navigation menu

```<code> body {
  font-family: Arial, Helvetica, sans-serif;
  margin: 0;
}

.navbar {
  overflow: hidden;
  background-color: #18143c;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 7px 14px 16px;
  text-decoration: none;
}

.subnav {
  float: left;
  overflow: auto;
}

.subnav .subnavbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 5px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
  margin-right:26px;
}

.navbar a:hover, .subnav:hover .subnavbtn {
  background-color: #46485c;
}

.subnav-content-1 {
 display: none;
  position: absolute;
  left: 0;
  background-color: #46485c;
  width: 100%;
  z-index: 1;
  overflow:auto;
}

.subnav-content-1 a {
  float: left;
  color: white;
  text-decoration: none;
  padding: 10px 10px;
}

.subnav-content-1 a:hover {
  background-color: #eee;
  color: black;
}

.show {display: block;}
</code>```

Here is the HTML for the navigation menu

```<code><div class="navbar">
    <a href="#home"style="padding-left:6px;">Forums 1</a>
  <div class="subnav">
  <button onclick="myFunction()" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
     <div id="myDropdown" class="subnav-content-1">
      <a href="#"style="margin-left:16px;">Test Main</a>
      <a href="#">Test link 1</a>
      <a href="#">Test link 1</a>
       <a href="#">Test link 1</a>
    </div>
  </div>
    <a href="#home"style="padding-left:6px;">Forums 2</a>
  <div class="subnav">
  <button onclick="myFunction()" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
     <div id="myDropdown" class="subnav-content-1">
      <a href="#"style="margin-left:16px;">Test Main</a>
      <a href="#">Test link 2</a>
      <a href="#">Test link 2</a>
       <a href="#">Test link 2</a>
    </div>
  </div>
</div>
</code>```

And here is the javascript

```<code>/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.subnavbtn')) {
    var dropdowns = document.getElementsByClassName("subnav-content-1");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
</script>
</code>```

here is a link to the page on W3schools where I've been working on this menu.
https://www.w3schools.com/code/tryit.asp?filename=GC3LUF0TLS6S

What I am trying to do is, get the menu working were, when you click the dropdown ARROW BUTTON, it opens the sub navigation menu, then to close sub navigation, you just click anywhere on the page.

This almost works!! Please help me get it working right.

答:
Hi man I found a fix for you, I don't know if it is what you need but it gets that job done:

First change the id's for each dropdown as they are conflicting when js is called, then call that js function with a the id number of each dropdown:

```<code><div class="navbar">
    <a href="#home"style="padding-left:6px;">Forums 1</a>
  <div class="subnav">
  <button onclick="**myFunction(1)**" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
     <div id="**myDropdown1**" class="subnav-content-1">
      <a href="#"style="margin-left:16px;">Test Main</a>
      <a href="#">Test link 1</a>
      <a href="#">Test link 1</a>
       <a href="#">Test link 1</a>
    </div>
  </div>
    <a href="#home"style="padding-left:6px;">Forums 2</a>
  <div class="subnav">
  <button onclick="**myFunction(2)**" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
     <div id="**myDropdown2**" class="subnav-content-1">
      <a href="#"style="margin-left:16px;">Test Main</a>
      <a href="#">Test link 2</a>
      <a href="#">Test link 2</a>
       <a href="#">Test link 2</a>
    </div>
  </div>
</div>
</code>```

Then you should add a parameter to you js function to know which dropdown to toggle:

```<code>function myFunction(n) {
    document.getElementById("myDropdown"+n).classList.toggle("show");
}
</code>```

Body:
I've been trying for hours with this javascript navigation, I've researched many sites, including w3schools, codepen, and css tricks, and many others, I've spent hours reading through stack, and everything has helped a lot, now I'm almost finished, and I need some help making this menu work.

Essentially, it is a sub navigation menu that stays open when you click the down ARROW BUTTON and closes when you click anywhere on the page. Sometimes it works, and sometimes it doesn't.

The menu has two links:
Forum 1 / down ARROW BUTTON and
Forum 2 / down ARROW BUTTON

I can get Forum 1 down ARROW BUTTON to open the subnavigation sometimes, by clicking the down ARROW BUTTON, but I cannot get Forum 2 down ARROW BUTTON to trigger sub navigation at all.

I'm not sure if it is the way I have the css, or what.

I'm providing the full menu with css, html, and javascript,

Like I said, I can get the first down ARROW BUTTON to open the sub navigation sometimes, but that is about it. Can you help me get this working please?

Here is the styling for the navigation menu

 body {
  font-family: Arial, Helvetica, sans-serif;
  margin: 0;
}

.navbar {
  overflow: hidden;
  background-color: #18143c;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 7px 14px 16px;
  text-decoration: none;
}

.subnav {
  float: left;
  overflow: auto;
}

.subnav .subnavbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 5px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
  margin-right:26px;
}

.navbar a:hover, .subnav:hover .subnavbtn {
  background-color: #46485c;
}

.subnav-content-1 {
 display: none;
  position: absolute;
  left: 0;
  background-color: #46485c;
  width: 100%;
  z-index: 1;
  overflow:auto;
}

.subnav-content-1 a {
  float: left;
  color: white;
  text-decoration: none;
  padding: 10px 10px;
}

.subnav-content-1 a:hover {
  background-color: #eee;
  color: black;
}

.show {display: block;}

Here is the HTML for the navigation menu

    Forums 1

  <button onclick="myFunction()" class="subnavbtn"></button>

      Test Main
      Test link 1
      Test link 1
       Test link 1

    Forums 2

  <button onclick="myFunction()" class="subnavbtn"></button>

      Test Main
      Test link 2
      Test link 2
       Test link 2

And here is the javascript

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.subnavbtn')) {
    var dropdowns = document.getElementsByClassName("subnav-content-1");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
</script>

here is a link to the page on W3schools where I've been working on this menu.
https://www.w3schools.com/code/tryit.asp?filename=GC3LUF0TLS6S

What I am trying to do is, get the menu working were, when you click the dropdown ARROW BUTTON, it opens the sub navigation menu, then to close sub navigation, you just click anywhere on the page.

This almost works!! Please help me get it working right.

Body:
Hi man I found a fix for you, I don't know if it is what you need but it gets that job done:

First change the id's for each dropdown as they are conflicting when js is called, then call that js function with a the id number of each dropdown:

<div class="navbar">
    <a href="#home"style="padding-left:6px;">Forums 1</a>
  <div class="subnav">
  <button onclick="**myFunction(1)**" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
     <div id="**myDropdown1**" class="subnav-content-1">
      <a href="#"style="margin-left:16px;">Test Main</a>
      <a href="#">Test link 1</a>
      <a href="#">Test link 1</a>
       <a href="#">Test link 1</a>
    </div>
  </div>
    <a href="#home"style="padding-left:6px;">Forums 2</a>
  <div class="subnav">
  <button onclick="**myFunction(2)**" class="subnavbtn"><i class="fa fa-caret-down"></i></button>
     <div id="**myDropdown2**" class="subnav-content-1">
      <a href="#"style="margin-left:16px;">Test Main</a>
      <a href="#">Test link 2</a>
      <a href="#">Test link 2</a>
       <a href="#">Test link 2</a>
    </div>
  </div>
</div>

Then you should add a parameter to you js function to know which dropdown to toggle:

function myFunction(n) {
    document.getElementById("myDropdown"+n).classList.toggle("show");
}


问:
GET or POST when reading request body
Should I use the GET or POST method when sending information to a server in the body of the HTTP request?  There are no query parameters appended to the URL, the server will inspect the body of the request for what it needs.</p>

答: POST should be used if you are not planing on using the query string. </p>

ContentLicense: CC BY-SA 3.0

Title: GET or POST when reading request body


问:
"Failed RTM connect" error when trying to connect to Slack with RTM API
I'm using the following Python code from Slack's "Migrating to 2.x" github docs

```<code>from slackclient import SlackClient

slack_token = os.environ["SLACK_API_TOKEN"]
client = SlackClient(slack_token)

def say_hello(data):
    if 'Hello' in data['text']:
        channel_id = data['channel']
        thread_ts = data['ts']
        user = data['user']

        client.api_call('chat.postMessage',
            channel=channel_id,
            text="Hi <@{}>!".format(user),
            thread_ts=thread_ts
        )

if client.rtm_connect():
    while client.server.connected is True:
        for data in client.rtm_read():
            if "type" in data and data["type"] == "message":
                say_hello(data)
else:
    print "Connection Failed"
</code>```

For the SLACK_API_TOKEN, I am using the Bot User OAuth Access Token for my app, found here:

The error I am getting is the following:

```<code>Failed RTM connect
Traceback (most recent call last):
  File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/client.py", line 140, in rtm_connect
    self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
  File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/server.py", line 168, in rtm_connect
    raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed
</code>```

Why am I getting this error?!?!?!

Other context:

I am on a Mac, unlike others who have had issues online using Windows
machines.

I am running the code locally, in a virtual env, via
python script.py in my terminal.

I last successfully ran this in December, and have seen that Slack dropped support for the RTM API (?) Dec 31st 2019?

The app has been reinstalled to my workspace, and the keys did not change.

I think it may be something I need to configure/change/set/refresh on the api.slack.com/apps side, since it broke without any code changes occurring.

Why am I focusing on debugging the example for 1.x? My code was previously working using rtm_connect / 1.x using the same commands as the example code, and without any code changes it has stopped working. My code and the example code yield the same errors, so I'm using the sample code to make debugging easier. I'd like to fix this before starting the process of migrating to 2.x, so I can start with working code before embarking on a long series of changes that can introduce their own errors.

答:
I not sure if this is the reason, but I ran into the same issues before.
The answer I found on the Slack Github is that new xoxob-* doesn't support RTM.

Please reference this web:
 - https://github.com/slackapi/python-slackclient/issues/326.

So I use my OAuth Access Token instead of Bot User OAuth Access Token.

Body:
I'm using the following Python code from Slack's "Migrating to 2.x" github docs

from slackclient import SlackClient

slack_token = os.environ["SLACK_API_TOKEN"]
client = SlackClient(slack_token)

def say_hello(data):
    if 'Hello' in data['text']:
        channel_id = data['channel']
        thread_ts = data['ts']
        user = data['user']

        client.api_call('chat.postMessage',
            channel=channel_id,
            text="Hi <@{}>!".format(user),
            thread_ts=thread_ts
        )

if client.rtm_connect():
    while client.server.connected is True:
        for data in client.rtm_read():
            if "type" in data and data["type"] == "message":
                say_hello(data)
else:
    print "Connection Failed"

For the SLACK_API_TOKEN, I am using the Bot User OAuth Access Token for my app, found here:

The error I am getting is the following:

Failed RTM connect
Traceback (most recent call last):
  File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/client.py", line 140, in rtm_connect
    self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
  File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/server.py", line 168, in rtm_connect
    raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed

Why am I getting this error?!?!?!

Other context:

I am on a Mac, unlike others who have had issues online using Windows
machines.

I am running the code locally, in a virtual env, via
python script.py in my terminal.

I last successfully ran this in December, and have seen that Slack dropped support for the RTM API (?) Dec 31st 2019?

The app has been reinstalled to my workspace, and the keys did not change.

I think it may be something I need to configure/change/set/refresh on the api.slack.com/apps side, since it broke without any code changes occurring.

Why am I focusing on debugging the example for 1.x? My code was previously working using rtm_connect / 1.x using the same commands as the example code, and without any code changes it has stopped working. My code and the example code yield the same errors, so I'm using the sample code to make debugging easier. I'd like to fix this before starting the process of migrating to 2.x, so I can start with working code before embarking on a long series of changes that can introduce their own errors.


问:
TFS can't check in changes after replacing file
I'm re-writing an Asp.Net project that a colleague had done a prototype version of. I deleted the Default.aspx and created and new one and now I'm trying to check that new version in.

When I try to check in pending changes I get the standard:

Check In, No files checked in due to conflicting changes. Please use
  Conflicts Channel to resolve conflicts and try again.

I'm re-directed to the Pending Changes - Conflicts tab, where I'm presented with the options: 'Take Server Version' or 'Keep Local Version'.

If I click 'Keep Local Version', I get the following error:

Error, The following exception was encountered. The item
  $/ProjectName/Default.aspx already has pending changes.

How can I get it to accept my new version of the file?

答:
The edited files are no longer with read-only status.

So this is the solution:

Close the project. (Or use TfsGoOffline, I love this, you can skip 2, 3, 4)

Disconnect internet.

Open the project and it will now in offline mode.

Reconnect to the Internet.

Right-click the solution and select "Online".

VS will checks all files that are not "read-only" and treats them as "changed" and mark as check out.

Now all files that have been replaced are successfully checked out.


问:
Problem restoring stdout after using pipe
Using the advise found here: Restoring stdout after using dup
I tried to restore the stdin and stdout. However, when using printf to check if stdout was restored I could not read an output.
The code is as follows. After restoring stdout as 1, I tried printing "done".

```<code>#include <stdio.h>
#include <unistd.h>

void main(int argv, char *argc) {
    int stdin_copy = dup(STDIN_FILENO);
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        fclose(stdout);
        close(testpipe[1]);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        fprintf(stderr, "initial value: %s\n", initialval);
        wait(NULL);
        dup2(stdin_copy, 0);
        dup2(stdout_copy, 1);
        printf("done");//was not displayed when I run code.
    }
}
</code>```

However, I did not see a "done" when I ran the code. (There should be a done after 15).
This is my output:
initial value:
exec successful
a: 3
b: 5
multby successful
15

What did I do wrong when restoring stdout?

答:
General remarks

Reiterating what I've said before on SO in other answers.

You aren't closing enough file descriptors in the child process.

Rule of thumb: If you
dup2()
one end of a pipe to standard input or standard output, close both of the
original file descriptors returned by
pipe()
as soon as possible.
In particular, you should close them before using any of the
exec*()
family of functions.

The rule also applies if you duplicate the descriptors with either
dup()
or
fcntl()
with F_DUPFD or F_DUPFD_CLOEXEC.

If the parent process will not communicate with any of its children via
the pipe, it must ensure that it closes both ends of the pipe early
enough (before waiting, for example) so that its children can receive
EOF indications on read (or get SIGPIPE signals or write errors on
write), rather than blocking indefinitely.
Even if the parent uses the pipe without using dup2(), it should
normally close at least one end of the pipe — it is extremely rare for
a program to read and write on both ends of a single pipe.

Note that the O_CLOEXEC option to
open(),
and the FD_CLOEXEC and F_DUPFD_CLOEXEC options to fcntl() can also factor
into this discussion.

If you use
posix_spawn()
and its extensive family of support functions (21 functions in total),
you will need to review how to close file descriptors in the spawned process
(posix_spawn_file_actions_addclose(),
etc.).

Note that using dup2(a, b) is safer than using close(b); dup(a);
for a variety of reasons.
One is that if you want to force the file descriptor to a larger than
usual number, dup2() is the only sensible way to do that.
Another is that if a is the same as b (e.g. both 0), then dup2()
handles it correctly (it doesn't close b before duplicating a)
whereas the separate close() and dup() fails horribly.
This is an unlikely, but not impossible, circumstance.

Analysis of code

The question contains the code:

```<code>#include <stdio.h>
#include <unistd.h>

void main(int argv, char *argc) {
    int stdin_copy = dup(STDIN_FILENO);
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        fclose(stdout);
        close(testpipe[1]);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        fprintf(stderr, "initial value: %s\n", initialval);
        wait(NULL);
        dup2(stdin_copy, 0);
        dup2(stdout_copy, 1);
        printf("done");//was not displayed when I run code.
    }
}
</code>```

The line void main(int argv, char *argc) { should be int main(void) since you do not use the command line arguments.  You also have the names argv and argc reversed from the normal convention — the first argument is normally called argc (argument count) and the second is normally called argv (argument vector).  Additionally, the type for the second argument should be char **argv (or char **argc if you want to confuse all your casual readers).  See also What should main() return in C and C++?

The next block of code that warrants discussion is:

```<code>    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    }
</code>```

This breaks the rule of thumb.  You should also put error handling code after the execl().

```<code>if (PID == 0)
{
    dup2(testpipe[0], STDIN_FILENO);
    close(testpipe[0]);
    close(testpipe[1]);
    execl("./multby", "multby", "3", (char *)NULL);
    fprintf(stderr, "failed to execute ./multby\n");
    exit(EXIT_FAILURE);
}
</code>```

The next block of code to analyze is:

```<code>dup2(testpipe[1], 1);
close(testpipe[0]);
printf("5");
fclose(stdout);
close(testpipe[1]);
</code>```

In theory, you should use STDOUT_FILENO instead of 1, but I have considerable sympathy with the use of 1 (not least because when I first learned C, there was no such symbolic constant).  You do actually close both ends of the pipe, but I'd prefer to see both closes immediately after the dup2() call, in line with the rule of thumb.  The printf() without a newline does send anything down the pipe; it stashes the 5 in the I/O buffer.

As Chris Dodd identified in their answer, the fclose(stdout) call is a source of much trouble.  You should probably simply replace it with fflush(stdout).

Moving on:

```<code>char initialval[100];
read(testpipe[0], initialval, 100);
fprintf(stderr, "initial value: %s\n", initialval);
wait(NULL);
dup2(stdin_copy, 0);
dup2(stdout_copy, 1);
printf("done");
</code>```

You didn't check whether the read() worked.  It didn't; it failed with EBADF, because just above this you use close(testpipe[0]);.  What you print on stderr there is an uninitialized string — that's not good.  In practice, if you want to read information from the child reliably, you need two pipes, one for parent-to-child communication and the other for child-to-parent communication.  Otherwise, there's no guarantee that the parent won't read what it wrote.  If you waited for the child to die before reading, you'd be in with a decent chance of it working, but you can't always rely on being able to do that.

The first of the two dup2() calls is pointless; you didn't change the redirection for standard input (so in fact stdin_copy is unnecessary).  The second changes the assignment of the standard output file descriptor, but you had already closed stdout, so there is no easy way to reopen it so that the printf() would work.  The message should end with a newline — most printf() format strings should end with a newline, unless it is deliberately being used to build up a single line of output piecemeal.  However, if you paid attention to the return value, you'd find that it failed (-1) and the chances are good that you'd find errno == EBADF again.

Fixing the code — fragile solution

Given this code for multby.c:

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

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage; %s number", argv[0]);
        return 1;
    }
    int multiplier = atoi(argv[1]);
    int number;
    if (scanf("%d", &number) == 1)
        printf("%d\n", number * multiplier);
    else
        fprintf(stderr, "%s: failed to read a number from standard input\n", argv[0]);
    return 0;
}
</code>```

and this code (as pipe23.c, compiled to pipe23):

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

int main(void)
{
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0)
    {
        dup2(testpipe[0], 0);
        dup2(testpipe[1], 1);
        close(testpipe[1]);
        close(testpipe[0]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
        fprintf(stderr, "failed to execute ./multby (%d: %s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
    else
    {
        dup2(testpipe[1], 1);
        close(testpipe[1]);
        printf("5\n");
        fflush(stdout);
        close(1);
        wait(NULL);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        close(testpipe[0]);
        fprintf(stderr, "initial value: [%s]\n", initialval);
        dup2(stdout_copy, 1);
        printf("done\n");
    }
}
</code>```

the combination barely works — it is not a resilient solution.  For example, I added the newline after the 5.  The child waits for another character after the 5 to determine that it has finished reading the number.  It doesn't get EOF because it has the write end of the pipe open for sending the response to the parent, even if it is hung reading from the pipe so it never will write to it.  But because it only attempts to read one number, it is OK.

The output is:

```<code>initial value: [15
]
done
</code>```

Fixing the code — robust solution

If you were dealing with arbitrary quantities of numbers, you'd need to use two pipes — it is the only reliable way of doing the task.  This would also work for a single number passed to the child, of course.

Here's a modified multby.c which loops on reading:

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

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage; %s number", argv[0]);
        return 1;
    }
    int multiplier = atoi(argv[1]);
    int number;
    while (scanf("%d", &number) == 1)
        printf("%d\n", number * multiplier);
    return 0;
}
</code>```

and here's a modified pipe23.c that uses two pipes and writes 3 numbers to the child, and gets back three results.  Note that it doesn't need to put a newline after the third number with this organization (though there'd be no harm done if it did include a newline).  Also, if you're devious, the second space in the list of numbers is unnecessary too; the - isn't part of the second number, so the scanning stops after the 0.

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

int main(void)
{
    int stdout_copy = dup(STDOUT_FILENO);
    int p_to_c[2];
    int c_to_p[2];
    if (pipe(p_to_c) != 0 || pipe(c_to_p) != 0)
    {
        fprintf(stderr, "failed to open a pipe (%d: %s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
    int PID = fork();
    if (PID == 0)
    {
        dup2(p_to_c[0], 0);
        dup2(c_to_p[1], 1);
        close(c_to_p[0]);
        close(c_to_p[1]);
        close(p_to_c[0]);
        close(p_to_c[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
        fprintf(stderr, "failed to execute ./multby (%d: %s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
    else
    {
        dup2(p_to_c[1], 1);
        close(p_to_c[1]);
        close(p_to_c[0]);
        close(c_to_p[1]);
        printf("5 10 -15");
        fflush(stdout);
        close(1);
        char initialval[100];
        int n = read(c_to_p[0], initialval, 100);
        if (n < 0)
        {
            fprintf(stderr, "failed to read from the child (%d: %s)\n", errno, strerror(errno));
            exit(EXIT_FAILURE);
        }
        close(c_to_p[0]);
        wait(NULL);
        fprintf(stderr, "initial value: [%.*s]\n", n, initialval);
        dup2(stdout_copy, 1);
        printf("done\n");
    }
}
</code>```

Note that there are lots of calls to close() in there — two for each of the 4 descriptors involved in handling two pipes.  This is normal.  Not taking care to close the file descriptors can easily lead to hung systems.

The output from running this pipe23 is this, which is what I wanted:

```<code>    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    }
</code>```0

Body:
Using the advise found here: Restoring stdout after using dup
I tried to restore the stdin and stdout. However, when using printf to check if stdout was restored I could not read an output.
The code is as follows. After restoring stdout as 1, I tried printing "done".

#include <stdio.h>
#include <unistd.h>

void main(int argv, char *argc) {
    int stdin_copy = dup(STDIN_FILENO);
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        fclose(stdout);
        close(testpipe[1]);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        fprintf(stderr, "initial value: %s\n", initialval);
        wait(NULL);
        dup2(stdin_copy, 0);
        dup2(stdout_copy, 1);
        printf("done");//was not displayed when I run code.
    }
}

However, I did not see a "done" when I ran the code. (There should be a done after 15).
This is my output:
initial value:
exec successful
a: 3
b: 5
multby successful
15

What did I do wrong when restoring stdout?

Body:
General remarks

Reiterating what I've said before on SO in other answers.

You aren't closing enough file descriptors in the child process.

Rule of thumb: If you
dup2()
one end of a pipe to standard input or standard output, close both of the
original file descriptors returned by
pipe()
as soon as possible.
In particular, you should close them before using any of the
exec*()
family of functions.

The rule also applies if you duplicate the descriptors with either
dup()
or
fcntl()
with F_DUPFD or F_DUPFD_CLOEXEC.

If the parent process will not communicate with any of its children via
the pipe, it must ensure that it closes both ends of the pipe early
enough (before waiting, for example) so that its children can receive
EOF indications on read (or get SIGPIPE signals or write errors on
write), rather than blocking indefinitely.
Even if the parent uses the pipe without using dup2(), it should
normally close at least one end of the pipe — it is extremely rare for
a program to read and write on both ends of a single pipe.

Note that the O_CLOEXEC option to
open(),
and the FD_CLOEXEC and F_DUPFD_CLOEXEC options to fcntl() can also factor
into this discussion.

If you use
posix_spawn()
and its extensive family of support functions (21 functions in total),
you will need to review how to close file descriptors in the spawned process
(posix_spawn_file_actions_addclose(),
etc.).

Note that using dup2(a, b) is safer than using close(b); dup(a);
for a variety of reasons.
One is that if you want to force the file descriptor to a larger than
usual number, dup2() is the only sensible way to do that.
Another is that if a is the same as b (e.g. both 0), then dup2()
handles it correctly (it doesn't close b before duplicating a)
whereas the separate close() and dup() fails horribly.
This is an unlikely, but not impossible, circumstance.

Analysis of code

The question contains the code:

#include <stdio.h>
#include <unistd.h>

void main(int argv, char *argc) {
    int stdin_copy = dup(STDIN_FILENO);
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        fclose(stdout);
        close(testpipe[1]);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        fprintf(stderr, "initial value: %s\n", initialval);
        wait(NULL);
        dup2(stdin_copy, 0);
        dup2(stdout_copy, 1);
        printf("done");//was not displayed when I run code.
    }
}

The line void main(int argv, char *argc) { should be int main(void) since you do not use the command line arguments.  You also have the names argv and argc reversed from the normal convention — the first argument is normally called argc (argument count) and the second is normally called argv (argument vector).  Additionally, the type for the second argument should be char **argv (or char **argc if you want to confuse all your casual readers).  See also What should main() return in C and C++?

The next block of code that warrants discussion is:

    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    }

This breaks the rule of thumb.  You should also put error handling code after the execl().

if (PID == 0)
{
    dup2(testpipe[0], STDIN_FILENO);
    close(testpipe[0]);
    close(testpipe[1]);
    execl("./multby", "multby", "3", (char *)NULL);
    fprintf(stderr, "failed to execute ./multby\n");
    exit(EXIT_FAILURE);
}

The next block of code to analyze is:

dup2(testpipe[1], 1);
close(testpipe[0]);
printf("5");
fclose(stdout);
close(testpipe[1]);

In theory, you should use STDOUT_FILENO instead of 1, but I have considerable sympathy with the use of 1 (not least because when I first learned C, there was no such symbolic constant).  You do actually close both ends of the pipe, but I'd prefer to see both closes immediately after the dup2() call, in line with the rule of thumb.  The printf() without a newline does send anything down the pipe; it stashes the 5 in the I/O buffer.

As Chris Dodd identified in their answer, the fclose(stdout) call is a source of much trouble.  You should probably simply replace it with fflush(stdout).

Moving on:

char initialval[100];
read(testpipe[0], initialval, 100);
fprintf(stderr, "initial value: %s\n", initialval);
wait(NULL);
dup2(stdin_copy, 0);
dup2(stdout_copy, 1);
printf("done");

You didn't check whether the read() worked.  It didn't; it failed with EBADF, because just above this you use close(testpipe[0]);.  What you print on stderr there is an uninitialized string — that's not good.  In practice, if you want to read information from the child reliably, you need two pipes, one for parent-to-child communication and the other for child-to-parent communication.  Otherwise, there's no guarantee that the parent won't read what it wrote.  If you waited for the child to die before reading, you'd be in with a decent chance of it working, but you can't always rely on being able to do that.

The first of the two dup2() calls is pointless; you didn't change the redirection for standard input (so in fact stdin_copy is unnecessary).  The second changes the assignment of the standard output file descriptor, but you had already closed stdout, so there is no easy way to reopen it so that the printf() would work.  The message should end with a newline — most printf() format strings should end with a newline, unless it is deliberately being used to build up a single line of output piecemeal.  However, if you paid attention to the return value, you'd find that it failed (-1) and the chances are good that you'd find errno == EBADF again.

Fixing the code — fragile solution

Given this code for multby.c:

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

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage; %s number", argv[0]);
        return 1;
    }
    int multiplier = atoi(argv[1]);
    int number;
    if (scanf("%d", &number) == 1)
        printf("%d\n", number * multiplier);
    else
        fprintf(stderr, "%s: failed to read a number from standard input\n", argv[0]);
    return 0;
}

and this code (as pipe23.c, compiled to pipe23):

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

int main(void)
{
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0)
    {
        dup2(testpipe[0], 0);
        dup2(testpipe[1], 1);
        close(testpipe[1]);
        close(testpipe[0]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
        fprintf(stderr, "failed to execute ./multby (%d: %s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
    else
    {
        dup2(testpipe[1], 1);
        close(testpipe[1]);
        printf("5\n");
        fflush(stdout);
        close(1);
        wait(NULL);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        close(testpipe[0]);
        fprintf(stderr, "initial value: [%s]\n", initialval);
        dup2(stdout_copy, 1);
        printf("done\n");
    }
}

the combination barely works — it is not a resilient solution.  For example, I added the newline after the 5.  The child waits for another character after the 5 to determine that it has finished reading the number.  It doesn't get EOF because it has the write end of the pipe open for sending the response to the parent, even if it is hung reading from the pipe so it never will write to it.  But because it only attempts to read one number, it is OK.

The output is:

initial value: [15
]
done

Fixing the code — robust solution

If you were dealing with arbitrary quantities of numbers, you'd need to use two pipes — it is the only reliable way of doing the task.  This would also work for a single number passed to the child, of course.

Here's a modified multby.c which loops on reading:

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

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage; %s number", argv[0]);
        return 1;
    }
    int multiplier = atoi(argv[1]);
    int number;
    while (scanf("%d", &number) == 1)
        printf("%d\n", number * multiplier);
    return 0;
}

and here's a modified pipe23.c that uses two pipes and writes 3 numbers to the child, and gets back three results.  Note that it doesn't need to put a newline after the third number with this organization (though there'd be no harm done if it did include a newline).  Also, if you're devious, the second space in the list of numbers is unnecessary too; the - isn't part of the second number, so the scanning stops after the 0.

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

int main(void)
{
    int stdout_copy = dup(STDOUT_FILENO);
    int p_to_c[2];
    int c_to_p[2];
    if (pipe(p_to_c) != 0 || pipe(c_to_p) != 0)
    {
        fprintf(stderr, "failed to open a pipe (%d: %s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
    int PID = fork();
    if (PID == 0)
    {
        dup2(p_to_c[0], 0);
        dup2(c_to_p[1], 1);
        close(c_to_p[0]);
        close(c_to_p[1]);
        close(p_to_c[0]);
        close(p_to_c[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
        fprintf(stderr, "failed to execute ./multby (%d: %s)\n", errno, strerror(errno));
        exit(EXIT_FAILURE);
    }
    else
    {
        dup2(p_to_c[1], 1);
        close(p_to_c[1]);
        close(p_to_c[0]);
        close(c_to_p[1]);
        printf("5 10 -15");
        fflush(stdout);
        close(1);
        char initialval[100];
        int n = read(c_to_p[0], initialval, 100);
        if (n < 0)
        {
            fprintf(stderr, "failed to read from the child (%d: %s)\n", errno, strerror(errno));
            exit(EXIT_FAILURE);
        }
        close(c_to_p[0]);
        wait(NULL);
        fprintf(stderr, "initial value: [%.*s]\n", n, initialval);
        dup2(stdout_copy, 1);
        printf("done\n");
    }
}

Note that there are lots of calls to close() in there — two for each of the 4 descriptors involved in handling two pipes.  This is normal.  Not taking care to close the file descriptors can easily lead to hung systems.

The output from running this pipe23 is this, which is what I wanted:

initial value: [15
30
-45
]
done


问:
Convert JSON format to CSV Bash using jq
Here is my sample code:

```<code>[
    {
        "urlString" : "https://www.test.com/products/gift-card",
        "imageUrl" : "https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792"
    },
    {
        "urlString" : "https://www.test.com/products/gift-card",
        "imageUrl" : "https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792"
    },
]
</code>```

I want to create a CSV file with the output:

```<code>https://www.test.com/products/gift-card,https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792
https://www.test.com/products/gift-card,https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792
</code>```

Header tags are not essential but if they are in the solution thats fine.

thanks for the help!

答:
```<code>jq -r '.[] | [.urlString, .imageUrl] | @csv'
</code>```

See this on jqplay at https://jqplay.org/s/zL6HpSSFw0

Body:
Here is my sample code:

[
    {
        "urlString" : "https://www.test.com/products/gift-card",
        "imageUrl" : "https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792"
    },
    {
        "urlString" : "https://www.test.com/products/gift-card",
        "imageUrl" : "https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792"
    },
]

I want to create a CSV file with the output:

https://www.test.com/products/gift-card,https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792
https://www.test.com/products/gift-card,https://cdn.shopify.com/s/files/1/0454/6253/products/dope_mone_850x.jpg?v=1539288792

Header tags are not essential but if they are in the solution thats fine.

thanks for the help!

Body:
jq -r '.[] | [.urlString, .imageUrl] | @csv'

See this on jqplay at https://jqplay.org/s/zL6HpSSFw0


问:
How to trigger a phone call when clicking a link in a web page on mobile phone
I need to build a web page for mobile devices. There's only one thing I still haven't figured out: how can I trigger a phone call through the click of text?

Is there a special URL I could enter like the mailto: tag for emails?

Device specific solution are not preferred.

I know iPhone automatically recognizes phone numbers and creates a link for this, but it would be great if this could be done for images too... and also for most mobile devices.

答:
Just use HTML anchor tag  and start the attribute href with tel:. I suggest starting the phone number with the country code. pay attention to the following example:

```<code><a href="tel:+989123456789">NO Different What it is</a>
</code>```

For this example, the country code is +98.

Hint: It is so suitable for cellphones, I know tel: prefix calls FaceTime on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.

For more information: you can visit the list of URL schemes supported by browsers to know all href values prefixes.

Body:
Just use HTML anchor tag <a> and start the attribute href with tel:. I suggest starting the phone number with the country code. pay attention to the following example:

<a href="tel:+989123456789">NO Different What it is</a>

For this example, the country code is +98.

Hint: It is so suitable for cellphones, I know tel: prefix calls FaceTime on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.

For more information: you can visit the list of URL schemes supported by browsers to know all href values prefixes.


问:
How to "name" each JSON object
I am sure this is a rather simple thing to do, but I am not able to figure it out.

I have a dataframe in R that looks like this:

```<code>a   b   c
1   9   J
2   5   K
</code>```

When I use toJSON and pass the dataframe as a named list

```<code>val <- toJSON(list( table = df), pretty = TRUE)
</code>```

I get:

```<code>{  "table":[
   {
     {
       "a":"1",
       "b":"9",
       "c":"J"
     }
   },
   {
     {
       "a":"2",
       "b":"5",
       "c":"K"
     }
   }
 ]
}
</code>```

How can I get each JSON object to be named "entry" as shown below:

```<code>{  "table":[
   {
     "entry":{
       "a":"1",
       "b":"9",
       "c":"J"
     }
   },
   {
     "entry":{
       "a":"2",
       "b":"5",
       "c":"K"
     }
   }
 ]
}
</code>```

答:
To get the structure you want is a bit complicated becaues of the {"entry":{"a":1,"b":9,"c":"J"}} object

To get this structure you need to have a named list

```<code>lst <- list( list(a = 1, b = 9, c = "J") )
attr( lst, "names" ) <- "entry"

toJSON( lst, auto_unbox = TRUE )
# {"entry":{"a":1,"b":9,"c":"J"}}
</code>```

Therefore each row of your data.frame needs to be a named list

```<code>res <- lapply( seq_len( nrow( df ) ), function(i) {
  lst <- list( as.list( df[i, , drop = F] ) )
  attr( lst, "names" ) <- "entry"
  lst
})

## add the 'table'
res <- list( table = res )

toJSON( res, auto_unbox = TRUE, pretty = TRUE )
# {
#   "table": [
#     {
#       "entry": {
#         "a": 1,
#         "b": 9,
#         "c": "J"
#       }
#     },
#     {
#       "entry": {
#         "a": 2,
#         "b": 5,
#         "c": "K"
#       }
#     }
#   ]
# }

</code>```

Title: How to "name" each JSON object

Body:
I am sure this is a rather simple thing to do, but I am not able to figure it out.

I have a dataframe in R that looks like this:

a   b   c
1   9   J
2   5   K

When I use toJSON and pass the dataframe as a named list

val <- toJSON(list( table = df), pretty = TRUE)

I get:

{  "table":[
   {
     {
       "a":"1",
       "b":"9",
       "c":"J"
     }
   },
   {
     {
       "a":"2",
       "b":"5",
       "c":"K"
     }
   }
 ]
}

How can I get each JSON object to be named "entry" as shown below:

{  "table":[
   {
     "entry":{
       "a":"1",
       "b":"9",
       "c":"J"
     }
   },
   {
     "entry":{
       "a":"2",
       "b":"5",
       "c":"K"
     }
   }
 ]
}

Body:
To get the structure you want is a bit complicated becaues of the {"entry":{"a":1,"b":9,"c":"J"}} object

To get this structure you need to have a named list

lst <- list( list(a = 1, b = 9, c = "J") )
attr( lst, "names" ) <- "entry"

toJSON( lst, auto_unbox = TRUE )
# {"entry":{"a":1,"b":9,"c":"J"}}

Therefore each row of your data.frame needs to be a named list

res <- lapply( seq_len( nrow( df ) ), function(i) {
  lst <- list( as.list( df[i, , drop = F] ) )
  attr( lst, "names" ) <- "entry"
  lst
})

## add the 'table'
res <- list( table = res )

toJSON( res, auto_unbox = TRUE, pretty = TRUE )
# {
#   "table": [
#     {
#       "entry": {
#         "a": 1,
#         "b": 9,
#         "c": "J"
#       }
#     },
#     {
#       "entry": {
#         "a": 2,
#         "b": 5,
#         "c": "K"
#       }
#     }
#   ]
# }


问:
Recall User Form Position
Haven't been able to locate many examples on the internet and absolutely nothing on the forum regarding saving the position of a User Form for reload.

This macro is seen on several websites :

```<code>Copy to clipboard
Option Explicit

Private Sub UserForm_Initialize()
If GetSetting("My Settings Folder", Me.Name, "Left Position") = "" _
    And GetSetting("My Settings Folder", Me.Name, "Top Position") = "" Then
    Me.StartUpPosition = 1 ' CenterOwner
Else
    Me.Left = GetSetting("My Settings Folder", Me.Name, "Left Position")
    Me.Top = GetSetting("My Settings Folder", Me.Name, "Top Position")
End If

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    SaveSetting "My Settings Folder", Me.Name, "Left Position", Me.Left
    SaveSetting "My Settings Folder", Me.Name, "Top Position", Me.Top
End Sub
</code>```

However ... it isn't working here.

What am I doing wrong ?

答:
The answer was very obvious ... except I overlooked it and the few samples on the internet did not mention this :

The StartUpPosition of the userform must be set to "0" (zero). Here is the edited macro :

```<code>Private Sub UserForm_Initialize()
    If GetSetting("My Settings Folder", Me.Name, "Left Position") = "" _
        And GetSetting("My Settings Folder", Me.Name, "Top Position") = "" Then
        Me.StartUpPosition = 1 ' CenterOwner
    Else
        Me.StartUpPosition = 0
        Me.Left = GetSetting("My Settings Folder", Me.Name, "Left Position")
        Me.Top = GetSetting("My Settings Folder", Me.Name, "Top Position")
    End If

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    SaveSetting "My Settings Folder", Me.Name, "Left Position", Me.Left
    SaveSetting "My Settings Folder", Me.Name, "Top Position", Me.Top
End Sub
</code>```

Title: Recall User Form Position

Body:
Haven't been able to locate many examples on the internet and absolutely nothing on the forum regarding saving the position of a User Form for reload.

This macro is seen on several websites :

Copy to clipboard
Option Explicit

Private Sub UserForm_Initialize()
If GetSetting("My Settings Folder", Me.Name, "Left Position") = "" _
    And GetSetting("My Settings Folder", Me.Name, "Top Position") = "" Then
    Me.StartUpPosition = 1 ' CenterOwner
Else
    Me.Left = GetSetting("My Settings Folder", Me.Name, "Left Position")
    Me.Top = GetSetting("My Settings Folder", Me.Name, "Top Position")
End If

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    SaveSetting "My Settings Folder", Me.Name, "Left Position", Me.Left
    SaveSetting "My Settings Folder", Me.Name, "Top Position", Me.Top
End Sub

However ... it isn't working here.

What am I doing wrong ?

Body:
The answer was very obvious ... except I overlooked it and the few samples on the internet did not mention this :

The StartUpPosition of the userform must be set to "0" (zero). Here is the edited macro :

Private Sub UserForm_Initialize()
    If GetSetting("My Settings Folder", Me.Name, "Left Position") = "" _
        And GetSetting("My Settings Folder", Me.Name, "Top Position") = "" Then
        Me.StartUpPosition = 1 ' CenterOwner
    Else
        Me.StartUpPosition = 0
        Me.Left = GetSetting("My Settings Folder", Me.Name, "Left Position")
        Me.Top = GetSetting("My Settings Folder", Me.Name, "Top Position")
    End If

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    SaveSetting "My Settings Folder", Me.Name, "Left Position", Me.Left
    SaveSetting "My Settings Folder", Me.Name, "Top Position", Me.Top
End Sub


问:
AWS DocumentDB change stream data availability from default to 24 hours
Started to use AWS DocumentDb change stream, want to keep Events written to a change stream for a database for 24 hours instead of default 3 hours.
How I can do this.
Standard AWS docs provide just this:</p>

```<code>db.adminCommand({modifyChangeStreams: 1,
    database: "",
    collection: "",
    enable: true
    });
</code>```

答:
ekaterina@, you are correct, the docs for change streams are not clear and we will fix that. You can change the default retention period change_stream_log_retention_duration to 24 hours. Here are the docs on how to change cluster parameters, in general:
https://docs.aws.amazon.com/documentdb/latest/developerguide/cluster_parameter_groups-parameters.html</p>

Body:
Started to use AWS DocumentDb change stream, want to keep Events written to a change stream for a database for 24 hours instead of default 3 hours.
How I can do this.
Standard AWS docs provide just this:

db.adminCommand({modifyChangeStreams: 1,
    database: "",
    collection: "",
    enable: true
    });


问:
Convert date/time format from Etc/GMT to ISO
I need to convert date/time values.

For example I want to convert this "2019-11-21 09:53:10 Etc/GMT" to a value with the same format as this "2020-02-13T15:24:47.977Z".

If you can provide the resulting equivalent value of the given example, I can make that as reference so I can already find the correct code for the conversion.

Or else if you can provide the exact javascript code for the conversion, that is better. I am using 'moment' and 'moment-timezone'.

答:
"2019-11-21 09:53:10 Etc/GMT" is not a format supported by ECMA-262 so parsing is implementation dependent and can't be relied on, e.g. in Safari:

```<code>new Date("2019-11-21 09:53:10 Etc/GMT");
</code>```

returns an invalid Date.

If you just want to convert "2019-11-21 09:53:10 Etc/GMT" to a valid ISO 8601 format that is also supported by ECMA-262, then there is no need for a Date object at all, just reformat the string slightly.

let timestamp = '2019-11-21 09:53:10 Etc/GMT'
let iso = timestamp.substr(0, 19).replace(' ','T') + 'Z';

console.log(iso);

// or more tolerant of time part
let timestamp2 = '2019-11-21 09:53:10.123 Etc/GMT'
console.log( timestamp2.replace(' ','T').replace(/ Etc.*$/,'Z') );

// Or
console.log( timestamp2.split(' ').slice(0,2).join('T') + 'Z');

// Or
let [d, t, rest] = timestamp2.split(' ');
console.log(`${d}T${t}Z`);```
</div>
</div>
</p>

<p>There are many ways to reformat the string without transforming to a Date and back to string. Of course if you have a string like:</p>

```'2019-11-21 09:53:10 Etc/GMT-4'
```

then you will need to manually parse it to get UTC as "Etc/GMT" offsets have the opposite sense to common offsets (i.e. they are +ve west and -ve east).

Body:
"2019-11-21 09:53:10 Etc/GMT" is not a format supported by ECMA-262 so parsing is implementation dependent and can't be relied on, e.g. in Safari:

new Date("2019-11-21 09:53:10 Etc/GMT");

returns an invalid Date.

If you just want to convert "2019-11-21 09:53:10 Etc/GMT" to a valid ISO 8601 format that is also supported by ECMA-262, then there is no need for a Date object at all, just reformat the string slightly.

let timestamp = '2019-11-21 09:53:10 Etc/GMT'
let iso = timestamp.substr(0, 19).replace(' ','T') + 'Z';

console.log(iso);

// or more tolerant of time part
let timestamp2 = '2019-11-21 09:53:10.123 Etc/GMT'
console.log( timestamp2.replace(' ','T').replace(/ Etc.*$/,'Z') );

// Or
console.log( timestamp2.split(' ').slice(0,2).join('T') + 'Z');

// Or
let [d, t, rest] = timestamp2.split(' ');
console.log(`${d}T${t}Z`);

There are many ways to reformat the string without transforming to a Date and back to string. Of course if you have a string like:

'2019-11-21 09:53:10 Etc/GMT-4'

then you will need to manually parse it to get UTC as "Etc/GMT" offsets have the opposite sense to common offsets (i.e. they are +ve west and -ve east).


问:
Time complexity of creating nested lists in Python
I have run into an oddity with creating nested lists in Python 2.6.6.

Consider the following two functions:

```<code>def lists(n):
    start_time = time.time()
    lists = [None]*n
    for i in xrange(n):
            lists[i] = [None]*n
            for j in xrange(n):
                    lists[i][j] = []
    print time.time() - start_time

def simple_lists(n):
    start_time = time.time()
    lists = [None]*n
    for i in xrange(n):
            lists[i] = [None]*n
            for j in xrange(n):
                    lists[i][j] = False
    print time.time() - start_time
</code>```

They both allocate an array of size n*n. One assigns all values as "False", and one assigns all values as empty lists. They should both run in O(n^2) as far as I can see. However, this does not seem the case... Observe the following test runs:

```<code>>>> for i in [4000, 8000, 16000]: simple_lists(i)
2.11170578003
8.67467808723
34.0958559513
>>> for i in [1000, 2000, 4000]: lists(i)
1.13742399216
7.39806008339
78.0808939934
</code>```

As you can see, simple_lists() seems to grow roughly O(n^2), while lists() seems to grow over O(n^3)!

What's going on here? This quirk is completely and utterly ruining the complexity of my code, and I can't explain why it's behaving like this. Does anyone have any ideas?

Edit: List comprehensions seem to cause the same complexity issues.

Redefining lists() like

```<code>def lists(n):
    start_time = time.time()
    lists = [[[] for y in xrange(n)] for x in xrange(n)]
    print time.time() - start_time
</code>```

causes the following results

```<code>>>> for i in [1000, 2000, 4000]: lists(i)
0.388785839081
4.45830011368
65.6449248791
</code>```

... which is still clearly growing at a pace quicker than O(n^2) (and even quicker than O(n^3) - sheesh).

edit2: After some further looking into the problem, it seems it's caused by the garbage collector. After running gc.disable(), this is the result with the original lists() definition:

```<code>>>> for i in [1000, 2000, 4000]: lists(i)
...
0.155457019806
0.616811990738
2.38965821266
</code>```

which is pretty damn neatly O(n^2).

Moral of the story: don't trust the garbage collector!

答:
Generate the first list first and it will do it in O(n) time.</p>

```<code>def simple_list(n):
    import time
    start_time = time.process_time()
    k=[[] for y in range(n)]
    lists = [k for x in range(n)]
    end_time=time.process_time()
    print (end_time - start_time)
</code>```

Body:
I have run into an oddity with creating nested lists in Python 2.6.6.

Consider the following two functions:

def lists(n):
    start_time = time.time()
    lists = [None]*n
    for i in xrange(n):
            lists[i] = [None]*n
            for j in xrange(n):
                    lists[i][j] = []
    print time.time() - start_time

def simple_lists(n):
    start_time = time.time()
    lists = [None]*n
    for i in xrange(n):
            lists[i] = [None]*n
            for j in xrange(n):
                    lists[i][j] = False
    print time.time() - start_time

They both allocate an array of size n*n. One assigns all values as "False", and one assigns all values as empty lists. They should both run in O(n^2) as far as I can see. However, this does not seem the case... Observe the following test runs:

>>> for i in [4000, 8000, 16000]: simple_lists(i)
2.11170578003
8.67467808723
34.0958559513
>>> for i in [1000, 2000, 4000]: lists(i)
1.13742399216
7.39806008339
78.0808939934

As you can see, simple_lists() seems to grow roughly O(n^2), while lists() seems to grow over O(n^3)!

What's going on here? This quirk is completely and utterly ruining the complexity of my code, and I can't explain why it's behaving like this. Does anyone have any ideas?

Edit: List comprehensions seem to cause the same complexity issues.

Redefining lists() like

def lists(n):
    start_time = time.time()
    lists = [[[] for y in xrange(n)] for x in xrange(n)]
    print time.time() - start_time

causes the following results

>>> for i in [1000, 2000, 4000]: lists(i)
0.388785839081
4.45830011368
65.6449248791

... which is still clearly growing at a pace quicker than O(n^2) (and even quicker than O(n^3) - sheesh).

edit2: After some further looking into the problem, it seems it's caused by the garbage collector. After running gc.disable(), this is the result with the original lists() definition:

>>> for i in [1000, 2000, 4000]: lists(i)
...
0.155457019806
0.616811990738
2.38965821266

which is pretty damn neatly O(n^2).

Moral of the story: don't trust the garbage collector!

Body:
Generate the first list first and it will do it in O(n) time.

def simple_list(n):
    import time
    start_time = time.process_time()
    k=[[] for y in range(n)]
    lists = [k for x in range(n)]
    end_time=time.process_time()
    print (end_time - start_time)


问:
Vb.net Insert to accs
It says syntax error on INSERT INTO</p>

```<code>Connection.Open()
Query = "INSERT INTO Admin (Username, Password, FullName, Office) Values ('" & TXT_USERNAME.Text & "','" & TXT_PASSWORD.Text & "','" & TXT_NAME.Text & "','" & CB_UNIT.Text & "');"
Command = New OleDbCommand(Query, Connection)
Command.ExecuteNonQuery()
</code>```

答:
The specific issue in this case is that Password is a reserved word in Jet/Access SQL.  In order to use a reserved word as an identifier, you need to escape it. In Jet/Access SQL, that means wrapping it in brackets:

```<code>INSERT INTO Admin (Username, [Password], FullName, Office) Values (...)
</code>```

Some people prefer to escape all identifiers, just to be on the safe side.

There are other issues there too though.  Most importantly, you should learn how to use parameters in ADO.NET code.  As it stands, your code would crash your app with another syntax error if someone's full name was "John O'Brien".  Using parameters avoids issues with single-quotes, formatting of dates and numbers and, most importantly, protects against SQL injection attacks.  Learn the proper way IMMEDIATELY.

Title: Vb.net Insert to accs

Body:
It says syntax error on INSERT INTO

Connection.Open()
Query = "INSERT INTO Admin (Username, Password, FullName, Office) Values ('" & TXT_USERNAME.Text & "','" & TXT_PASSWORD.Text & "','" & TXT_NAME.Text & "','" & CB_UNIT.Text & "');"
Command = New OleDbCommand(Query, Connection)
Command.ExecuteNonQuery()

Body:
The specific issue in this case is that Password is a reserved word in Jet/Access SQL.  In order to use a reserved word as an identifier, you need to escape it. In Jet/Access SQL, that means wrapping it in brackets:

INSERT INTO Admin (Username, [Password], FullName, Office) Values (...)

Some people prefer to escape all identifiers, just to be on the safe side.

There are other issues there too though.  Most importantly, you should learn how to use parameters in ADO.NET code.  As it stands, your code would crash your app with another syntax error if someone's full name was "John O'Brien".  Using parameters avoids issues with single-quotes, formatting of dates and numbers and, most importantly, protects against SQL injection attacks.  Learn the proper way IMMEDIATELY.