问:
C# 8 nullables and Result container
I have a IResult<T> container that I use to handle errors. It looks like this:

```<code>public interface IResult<out T>
{
    ResultOutcome Outcome { get; }   //enum: {Failure, Uncertain, Success}
    string Description { get; }      //string describing the error, in case of !Success
    bool IsSuccess();                //Outcome == Success
    T Data { get; }                  //If success, it contains the data passed on, otherwise NULL
}
</code>```

And you'd use it like this:

```<code>IResult<int> GetSomething()
{
    try{
        int result = //things that might throw...
        return Result<int>.Success(result);
    }
    catch(Exception e)
    {
        return Result<int>.Failure($"Something went wrong: {e.Message}");
    }
}
</code>```

And then:

```<code>var result = GetSomething();
if (!result.IsSuccess()) return result; //<- error passed on.

int resultData = result.Data; //<- no errors, so there is something in here.

</code>```

Until now, all good. When I introduce the nullable types, though, I have a problem:

```<code>public interface IResult<out T> where T : class // unfortunately this is necessary
{
    ...
    T? Data { get; }                  //If success, it contains the data passed on, otherwise NULL
}
</code>```

```<code>var result = GetSomething();
if (!result.IsSuccess()) return result; //<- error passed on.

int resultData = result.Data; //<- WARNING!!! POSSIBLE DEREFERENCE OF NULL

</code>```

Now the question: I am sure that result.Data contains something, as it passed the IsSuccess() step. How can I reassure the compiler about it? Is there a way or C#8 nullable concept is just not compatible with this?

Are there other ways to handle results in a similar fashion? (passing on containers instead of exceptions).

P.s. 1

Please, don't suggest to use result.Data!;.

P.s. 2

This code is already used on a thousand of lines or more, so if the change can be on the interface, rather than on the usages, it would be way better.

答:
Here is the C# 8.0 part of the above (great!) @PanagiotisKanavos answer in one piece:</p>

```<code>using System;

#nullable enable

namespace ErrorHandling {
  public interface IResult<TSuccess, TError> {
    public bool OK { get; }

    public TSuccess Data => (this is Ok<TSuccess, TError>(var Data)) ? Data : throw new InvalidOperationException("An Error has no data");
    public TError Error => (this is Fail<TSuccess, TError>(var Error)) ? Error : throw new InvalidOperationException("A Success Result has no Description");

    public static IResult<TSuccess, TError> Good(TSuccess data) => new Ok<TSuccess, TError>(data);
    public static IResult<TSuccess, TError> Bad(TError error) => new Fail<TSuccess, TError>(error);
  }

  public class Ok<TSuccess, TError> : IResult<TSuccess, TError> {
    public bool OK => true;
    public TSuccess Data { get; }

    public Ok(TSuccess data) => Data = data;
    public void Deconstruct(out TSuccess data) => data = Data;
  }

  public class Fail<TSuccess, TError> : IResult<TSuccess, TError> {
    public bool OK => false;
    public TError Error { get; }

    public Fail(TError error) => Error = error;
    public void Deconstruct(out TError error) => error = Error;
  }

  class Main {
    public IResult<int, string> F() {
      if (DateTime.Now.Year < 2020) return IResult<int, string>.Good(3);
      return IResult<int, string>.Bad("error");
    }

    public void F1() {
      var message = F() switch {
        { OK: true, Data: var data } => $"Got some: {data}",
        { OK: false, Error: var error } => $"Oops {error}",
      };
      Console.WriteLine(message);
    }

    public void F2() {
      if (F() is { OK: false, Error: var error }) {
        Console.WriteLine(error);
        return;
      }

      if (F() is { OK: true, Data: var data }) { // Is there a way to get data without a new scope ?
        Console.WriteLine(data);
      }
    }
  }
}
</code>```

Title: C# 8 nullables and Result container

Body:
I have a IResult<T> container that I use to handle errors. It looks like this:

public interface IResult<out T>
{
    ResultOutcome Outcome { get; }   //enum: {Failure, Uncertain, Success}
    string Description { get; }      //string describing the error, in case of !Success
    bool IsSuccess();                //Outcome == Success
    T Data { get; }                  //If success, it contains the data passed on, otherwise NULL
}

And you'd use it like this:

IResult<int> GetSomething()
{
    try{
        int result = //things that might throw...
        return Result<int>.Success(result);
    }
    catch(Exception e)
    {
        return Result<int>.Failure($"Something went wrong: {e.Message}");
    }
}

And then:

var result = GetSomething();
if (!result.IsSuccess()) return result; //<- error passed on.

int resultData = result.Data; //<- no errors, so there is something in here.

Until now, all good. When I introduce the nullable types, though, I have a problem:

public interface IResult<out T> where T : class // unfortunately this is necessary
{
    ...
    T? Data { get; }                  //If success, it contains the data passed on, otherwise NULL
}

var result = GetSomething();
if (!result.IsSuccess()) return result; //<- error passed on.

int resultData = result.Data; //<- WARNING!!! POSSIBLE DEREFERENCE OF NULL

Now the question: I am sure that result.Data contains something, as it passed the IsSuccess() step. How can I reassure the compiler about it? Is there a way or C#8 nullable concept is just not compatible with this?

Are there other ways to handle results in a similar fashion? (passing on containers instead of exceptions).

P.s. 1

Please, don't suggest to use result.Data!;.

P.s. 2

This code is already used on a thousand of lines or more, so if the change can be on the interface, rather than on the usages, it would be way better.

Body:
Here is the C# 8.0 part of the above (great!) @PanagiotisKanavos answer in one piece:

using System;

#nullable enable

namespace ErrorHandling {
  public interface IResult<TSuccess, TError> {
    public bool OK { get; }

    public TSuccess Data => (this is Ok<TSuccess, TError>(var Data)) ? Data : throw new InvalidOperationException("An Error has no data");
    public TError Error => (this is Fail<TSuccess, TError>(var Error)) ? Error : throw new InvalidOperationException("A Success Result has no Description");

    public static IResult<TSuccess, TError> Good(TSuccess data) => new Ok<TSuccess, TError>(data);
    public static IResult<TSuccess, TError> Bad(TError error) => new Fail<TSuccess, TError>(error);
  }

  public class Ok<TSuccess, TError> : IResult<TSuccess, TError> {
    public bool OK => true;
    public TSuccess Data { get; }

    public Ok(TSuccess data) => Data = data;
    public void Deconstruct(out TSuccess data) => data = Data;
  }

  public class Fail<TSuccess, TError> : IResult<TSuccess, TError> {
    public bool OK => false;
    public TError Error { get; }

    public Fail(TError error) => Error = error;
    public void Deconstruct(out TError error) => error = Error;
  }

  class Main {
    public IResult<int, string> F() {
      if (DateTime.Now.Year < 2020) return IResult<int, string>.Good(3);
      return IResult<int, string>.Bad("error");
    }

    public void F1() {
      var message = F() switch {
        { OK: true, Data: var data } => $"Got some: {data}",
        { OK: false, Error: var error } => $"Oops {error}",
      };
      Console.WriteLine(message);
    }

    public void F2() {
      if (F() is { OK: false, Error: var error }) {
        Console.WriteLine(error);
        return;
      }

      if (F() is { OK: true, Data: var data }) { // Is there a way to get data without a new scope ?
        Console.WriteLine(data);
      }
    }
  }
}


来源: stackexchange

问:
Why do I get this GRPC Error "WARNING: EmulatorService.cpp:448: Cannot find certfile" when I start the emulator?
Good evening everyone, I have only been dealing with Java and Android Studio for a few months, can someone help me to solve this error? It occurs every time the emulator starts. Thank you

Emulator: Started GRPC server at 127.0.0.1:8554

Emulator: emulator: WARNING: EmulatorService.cpp:448: Cannot find certfile: C:\Users\Sawye.android\emulator-grpc.cer security will be disabled.

答: Got the same issue, I restarted the computer and then runned again the emulator and it worked. Important! you have to run the app, not debug it. You can use debug after the app is installed again in the emulator</p>

ContentLicense: CC BY-SA 4.0


问:
Mutate with paste0
How do I mutate a field when concatenating the name of the field?

```<code>library(tidyverse)
x <- "blah"
y <- "cyl"

mtcars %>%
  mutate(paste0(x,y) := as.factor(cyl)) # "Error: The LHS of `:=` must be a string or a symbol"

mtcars %>%
  mutate(paste0(x,y) = as.factor(cyl)) # Error: unexpected '=' in: "mtcars %>%  mutate(paste0(x,y) ="
</code>```

How ca I end up with a new field called 'blahcyl' that is a factor of cyl?

Title: Mutate with paste0

Body:
How do I mutate a field when concatenating the name of the field?

library(tidyverse)
x <- "blah"
y <- "cyl"

mtcars %>%
  mutate(paste0(x,y) := as.factor(cyl)) # "Error: The LHS of `:=` must be a string or a symbol"

mtcars %>%
  mutate(paste0(x,y) = as.factor(cyl)) # Error: unexpected '=' in: "mtcars %>%  mutate(paste0(x,y) ="

How ca I end up with a new field called 'blahcyl' that is a factor of cyl?

Body:
Evaluate the string with !!

library(dplyr)
mtcars %>% mutate(!!paste0(x,y) := as.factor(cyl))

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb blahcyl
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4       6
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4       6
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1       4
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1       6
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2       8
#...


问:
Supported OpenSL ES Features in Android
Android is supposed to support 3D audio via the OpenSL es API which is accesible via the NDK. That more or less works, I managed it to play sound via a created player and an output mix. But when I try to realise a listener with a 3D location interface (SL_IID_3DLOCATION constant) which is mandatory for playing 3D sound. But when I try to set the constant to SL_BOOLEAN_TRUE the result of the CreateListener method is 12 as passed to the LogCat. 12 is the value of the OpenSL es constant SL_RESULT_FEATURE_UNSUPPORTED. Below you can find a short part of the code, can anyone confirm if I do anything wrong or if the feature really is unsopported, meaning that the OpenSL es implementation does not support 3D audio?</p>

```<code>#define SL_RESULT_FEATURE_UNSUPPORTED       ((SLuint32) 0x0000000C)

const SLInterfaceID listener_ids[] = {SL_IID_3DLOCATION};
const SLboolean listener_req[] = {SL_BOOLEAN_TRUE};

result = (*engine)->CreateListener(engine, &listenerObject, 1, listener_ids, listener_req);
__android_log_print(ANDROID_LOG_VERBOSE, DEBUG_TAG, "CREATE: [%i]", result);

assert(SL_RESULT_SUCCESS == result);

result = (*listenerObject)->Realize(listenerObject, SL_BOOLEAN_FALSE);
__android_log_print(ANDROID_LOG_VERBOSE, DEBUG_TAG, "REALIZE: [%i]", result);

assert(SL_RESULT_SUCCESS == result);
</code>```

答:
You might want to take a look at this website: https://developer.android.com/ndk/guides/audio/opensl/opensl-for-android. It shows what is and (more importantly), what is not supported by the OpenSL ES API's for Android. I haven't worked with with the 3D location feature, but then again, I haven't had the need for it yet.

Anyway, maybe that site will give you more information about it...

ContentLicense: CC BY-SA 2.5

Title: Supported OpenSL ES Features in Android

Body:
Android is supposed to support 3D audio via the OpenSL es API which is accesible via the NDK. That more or less works, I managed it to play sound via a created player and an output mix. But when I try to realise a listener with a 3D location interface (SL_IID_3DLOCATION constant) which is mandatory for playing 3D sound. But when I try to set the constant to SL_BOOLEAN_TRUE the result of the CreateListener method is 12 as passed to the LogCat. 12 is the value of the OpenSL es constant SL_RESULT_FEATURE_UNSUPPORTED. Below you can find a short part of the code, can anyone confirm if I do anything wrong or if the feature really is unsopported, meaning that the OpenSL es implementation does not support 3D audio?

#define SL_RESULT_FEATURE_UNSUPPORTED       ((SLuint32) 0x0000000C)

const SLInterfaceID listener_ids[] = {SL_IID_3DLOCATION};
const SLboolean listener_req[] = {SL_BOOLEAN_TRUE};

result = (*engine)->CreateListener(engine, &listenerObject, 1, listener_ids, listener_req);
__android_log_print(ANDROID_LOG_VERBOSE, DEBUG_TAG, "CREATE: [%i]", result);

assert(SL_RESULT_SUCCESS == result);

result = (*listenerObject)->Realize(listenerObject, SL_BOOLEAN_FALSE);
__android_log_print(ANDROID_LOG_VERBOSE, DEBUG_TAG, "REALIZE: [%i]", result);

assert(SL_RESULT_SUCCESS == result);


问:
JupyterLab - python open() function results in FileNotFoundError
I am trying to open an existing file in a subfolder of the current working directory. This is my command:

fyle = open('/SPAdes/default/{}'.format(file), 'r')

The filevariable contains the correct filename, the folder structure is correct (working on macOS), and the file exists.

This command, however, results if this error message:

FileNotFoundError: [Errno 2] No such file or directory: [filename]

Does it have anything to do with the way JupyterLab works? How am I supposed to specify the folder srtucture on Jupyter? I am able to create a new file in the current folder, but I am not able to create one in a subfolder of the current one (results in the same error message).

The folder structure is recognized on the same Jupyter notebook by bash commands, but I am somehow not able to access subfolders using python code.
Any idea as to what is wrong with the way I specified the folder structure?

Thanks a lot in advance.

答:
There shouldn’t be a forward slash in front of SPAdes.

Paths starting with a slash exist high up in file hierarchy. You said this is a sub-directory of your current working directory.


问:
Firing a click event on a child component
I have been trying to write a test that will ensure that when a marker is clicked (from leaflet) further details will be displayed to the user. The Marker component is a child of the Map component. To start I am just wanting to see if the onClick function is called once when the marker is clicked.

The Map component returns the following structure

```<code>return(
  <LeafletMap>
    <Marker data-testid='marker' onClick={someFunc}/>
    <TileLayer/>
    <Popup/>
  </LeafletMap>
)
</code>```

In my test I attempt to render the Map component and find the marker via a data-testid:

```<code>const handleParcelClick = jest.fn()
it('get parcel details upon clicking the marker', () => {
    const {getByTestId}= render(<Map lat={someNumber} lng={someNumber} zoom={14} parcels={fakeParcels} activeParcel={fakeDetails} onParcelClick={handleParcelClick} />)
    const marker = getByTestId('marker')
    fireEvent.click(marker)
    expect(handleParcelClick).toBeCalledTimes(1)
});
</code>```

When attempting to run I get the following error:

```<code>      at getElementError (node_modules/@testing-library/dom/dist/query-helpers.js:22:10)
      at args (node_modules/@testing-library/dom/dist/query-helpers.js:76:13)
      at getByTestId (node_modules/@testing-library/dom/dist/query-helpers.js:59:17)
      at Object.<anonymous>.it (src/ParcelDetails.test.tsx:58:20)
</code>```

I have attempted using enzyme as well with no success. The data-testid in the actual code is unique for each marker, called marker above for simplicity. Am I going about this wrong? Should I be testing the Marker separately from the Map component?

Update: I have attempted to use enzyme as a solution; however, I receive the following error when trying to simulate a click

```<code>TypeError: Cannot read property '__reactInternalInstance$k2volvgmsgj' of null
</code>```

There does not seem to be a consistent solution for this error and I am confused as to why I am getting it. I have ensured that marker is the component I am wanting to click and that it is not null.

Here is my updated code:

```<code>it('Loads parcel details on click', ()=> {
    const mockClick = jest.fn();
    const component = mount(<Map lat={n1} lng={n2} zoom={14} parcels={fakeParcels} activeParcel={fakeDetails} onParcelClick={mockClick} />);
    const marker = component.find(Marker).first();
    marker.simulate('click');
    expect(mockClick).toBeCalledTimes(1);
});
</code>```

答:
The easiest way to fire a click event on an element in jest is to first find the element using dom selector and then simulate click on it, like this:

```<code>let element = document.getElementById('your-element-id');
element.simulate('click');
</code>```

Hope this helps!!

Body:
I have been trying to write a test that will ensure that when a marker is clicked (from leaflet) further details will be displayed to the user. The Marker component is a child of the Map component. To start I am just wanting to see if the onClick function is called once when the marker is clicked.

The Map component returns the following structure

return(
  <LeafletMap>
    <Marker data-testid='marker' onClick={someFunc}/>
    <TileLayer/>
    <Popup/>
  </LeafletMap>
)

In my test I attempt to render the Map component and find the marker via a data-testid:

const handleParcelClick = jest.fn()
it('get parcel details upon clicking the marker', () => {
    const {getByTestId}= render(<Map lat={someNumber} lng={someNumber} zoom={14} parcels={fakeParcels} activeParcel={fakeDetails} onParcelClick={handleParcelClick} />)
    const marker = getByTestId('marker')
    fireEvent.click(marker)
    expect(handleParcelClick).toBeCalledTimes(1)
});

When attempting to run I get the following error:

      at getElementError (node_modules/@testing-library/dom/dist/query-helpers.js:22:10)
      at args (node_modules/@testing-library/dom/dist/query-helpers.js:76:13)
      at getByTestId (node_modules/@testing-library/dom/dist/query-helpers.js:59:17)
      at Object.<anonymous>.it (src/ParcelDetails.test.tsx:58:20)

I have attempted using enzyme as well with no success. The data-testid in the actual code is unique for each marker, called marker above for simplicity. Am I going about this wrong? Should I be testing the Marker separately from the Map component?

Update: I have attempted to use enzyme as a solution; however, I receive the following error when trying to simulate a click

TypeError: Cannot read property '__reactInternalInstance$k2volvgmsgj' of null

There does not seem to be a consistent solution for this error and I am confused as to why I am getting it. I have ensured that marker is the component I am wanting to click and that it is not null.

Here is my updated code:

it('Loads parcel details on click', ()=> {
    const mockClick = jest.fn();
    const component = mount(<Map lat={n1} lng={n2} zoom={14} parcels={fakeParcels} activeParcel={fakeDetails} onParcelClick={mockClick} />);
    const marker = component.find(Marker).first();
    marker.simulate('click');
    expect(mockClick).toBeCalledTimes(1);
});

Body:
The easiest way to fire a click event on an element in jest is to first find the element using dom selector and then simulate click on it, like this:

let element = document.getElementById('your-element-id');
element.simulate('click');

Hope this helps!!


问:
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?

答:
struct.pack returns bytes in python 3, not a string as it did in python 2. Have a look at this answer to see one way to emulate the python 2 behavior.

Edit: actually you may need to do something slightly different, since it looks like socket.send wants bytes as input. So you'd need to convert the combined payload to bytes.

You could try changing the following code that seems to be populating the payload to return bytes in both cases. Notice the "b" added in the return values to specify bytes instead of str. You are hitting the TYPE_LISTEN case but should test the other case as well, as it looks like it had the same bug trying to concat str and bytes:

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

You'll likely need to edit _pack in PlistProtocol as well.

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:
struct.pack returns bytes in python 3, not a string as it did in python 2. Have a look at this answer to see one way to emulate the python 2 behavior.

Edit: actually you may need to do something slightly different, since it looks like socket.send wants bytes as input. So you'd need to convert the combined payload to bytes.

You could try changing the following code that seems to be populating the payload to return bytes in both cases. Notice the "b" added in the return values to specify bytes instead of str. You are hitting the TYPE_LISTEN case but should test the other case as well, as it looks like it had the same bug trying to concat str and bytes:

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

You'll likely need to edit _pack in PlistProtocol as well.


问:
Hacked database by using mongodb. Did anyone get this situation?
Today, my website suddenly down and then I checked my database which I used mongodb. It seemed that someone hacked my database and then they created a collection like this:

{
    "_id": {
        "$oid": "5e3dd717e3d0c9664c95ad51"
    },
    "btc": "1J7YbJbvmPBXZsR4U8dGbhDC7WH5EwoRQt",
    "info": "All your data is a backed up. You must pay 0.1 BTC to 1J7YbJbvmPBXZsR4U8dGbhDC7WH5EwoRQt 48 hours for recover it.
    After 48 hours expiration we will leaked and exposed all your data. Also do not forget about GDPR.
    Need any proofs? coojeipo@secmail.pro You are welcome!"
}```

I don't know what should I do now. Do I need to uninstall mongodb on my server and then setup it again? Please give my advice.

Thank you

答: use MongoDB atlas for production and make sure you set your server application IP address as the only IP address that can access your application.</p>

Body:
Today, my website suddenly down and then I checked my database which I used mongodb. It seemed that someone hacked my database and then they created a collection like this:

{
    "_id": {
        "$oid": "5e3dd717e3d0c9664c95ad51"
    },
    "btc": "1J7YbJbvmPBXZsR4U8dGbhDC7WH5EwoRQt",
    "info": "All your data is a backed up. You must pay 0.1 BTC to 1J7YbJbvmPBXZsR4U8dGbhDC7WH5EwoRQt 48 hours for recover it.
    After 48 hours expiration we will leaked and exposed all your data. Also do not forget about GDPR.
    Need any proofs? coojeipo@secmail.pro You are welcome!"
}

I don't know what should I do now. Do I need to uninstall mongodb on my server and then setup it again? Please give my advice.

Thank you


问:
EnityManagerFactory Singleton. Please just check out?
I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!

```<code>import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerFactorySingleton {
    private static EntityManagerFactorySingleton singleton;
    private EntityManagerFactory emf;

public EntityManagerFactorySingleton(){
    emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}

public synchronized static EntityManagerFactorySingleton getInstance() {
   if(singleton == null) {
    singleton = new EntityManagerFactorySingleton();
   }
   return singleton;
}

public EntityManagerFactory getEntityManagerFactory(){
    return emf;
}
</code>```

}

答:
Your code is not "solid":

constructor must be private for a singleton

you shouldn't have the getInstance() method synchronised, although you need to perform the initialisation thread-safe. That's because after initialization, all the threads that need the instance will have to wait for each other (and that's a useless bottleneck).
Only if your instance is null, call a synchronized (private) method that performs the initialisation; inside that method, check again if the instance is null. Another approach is to have a private inner class SingletonHolder that holds the instance, so you'll rely on the class-loader for performing the thread-safe initialisation.

However, if you can't (don't want to) avoid using a singleton, a very good choice would be an enum with only one constant defined: INSTANCE;

```<code>public enum EntityManagerFactorySingleton {
    INSTANCE;

    // all your code -- fields, constructor, instance / static methods get in here
    // you can still have the `getInstance()` static method returning INSTANCE, if you want.
}
</code>```

The only drawback is that you cannot perform lazy initialisation for the INSTANCE, but you're now thread-safe and ready for serialization or cloning issues without any effort.

ContentLicense: CC BY-SA 3.0

Body:
I am just cruious if this looks solid. It gives no errors but I just want to double check as I am having a pooling issue with c3p0. Just checking to see if anything here is the cause. Thank you in advance!

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerFactorySingleton {
    private static EntityManagerFactorySingleton singleton;
    private EntityManagerFactory emf;

public EntityManagerFactorySingleton(){
    emf = Persistence.createEntityManagerFactory(ConfigList.getProperty(Config.PERSISTENCE_UNIT), System.getProperties());
}

public synchronized static EntityManagerFactorySingleton getInstance() {
   if(singleton == null) {
    singleton = new EntityManagerFactorySingleton();
   }
   return singleton;
}

public EntityManagerFactory getEntityManagerFactory(){
    return emf;
}

}

Body:
Your code is not "solid":

constructor must be private for a singleton

you shouldn't have the getInstance() method synchronised, although you need to perform the initialisation thread-safe. That's because after initialization, all the threads that need the instance will have to wait for each other (and that's a useless bottleneck).
Only if your instance is null, call a synchronized (private) method that performs the initialisation; inside that method, check again if the instance is null. Another approach is to have a private inner class SingletonHolder that holds the instance, so you'll rely on the class-loader for performing the thread-safe initialisation.

However, if you can't (don't want to) avoid using a singleton, a very good choice would be an enum with only one constant defined: INSTANCE;

public enum EntityManagerFactorySingleton {
    INSTANCE;

    // all your code -- fields, constructor, instance / static methods get in here
    // you can still have the `getInstance()` static method returning INSTANCE, if you want.
}

The only drawback is that you cannot perform lazy initialisation for the INSTANCE, but you're now thread-safe and ready for serialization or cloning issues without any effort.


问:
Mark inputs in pytest parametrize
I have a test that I would like to run as part of two different test suites with different parameter inputs based on the test suite. The test suites are identified with pytest markers.

Is there a way to mark parametrize entries so that they are only run during that specific test suite?

Here is what I'd like to do:

```<code>@pytest.mark.suiteA # include the test in Suite A
@pytest.mark.suiteB # include the test in Suite B
@pytest.mark.parametrize("inputParameter", [
                              (10),                    # use this input for Suites A and B
                              pytest.mark.suiteB(12)]) # only use this input for Suite B
def test_printInputParameter(inputParameter):
    print inputParameter
</code>```

Running code like this doesn't produce the results I want-- both inputs are used for both suites.

I have seen that pytest will allow use of xfail or skip within parametrize (see "Skip/xfail with parametrize" on http://pytest.org/latest/skipping.html) If there is a way to write a conditional statement that will evaluate as true only when running Suite B, that would also accomplish what I need.

Thanks in advance for the help.

答:
You are on the right track. Part of the problem is that you've marked the test function with both suiteA and suiteB, so the function is considered part of both.

The parameter marker style you are using probably worked in '14 (and still works at late as pytest 3), but it doesn't work in the latest pytest version (5.x).

These examples use the latest style, which also works at least as far back as pytest 3.x.

From the pytest docs:

When using parametrize, applying a mark will make it apply to each individual test. However it is also possible to apply a marker to an individual test instance:

```<code>import pytest

@pytest.mark.foo
@pytest.mark.parametrize(
    ("n", "expected"), [(1, 2), pytest.param(1, 3, marks=pytest.mark.bar), (2, 3)]
)
def test_increment(n, expected):
    assert n + 1 == expected
</code>```

In the above example, using mark foo will run that test will all parameters (including bar). Using mark bar will run that test with only the 1 marked parameter.

So, for your example, you can do (forgive me, I updated all names, except the markers, to PEP8 standard):

```<code>@pytest.mark.parametrize("input_parameter", [
        # use this input for Suite A and Suite B
        pytest.param(10, marks=[pytest.mark.suiteA, pytest.mark.suiteB]),
        # use this input only for Suite B
        pytest.param(12, marks=pytest.mark.suiteB),
        # this input will run when no markers are specified
        (13),
])
def test_print_input_parameter(input_parameter):
    print(input_parameter)
</code>```

You must get rid of the two mark decorators above the function. You will only need this parameter decorator.

Based on the comments, input 10 is marked to ensure it will only run with suiteA or suiteB. It will execute if either of these, or both, are called for.

Input 12 is tied to a single mark, suiteB. It will only execute if suiteB is called for.

I also added input value 13 as an example for the default unmarked test runs. As normal, this will not execute for suiteA or suiteB (or suiteC or any other marker filter), but will run if no markers are specified (as will the rest).

Alternatively, you could do:

```<code>@pytest.mark.suiteB # this function is a part of suiteB
@pytest.mark.parametrize("input_parameter", [
        # use this input for Suite A and Suite B
        pytest.param(10, marks=pytest.mark.suiteA),
        # use this input only for Suite B
        (12),
        # this input is also part of Suite B thanks to the function decorator, as well as suiteC and suiteD
        pytest.param(13, marks=[pytest.mark.suiteC, pytest.mark.suiteD]),
])
def test_print_input_parameter(input_parameter):
    print(input_parameter)
</code>```

With your original two parameters, you really had a full suiteB test with one parameter only for suiteA.

In this case, the function decorator runs the whole test under suiteB. If suiteA is specified, only 10 will be executed.

Because the function decorator is used, my made up parameter 13, like all parameters for this function, is also part of suiteB. I can add it to as many other markers as I want, but the function decorator ensures this test will run with all parameters under suiteB.

This alternative would work given your example, but if you have any parameters that do not overlap (e.g. 13 is not run under suiteB), you'll have to specify each of them individually like the middle example.

Title: Mark inputs in pytest parametrize

Body:
I have a test that I would like to run as part of two different test suites with different parameter inputs based on the test suite. The test suites are identified with pytest markers.

Is there a way to mark parametrize entries so that they are only run during that specific test suite?

Here is what I'd like to do:

@pytest.mark.suiteA # include the test in Suite A
@pytest.mark.suiteB # include the test in Suite B
@pytest.mark.parametrize("inputParameter", [
                              (10),                    # use this input for Suites A and B
                              pytest.mark.suiteB(12)]) # only use this input for Suite B
def test_printInputParameter(inputParameter):
    print inputParameter

Running code like this doesn't produce the results I want-- both inputs are used for both suites.

I have seen that pytest will allow use of xfail or skip within parametrize (see "Skip/xfail with parametrize" on http://pytest.org/latest/skipping.html) If there is a way to write a conditional statement that will evaluate as true only when running Suite B, that would also accomplish what I need.

Thanks in advance for the help.

Body:
You are on the right track. Part of the problem is that you've marked the test function with both suiteA and suiteB, so the function is considered part of both.

The parameter marker style you are using probably worked in '14 (and still works at late as pytest 3), but it doesn't work in the latest pytest version (5.x).

These examples use the latest style, which also works at least as far back as pytest 3.x.

From the pytest docs:

When using parametrize, applying a mark will make it apply to each individual test. However it is also possible to apply a marker to an individual test instance:

import pytest

@pytest.mark.foo
@pytest.mark.parametrize(
    ("n", "expected"), [(1, 2), pytest.param(1, 3, marks=pytest.mark.bar), (2, 3)]
)
def test_increment(n, expected):
    assert n + 1 == expected

In the above example, using mark foo will run that test will all parameters (including bar). Using mark bar will run that test with only the 1 marked parameter.

So, for your example, you can do (forgive me, I updated all names, except the markers, to PEP8 standard):

@pytest.mark.parametrize("input_parameter", [
        # use this input for Suite A and Suite B
        pytest.param(10, marks=[pytest.mark.suiteA, pytest.mark.suiteB]),
        # use this input only for Suite B
        pytest.param(12, marks=pytest.mark.suiteB),
        # this input will run when no markers are specified
        (13),
])
def test_print_input_parameter(input_parameter):
    print(input_parameter)

You must get rid of the two mark decorators above the function. You will only need this parameter decorator.

Based on the comments, input 10 is marked to ensure it will only run with suiteA or suiteB. It will execute if either of these, or both, are called for.

Input 12 is tied to a single mark, suiteB. It will only execute if suiteB is called for.

I also added input value 13 as an example for the default unmarked test runs. As normal, this will not execute for suiteA or suiteB (or suiteC or any other marker filter), but will run if no markers are specified (as will the rest).

Alternatively, you could do:

@pytest.mark.suiteB # this function is a part of suiteB
@pytest.mark.parametrize("input_parameter", [
        # use this input for Suite A and Suite B
        pytest.param(10, marks=pytest.mark.suiteA),
        # use this input only for Suite B
        (12),
        # this input is also part of Suite B thanks to the function decorator, as well as suiteC and suiteD
        pytest.param(13, marks=[pytest.mark.suiteC, pytest.mark.suiteD]),
])
def test_print_input_parameter(input_parameter):
    print(input_parameter)

With your original two parameters, you really had a full suiteB test with one parameter only for suiteA.

In this case, the function decorator runs the whole test under suiteB. If suiteA is specified, only 10 will be executed.

Because the function decorator is used, my made up parameter 13, like all parameters for this function, is also part of suiteB. I can add it to as many other markers as I want, but the function decorator ensures this test will run with all parameters under suiteB.

This alternative would work given your example, but if you have any parameters that do not overlap (e.g. 13 is not run under suiteB), you'll have to specify each of them individually like the middle example.


问:
pyTelegramBotAPI. How to save state in next_step_handler solution?
User in my solution goes step by step by typing message in telegram. The problem is that after server reboot his state not saving and he needs to begin again.

For example, if user on 'process_mid' step, after rebooting, he can't go to 'process_end'. User can only begin new stage by typing 'start' command.

```<code>bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def process_start(message):
    text = 'start'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_mid)

def process_mid(message):
    text = 'mid'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_end)

def process_end(message):
    text = 'end'
    bot.send_message(message.chat.id, text)

bot.polling(none_stop=True)
</code>```

答:
This Example will show you how to use register_next_step handler
https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py

Body:
User in my solution goes step by step by typing message in telegram. The problem is that after server reboot his state not saving and he needs to begin again.

For example, if user on 'process_mid' step, after rebooting, he can't go to 'process_end'. User can only begin new stage by typing 'start' command.

bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def process_start(message):
    text = 'start'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_mid)

def process_mid(message):
    text = 'mid'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_end)

def process_end(message):
    text = 'end'
    bot.send_message(message.chat.id, text)

bot.polling(none_stop=True)


问:
Producing files in dagster without caring about the filename
In the dagster tutorial, in the Materializiations section, we choose a filename (sorted_cereals_csv_path) for our intermediate output, and then yield it as a materialization:

@solid
def sort_by_calories(context, cereals):

    # Sort the data (removed for brevity)

    sorted_cereals_csv_path = os.path.abspath(
        'calories_sorted_{run_id}.csv'.format(run_id=context.run_id)
    )
    with open(sorted_cereals_csv_path, 'w') as fd:
        writer = csv.DictWriter(fd, fieldnames)
        writer.writeheader()
        writer.writerows(sorted_cereals)
    yield Materialization(
        label='sorted_cereals_csv',
        description='Cereals data frame sorted by caloric content',
        metadata_entries=[
            EventMetadataEntry.path(
                sorted_cereals_csv_path, 'sorted_cereals_csv_path'
            )
        ],
    )
    yield Output(None)
```

However, this is relying on the fact that we can use the local filesystem (which may not be true), it will likely get overwritten by later runs (which is not what I want) and it's also forcing us to come up with a filename which will never be used.

What I'd like to do in most of my solids is just say "here is a file object, please store it for me", without concerning myself with where it's going to be stored. Can I materialize a file without considering all these things? Should I use python's tempfile facility for this?

答:
Actually it seems this is answered in the output_materialization example.

You basically define a type:

@usable_as_dagster_type(
    name='LessSimpleDataFrame',
    description='A more sophisticated data frame that type checks its structure.',
    input_hydration_config=less_simple_data_frame_input_hydration_config,
    output_materialization_config=less_simple_data_frame_output_materialization_config,
)
class LessSimpleDataFrame(list):
    pass
```

<p>This type has an output_materialization strategy that reads the config:</p>

```def less_simple_data_frame_output_materialization_config(
    context, config, value
):
    csv_path = os.path.abspath(config['csv']['path'])

    # Save data to this path
```

<p>And you specify this path in the config:</p>

```    execute_pipeline(
        output_materialization_pipeline,
        {
            'solids': {
                'sort_by_calories': {
                    'outputs': [
                        {'result': {'csv': {'path': 'cereal_out.csv'}}}
                    ],
                }
            }
        },
    )
```

You still have to come up with a filename for each intermediate output, but you can do it in the config, which can differ per-run, instead of defining it in the pipeline itself.

Body:
In the dagster tutorial, in the Materializiations section, we choose a filename (sorted_cereals_csv_path) for our intermediate output, and then yield it as a materialization:

@solid
def sort_by_calories(context, cereals):

    # Sort the data (removed for brevity)

    sorted_cereals_csv_path = os.path.abspath(
        'calories_sorted_{run_id}.csv'.format(run_id=context.run_id)
    )
    with open(sorted_cereals_csv_path, 'w') as fd:
        writer = csv.DictWriter(fd, fieldnames)
        writer.writeheader()
        writer.writerows(sorted_cereals)
    yield Materialization(
        label='sorted_cereals_csv',
        description='Cereals data frame sorted by caloric content',
        metadata_entries=[
            EventMetadataEntry.path(
                sorted_cereals_csv_path, 'sorted_cereals_csv_path'
            )
        ],
    )
    yield Output(None)

However, this is relying on the fact that we can use the local filesystem (which may not be true), it will likely get overwritten by later runs (which is not what I want) and it's also forcing us to come up with a filename which will never be used.

What I'd like to do in most of my solids is just say "here is a file object, please store it for me", without concerning myself with where it's going to be stored. Can I materialize a file without considering all these things? Should I use python's tempfile facility for this?

Body:
Actually it seems this is answered in the output_materialization example.

You basically define a type:

@usable_as_dagster_type(
    name='LessSimpleDataFrame',
    description='A more sophisticated data frame that type checks its structure.',
    input_hydration_config=less_simple_data_frame_input_hydration_config,
    output_materialization_config=less_simple_data_frame_output_materialization_config,
)
class LessSimpleDataFrame(list):
    pass

This type has an output_materialization strategy that reads the config:

def less_simple_data_frame_output_materialization_config(
    context, config, value
):
    csv_path = os.path.abspath(config['csv']['path'])

    # Save data to this path

And you specify this path in the config:

    execute_pipeline(
        output_materialization_pipeline,
        {
            'solids': {
                'sort_by_calories': {
                    'outputs': [
                        {'result': {'csv': {'path': 'cereal_out.csv'}}}
                    ],
                }
            }
        },
    )

You still have to come up with a filename for each intermediate output, but you can do it in the config, which can differ per-run, instead of defining it in the pipeline itself.


问:
Vuejs route loading based on user type
I am returning user type in all my components but i need to add validation of it in my routes, not sure how to.

Code

This is my route.js file where the routes i need users to be authenticated are defined in meta

```<code>import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);

const router = new VueRouter({
    mode: "history",
    routes: [
        // ADMIN ROUTES
        {
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard,
            meta: {
                requiresAuth: true,
                layout: 'admin'
            }
        },
    ]
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!store.getters.isLoggedIn) {
        next({
          name: 'login'
        })
      } else {
        next()
      }
    } else {
      next()
    }
  })

router.afterEach((to, from) => {
    Vue.nextTick(() => {
        document.title = to.pageTitle || 'CC';
    });
});

export default router;
</code>```

As you can see I have requiresAuth: true, which only allows authenticated user to access this route, I also need to add another value which says if user type == admin that way not all logged in users can access to such route but only admins.

This is my logged user info which is accessible in all components and is included type value

Question

How can I add user type to routes meta?

Note

my type value can be one of this 3 conditions

admin (admins role)

customer (any other user role)

undefined (user with no role assigned)

Update

Forgot to mention that in all my components I also have this function

```<code>beforeRouteEnter (to, from, next) {
  const token = localStorage.getItem('access_token')
  return token ? next() : next('/login')
},
</code>```

This simply check if my user is logged in based on saved token in localStorage

Update 2

I've also tried to get my user type in component function like code below, but is returned this.$store is undefined

```<code>beforeRouteEnter (to, from, next) {
    if (this.$store.getters.loggedUser.type != 'admin') {
        next({
            name: 'home'
        })
    } else {
        next()
    }
}
</code>```

答:
The component instance this is not avaliable inside beforeRouteEnter See here.

One way to do what you want is to add another meta attribute to your admin routes and check the user type for each route that has admin: true.

Your router code would look something like this:

```<code>const router = new VueRouter({
    mode: "history",
    routes: [
        // ADMIN ROUTES
        {
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard,
            meta: {
                requiresAuth: true,
                layout: 'admin',
                admin: true
            }
        },
    ]
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!store.getters.isLoggedIn) {
            next({
                name: 'login'
            })
        }
    }
    if (to.matched.some(record => record.meta.admin)) {
        if (store.getters.loggedUser.type !== 'admin') {
            // Do something if the user is not an admin
            // maybe redirect to a forbidden page
        }
    }
    next()
})
</code>```

Title: Vuejs route loading based on user type

Body:
I am returning user type in all my components but i need to add validation of it in my routes, not sure how to.

Code

This is my route.js file where the routes i need users to be authenticated are defined in meta

import Vue from "vue";
import VueRouter from 'vue-router';
import store from './store';
Vue.use(VueRouter);

const router = new VueRouter({
    mode: "history",
    routes: [
        // ADMIN ROUTES
        {
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard,
            meta: {
                requiresAuth: true,
                layout: 'admin'
            }
        },
    ]
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!store.getters.isLoggedIn) {
        next({
          name: 'login'
        })
      } else {
        next()
      }
    } else {
      next()
    }
  })

router.afterEach((to, from) => {
    Vue.nextTick(() => {
        document.title = to.pageTitle || 'CC';
    });
});

export default router;

As you can see I have requiresAuth: true, which only allows authenticated user to access this route, I also need to add another value which says if user type == admin that way not all logged in users can access to such route but only admins.

This is my logged user info which is accessible in all components and is included type value

Question

How can I add user type to routes meta?

Note

my type value can be one of this 3 conditions

admin (admins role)

customer (any other user role)

undefined (user with no role assigned)

Update

Forgot to mention that in all my components I also have this function

beforeRouteEnter (to, from, next) {
  const token = localStorage.getItem('access_token')
  return token ? next() : next('/login')
},

This simply check if my user is logged in based on saved token in localStorage

Update 2

I've also tried to get my user type in component function like code below, but is returned this.$store is undefined

beforeRouteEnter (to, from, next) {
    if (this.$store.getters.loggedUser.type != 'admin') {
        next({
            name: 'home'
        })
    } else {
        next()
    }
}

Body:
The component instance this is not avaliable inside beforeRouteEnter See here.

One way to do what you want is to add another meta attribute to your admin routes and check the user type for each route that has admin: true.

Your router code would look something like this:

const router = new VueRouter({
    mode: "history",
    routes: [
        // ADMIN ROUTES
        {
            path: '/dashboard',
            name: 'dashboard',
            component: Dashboard,
            meta: {
                requiresAuth: true,
                layout: 'admin',
                admin: true
            }
        },
    ]
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!store.getters.isLoggedIn) {
            next({
                name: 'login'
            })
        }
    }
    if (to.matched.some(record => record.meta.admin)) {
        if (store.getters.loggedUser.type !== 'admin') {
            // Do something if the user is not an admin
            // maybe redirect to a forbidden page
        }
    }
    next()
})


问:
IE Stops Script Execution Using Reference to console.log/error/warn/info
If you get a reference to one of the console.log (console.error console.warn console.info) functions in IE 11 and try to call it, it blows up and stops script execution when not using F12 dev tools.

```<code>const logFunc = console.log;
logFunc('do some logging'); <-- stops executing further scripts here
</code>```

If you have dev tools showing, it works fine. So the only way to debug is the old-fashioned alert approach.

答:
The reason why it is not working is,

Since version 10, Internet Explorer always has a console object. If the developer tools are closed, calls to the console object are simply ignored.

You can copy the method to a variable, but you cannot use the variable to call the method.

Reference:

Console.log Surprises with Internet Explorer 11 and Edge

Body:
If you get a reference to one of the console.log (console.error console.warn console.info) functions in IE 11 and try to call it, it blows up and stops script execution when not using F12 dev tools.

const logFunc = console.log;
logFunc('do some logging'); <-- stops executing further scripts here

If you have dev tools showing, it works fine. So the only way to debug is the old-fashioned alert approach.


问:
Truth tables in code? How to structure state machine?
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

```<code>u8 newState[] = decisionTable[input1][input2][input3][input4];
</code>```

And then I could access the output values with:

```<code>setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );
</code>```

But in order to get that, it looks like I would have to do a fairly confusing table like so:

```<code>static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};
</code>```

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

```<code>#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))
</code>```

And that will let my truth table array look like this:

```<code>static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};
</code>```

And I can then access my truth table like so:

```<code>decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]
</code>```

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

答:
No need for a multidimensional table.  With a 4 bit => 4 bit mapping, you can have a single u8[16] array mapping inputs to outputs.  State lookups will be much cheaper, and you can extract individual bits with some shift-and-mask ops.

If the algorithm to populate rows is easy to codify, you could #define a macro to populate each row by index number.

OwnerDisplayName: HanClinto

Body:
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

u8 newState[] = decisionTable[input1][input2][input3][input4];

And then I could access the output values with:

setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );

But in order to get that, it looks like I would have to do a fairly confusing table like so:

static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))

And that will let my truth table array look like this:

static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};

And I can then access my truth table like so:

decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

LastEditorDisplayName: Im safe against SQL injection

OwnerDisplayName: HUAGHAGUAH


问:
How to overlay a bar chart with a line chart in R?
I am looking to lay over multiple years off data, based off of weeks. I am looking for the most recent year (2020) to be a bar chat, and the prior years (2019 & 2018) to be line plots.

My current code produces the visual below

```<code>data %>%
  ggplot(aes(week, result, fill = year)) +
  geom_col()
</code>```

Chart

If I wanted to make all the years a bar chart, I know I could use "dodge" in geom_col. However, I am trying to split out the data into different geoms

When I use the subset function (code below), something strange happens with my chart and I can't figure out what is going on

```<code>data %>%
  ggplot(aes(week, result, fill = year)) +
  geom_col(data = subset(data, year == 2020)) +
  geom_line(data = subset(data, year != 2020))
</code>```

Chart 2

Below is a sample of the data that I am using. Any ideas on what I'm doing wrong?

```<code>structure(list(year = c("2018", "2018", "2019", "2019", "2020",
"2020"), week = c(1L, 2L, 1L, 2L, 1L, 2L), result = c(6.88475831020016,
7.62267452779933, 3.67553313593328, 6.18354398162893, 2.38101968527051,
5.9596355812872)), .Names = c("year", "week", "result"), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
I am not sure where is your error but with my dummy example mimicking your example, I just add color in aes in order to make lines being grouped by years and the rest of the code is similar as yours:

ggplot(df, aes(x = week, y = Value,
               color = as.factor(year),
               fill = as.factor(year)))+
  geom_col(data = subset(df, year == 2020)) +
  geom_line(data = subset(df, year != 2020))
```

<p><img src="https://i.stack.imgur.com/34RWh.png" alt="enter image description here"></p>

<p><strong>Data</strong></p>

<pre class="lang-r prettyprint-override"><code>df <- data.frame(year = rep(2018:2020, each = 7),
                 week = rep(1:7,3),
                 Value = rnorm(21))
</code>```

EDIT with OP data

Based on your data, you just need to subset based on character values and not numerical as pointed out by @camille:

ggplot(df, aes(x = week, y = result,
                 color =year,
                 fill = year))+
    geom_col(data = subset(df, year == "2020")) +
    geom_line(data = subset(df, year != "2020"))
```

Body:
I am looking to lay over multiple years off data, based off of weeks. I am looking for the most recent year (2020) to be a bar chat, and the prior years (2019 & 2018) to be line plots.

My current code produces the visual below

data %>%
  ggplot(aes(week, result, fill = year)) +
  geom_col()

Chart

If I wanted to make all the years a bar chart, I know I could use "dodge" in geom_col. However, I am trying to split out the data into different geoms

When I use the subset function (code below), something strange happens with my chart and I can't figure out what is going on

data %>%
  ggplot(aes(week, result, fill = year)) +
  geom_col(data = subset(data, year == 2020)) +
  geom_line(data = subset(data, year != 2020))

Chart 2

Below is a sample of the data that I am using. Any ideas on what I'm doing wrong?

structure(list(year = c("2018", "2018", "2019", "2019", "2020",
"2020"), week = c(1L, 2L, 1L, 2L, 1L, 2L), result = c(6.88475831020016,
7.62267452779933, 3.67553313593328, 6.18354398162893, 2.38101968527051,
5.9596355812872)), .Names = c("year", "week", "result"), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

Body:
I am not sure where is your error but with my dummy example mimicking your example, I just add color in aes in order to make lines being grouped by years and the rest of the code is similar as yours:

ggplot(df, aes(x = week, y = Value,
               color = as.factor(year),
               fill = as.factor(year)))+
  geom_col(data = subset(df, year == 2020)) +
  geom_line(data = subset(df, year != 2020))

Data

df <- data.frame(year = rep(2018:2020, each = 7),
                 week = rep(1:7,3),
                 Value = rnorm(21))

EDIT with OP data

Based on your data, you just need to subset based on character values and not numerical as pointed out by @camille:

ggplot(df, aes(x = week, y = result,
                 color =year,
                 fill = year))+
    geom_col(data = subset(df, year == "2020")) +
    geom_line(data = subset(df, year != "2020"))


问:
React form submission logic with lifted state and controlled dependence
I've dug myself into a deep rabbit hole with this component in an attempt to use React hooks.

The Parent component handles a dictionary state which is eventually distributed to multiple components.

My problem child component WordInput has a form with a single input. When submitting the form the component is fetching the word's definition from an API and passing on both the word and the definition to the parent which then sets the state in the form of dictionary. So far, so good IF it's the first word in dictionary. The part I'm having trouble with is to submit any subsequent words/definitions.

When the user submits a subsequent word, I want the component to check whether the word already exists in the dictionary that is passed to the child. If it doesn't exist, add it to the dictionary via the submit function.

I think the problem is that I'm trying to do too much with useEffect
I useEffect to:
  - set loading
  - check and process the dictionary for existing words
  - check that definition and word aren't empty and submit both to parent/dictionary
  - fetch a definition from an API

In the unprocessed code, I have multiple console.groups to help me keep track of what is happening. The more I add to the component, the more Subgroups and subgroups of subgroups accumulate. Clearly, the approach I'm taking isn't very dry and causes too many re-renders of the component/useEffect functions. For conciseness, I have taken out the console.log entries.

The imported fetchWordDefinition merely processes the fetched data and arranges it correctly into an array.

I don't know how to keep this dry and effective, and any help is appreciated with this rather simple task. My hunch is to keep all the logic to submit the word/definition in the submit handler, and only use useEffect to validate the data prior to that.

```<code>import React, { useState, useEffect } from "react";
import fetchWordDefinition from "./lib/utils";

const WordInput = ({ onSubmit, dictionary }) => {
    const [definition, setDefinition] = useState([]);
    const [cause, setCause] = useState({ function: "" });
    const [error, setError] = useState({});
    const [loading, setLoading] = useState(false);
    const [word, setWord] = useState("");
    const [wordExistsInDB, setWordExistsInDB] = useState(false);

    useEffect(() => {
        const dictionaryEmpty = dictionary.length === 0 ? true : false;

        if (dictionaryEmpty) {
            return;
        } else {
            for (let i = 0; i < dictionary.length; i += 1) {
                if (dictionary[i].word === word) {
                    setWordExistsInDB(true);
                    setError({ bool: true, msg: "Word already exists in DB" });
                    break;
                } else {
                    setWordExistsInDB(false);
                    setError({ bool: false, msg: "" });
                }
            }
        }
    }, [dictionary, word]);

    useEffect(() => {
        const definitionNotEmpty = definition.length !== 0 ? true : false;
        const wordNotEmpty = word !== "" ? true : false;

        if (wordNotEmpty && definitionNotEmpty && !wordExistsInDB) {
            onSubmit(word, definition);
            setWord("");
            setDefinition([]);
        }
    }, [definition, word, onSubmit, wordExistsInDB]);

    useEffect(() => {
        if (cause.function === "fetch") {
            async function fetchFunction() {
                const fetch = await fetchWordDefinition(word);
                return fetch;
            }

            fetchFunction().then(definitionArray => {
                setDefinition(definitionArray);
                setCause({ function: "" });
            });
        }
    }, [cause, word]);

    const handleSubmit = async e => {
        e.preventDefault();

        setLoading(true);
        setCause({ function: "fetch" });
    };

    return (
        <form onSubmit={handleSubmit}>
            {error.bool ? <span>{error.msg}</span> : null}
            <input
                name='word'
                placeholder='Enter Word'
                type='text'
                value={word}
                onChange={({ target: { value } }) => setWord(value)}
            />
            <input type='submit' />
        </form>
    );
};

export default WordInput;
</code>```

答:
There are indeed more useEffect's happening than necessary, as well as most of the state. All you need is the handleSubmit to do the fetching.

```<code>const WordInput = ({ onSubmit, dictionary }) => {
  const [word, setWord] = React.useState("");
  const handleChange = React.useCallback(e => {
    setWord(e.currentTarget.value)
  }, [])
  const handleSubmit = React.useCallback(() => {
    //check if word is in dictionary
    const wordIsAlreadyThere = dictionary.map(entry => entry.word).includes(word)
    //fetch the definition, wait for it, and call submit
    if(!wordIsAlreadyThere && word.length > 0){
      fetchWordDefinition(word)
        .then(definition => {
          onSubmit(word, definition)
          setWord('')
        }).catch(err => console.log(err))
    }
  }, [])
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={word}
        onChange={handleChange}/>
      <input type='submit' />
     </form>
  );
}
</code>```

Body:
I've dug myself into a deep rabbit hole with this component in an attempt to use React hooks.

The Parent component handles a dictionary state which is eventually distributed to multiple components.

My problem child component WordInput has a form with a single input. When submitting the form the component is fetching the word's definition from an API and passing on both the word and the definition to the parent which then sets the state in the form of dictionary. So far, so good IF it's the first word in dictionary. The part I'm having trouble with is to submit any subsequent words/definitions.

When the user submits a subsequent word, I want the component to check whether the word already exists in the dictionary that is passed to the child. If it doesn't exist, add it to the dictionary via the submit function.

I think the problem is that I'm trying to do too much with useEffect
I useEffect to:
  - set loading
  - check and process the dictionary for existing words
  - check that definition and word aren't empty and submit both to parent/dictionary
  - fetch a definition from an API

In the unprocessed code, I have multiple console.groups to help me keep track of what is happening. The more I add to the component, the more Subgroups and subgroups of subgroups accumulate. Clearly, the approach I'm taking isn't very dry and causes too many re-renders of the component/useEffect functions. For conciseness, I have taken out the console.log entries.

The imported fetchWordDefinition merely processes the fetched data and arranges it correctly into an array.

I don't know how to keep this dry and effective, and any help is appreciated with this rather simple task. My hunch is to keep all the logic to submit the word/definition in the submit handler, and only use useEffect to validate the data prior to that.

import React, { useState, useEffect } from "react";
import fetchWordDefinition from "./lib/utils";

const WordInput = ({ onSubmit, dictionary }) => {
    const [definition, setDefinition] = useState([]);
    const [cause, setCause] = useState({ function: "" });
    const [error, setError] = useState({});
    const [loading, setLoading] = useState(false);
    const [word, setWord] = useState("");
    const [wordExistsInDB, setWordExistsInDB] = useState(false);

    useEffect(() => {
        const dictionaryEmpty = dictionary.length === 0 ? true : false;

        if (dictionaryEmpty) {
            return;
        } else {
            for (let i = 0; i < dictionary.length; i += 1) {
                if (dictionary[i].word === word) {
                    setWordExistsInDB(true);
                    setError({ bool: true, msg: "Word already exists in DB" });
                    break;
                } else {
                    setWordExistsInDB(false);
                    setError({ bool: false, msg: "" });
                }
            }
        }
    }, [dictionary, word]);

    useEffect(() => {
        const definitionNotEmpty = definition.length !== 0 ? true : false;
        const wordNotEmpty = word !== "" ? true : false;

        if (wordNotEmpty && definitionNotEmpty && !wordExistsInDB) {
            onSubmit(word, definition);
            setWord("");
            setDefinition([]);
        }
    }, [definition, word, onSubmit, wordExistsInDB]);

    useEffect(() => {
        if (cause.function === "fetch") {
            async function fetchFunction() {
                const fetch = await fetchWordDefinition(word);
                return fetch;
            }

            fetchFunction().then(definitionArray => {
                setDefinition(definitionArray);
                setCause({ function: "" });
            });
        }
    }, [cause, word]);

    const handleSubmit = async e => {
        e.preventDefault();

        setLoading(true);
        setCause({ function: "fetch" });
    };

    return (
        <form onSubmit={handleSubmit}>
            {error.bool ? {error.msg} : null}
            <input
                name='word'
                placeholder='Enter Word'
                type='text'
                value={word}
                onChange={({ target: { value } }) => setWord(value)}
            />
            <input type='submit' />
        </form>
    );
};

export default WordInput;

Body:
There are indeed more useEffect's happening than necessary, as well as most of the state. All you need is the handleSubmit to do the fetching.

const WordInput = ({ onSubmit, dictionary }) => {
  const [word, setWord] = React.useState("");
  const handleChange = React.useCallback(e => {
    setWord(e.currentTarget.value)
  }, [])
  const handleSubmit = React.useCallback(() => {
    //check if word is in dictionary
    const wordIsAlreadyThere = dictionary.map(entry => entry.word).includes(word)
    //fetch the definition, wait for it, and call submit
    if(!wordIsAlreadyThere && word.length > 0){
      fetchWordDefinition(word)
        .then(definition => {
          onSubmit(word, definition)
          setWord('')
        }).catch(err => console.log(err))
    }
  }, [])
  return (
    <form onSubmit={handleSubmit}>
      <input
        value={word}
        onChange={handleChange}/>
      <input type='submit' />
     </form>
  );
}


问:
Does Trello provide a way to identify who created a card?
The api docs made it seem like the answer was no, but I couldn't tell.  Is there a way to find all the Trello cards I created on a board or set of boards or across all boards?</p>

答:
I wrote a userscript which adds the creation date and the creator name and account link to the Trello card.

You could install it from my GitHub repository or from OpenUserJS.org


问:
using data from context before is available
I have an input field that´s rendering data from the context. and it can change the data as well.

```<code><input value={ user.name } onChange={(e) => setUser({...user, name: e.target.value})} />
</code>```

when the date doesn´t exist yet I´m getting this warning

Warning: A component is changing an uncontrolled input of type
  undefined to be controlled.

only way to fix it is setting name to empty by default

```<code>const [user, setUser] = useState({ name: ''});
</code>```

but my user is not empty anymore by default (I can´t check if (user) {...} )
how can I use

```<code>const [user, setUser] = useState({ });
</code>```

without getting the warning? (input should be empty by default. that´s fine)

答:
You can simply provide a default value for your input element if user.name is falsey.

```<code><input
  value={ user.name || "" }
  onChange={(e) => setUser({...user, name: e.target.value})}
/>
</code>```

Body:
I have an input field that´s rendering data from the context. and it can change the data as well.

<input value={ user.name } onChange={(e) => setUser({...user, name: e.target.value})} />

when the date doesn´t exist yet I´m getting this warning

Warning: A component is changing an uncontrolled input of type
  undefined to be controlled.

only way to fix it is setting name to empty by default

const [user, setUser] = useState({ name: ''});

but my user is not empty anymore by default (I can´t check if (user) {...} )
how can I use

const [user, setUser] = useState({ });

without getting the warning? (input should be empty by default. that´s fine)

Body:
You can simply provide a default value for your input element if user.name is falsey.

<input
  value={ user.name || "" }
  onChange={(e) => setUser({...user, name: e.target.value})}
/>


问:
How to populate dropdown menu in React with entries from an excel file?
So currently, this is what I have to populate my dropdown menu. I use React Hook Form to create my dropdown. Currently, the options are hard-coded, but I want to read data from an excel or cvs file and then populate my options from that data. I have googled but most show up as populate from json file. I want to populate from excel file.
Thank you!</p>

```<code><h5 for="secondaryControls">Secondary controls-other </h5>
           <div className="float-left">
      {fields.map((field, idx) => {
        return (

          <div key={`${field}-${idx}`}>

          <select name="primaryControls" ref={register}>

<option value="Component3">->Link:  Lift /Transfer Seat </option>
<option value="Component4">->ASENTO – XL-SEAT:  Lift /Transfer Board</option>
    value={field.value}
              onChange={e => ChangeItem(idx, e)}
          </select>

            <input
              type="text"
style={{width: "370px"}}
          value={field.value}

              onChange={e => ChangeItem(idx, e)}
            />
            <button type="button" onClick={() => RemoveDropDown(idx)}>
              X
            </button>
<button type="button" onClick={() => NewDropDown()}>
        +
      </button>
          <br /><br />
        </div>
        );
      })}
    </div>
</code>```

答:
You need to first convert your excel file to a JSON. There are multiple libraries out there which will help you do that, one of them is convert-excel-to-json.

Once your file is converted to JSON, then you can easily loop over the object to create dropdown options.

Body:
So currently, this is what I have to populate my dropdown menu. I use React Hook Form to create my dropdown. Currently, the options are hard-coded, but I want to read data from an excel or cvs file and then populate my options from that data. I have googled but most show up as populate from json file. I want to populate from excel file.
Thank you!

Secondary controls-other

      {fields.map((field, idx) => {
        return (

          <div key={`${field}-${idx}`}>

          <select name="primaryControls" ref={register}>

<option value="Component3">->Link:  Lift /Transfer Seat </option>
<option value="Component4">->ASENTO – XL-SEAT:  Lift /Transfer Board</option>
    value={field.value}
              onChange={e => ChangeItem(idx, e)}
          </select>

            <input
              type="text"
style={{width: "370px"}}
          value={field.value}

              onChange={e => ChangeItem(idx, e)}
            />
            <button type="button" onClick={() => RemoveDropDown(idx)}>
              X
            </button>
<button type="button" onClick={() => NewDropDown()}>
        +
      </button>

        );
      })}