问:
How to show Hexadecimal unique ID NFC Tag have in my android NFC application?
I already make a write tag application that working find, I store data text to labeled thing ( example : computer 1) in NFC tag. Both write and read working fine. But I need to read the Hexadecimal ID that every tag have when I read the information text I know the have unique Hexadecimal ID (Cause I see that one when I test it with google play application there). But I don't know how to do it. I'm really bad at coding, so please help me.

Here is the code :

```<code>public class MainActivity extends Activity {

    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[];
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low;

    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);
        tvNFCContent.addTextChangedListener(watch);

        handler = new Handler() ;

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }

        readFromIntent(getIntent());
    }

    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }

    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

     tvNFCContent.setText("NFC Content: " + text);
     TimeBuff += MillisecondTime;
     handler.removeCallbacks(runnable);

    }

    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();

            StartTime = SystemClock.uptimeMillis();
            handler.postDelayed(runnable, 0);

            NdefMessage[] messages = getNdefMessage(intent);
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] payload = messages[0].getRecords()[0].getPayload();
            userData = new String(payload);
        } else {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }

    }

    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;
            UpdateTime = TimeBuff + MillisecondTime;
            Seconds = (int) (UpdateTime / 1000);
            Minutes = Seconds / 60;
            Seconds = Seconds % 60;
            MilliSeconds = (int) (UpdateTime % 1000);
            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);

    }

    TextWatcher watch = new TextWatcher(){

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence s, int a, int b, int c) {
            // TODO Auto-generated method stub

        }
    };
}

</code>```

I'm sorry I upload the whole code, I just want to make it easy fpr anyone that would like to help me.

答:
Add this code in onNewIntent()

```<code>Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] uid = tag.getId(); //This is the Unique IDentifier of the card
</code>```

Use the following method to get hex value

```<code>public static String getHexValue(final byte[] buffer) {
    if (buffer == null || buffer.length == 0) {
        return ("0x" + "[none]");
    }

    final StringBuffer sb = new StringBuffer();
    sb.append("0x");
    for (int i = 0; i < buffer.length - 1; i++) {
        sb.append(String.format("%02X%s", buffer[i], ""));
    }
    sb.append(String.format("%02X", buffer[buffer.length - 1]));

    return sb.toString();
}
</code>```

Body:
I already make a write tag application that working find, I store data text to labeled thing ( example : computer 1) in NFC tag. Both write and read working fine. But I need to read the Hexadecimal ID that every tag have when I read the information text I know the have unique Hexadecimal ID (Cause I see that one when I test it with google play application there). But I don't know how to do it. I'm really bad at coding, so please help me.

Here is the code :

public class MainActivity extends Activity {

    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[];
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low;

    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);
        tvNFCContent.addTextChangedListener(watch);

        handler = new Handler() ;

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }

        readFromIntent(getIntent());
    }

    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }

    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

     tvNFCContent.setText("NFC Content: " + text);
     TimeBuff += MillisecondTime;
     handler.removeCallbacks(runnable);

    }

    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();

            StartTime = SystemClock.uptimeMillis();
            handler.postDelayed(runnable, 0);

            NdefMessage[] messages = getNdefMessage(intent);
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] payload = messages[0].getRecords()[0].getPayload();
            userData = new String(payload);
        } else {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }

    }

    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;
            UpdateTime = TimeBuff + MillisecondTime;
            Seconds = (int) (UpdateTime / 1000);
            Minutes = Seconds / 60;
            Seconds = Seconds % 60;
            MilliSeconds = (int) (UpdateTime % 1000);
            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);

    }

    TextWatcher watch = new TextWatcher(){

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence s, int a, int b, int c) {
            // TODO Auto-generated method stub

        }
    };
}

I'm sorry I upload the whole code, I just want to make it easy fpr anyone that would like to help me.

Body:
Add this code in onNewIntent()

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] uid = tag.getId(); //This is the Unique IDentifier of the card

Use the following method to get hex value

public static String getHexValue(final byte[] buffer) {
    if (buffer == null || buffer.length == 0) {
        return ("0x" + "[none]");
    }

    final StringBuffer sb = new StringBuffer();
    sb.append("0x");
    for (int i = 0; i < buffer.length - 1; i++) {
        sb.append(String.format("%02X%s", buffer[i], ""));
    }
    sb.append(String.format("%02X", buffer[buffer.length - 1]));

    return sb.toString();
}


来源: stackexchange

问:
create like button using react native and firebase
I'm beginner in react-native and I'm actually developing a event application in React-Native , i'm trying to create a like/dislike button . that's my code but not work

```<code>  const [likes,setLikes] = useState('');
const [liked,setLiked] = useState(false);

const eventInfo = ()=>{
    const getInfo = firebase.database().ref('/users/event/' +postKey)
    getInfo.on('value', snapshot => {
        console.log('User data: ', snapshot.val())
        setLikes(snapshot.val().likes)
       // setIntersted(snapshot.val().interested)
       // setInterestedNmb(snapshot.val().interestedNmb)
       // setInterestedName(snapshot.val().interestedName)
        setLiked(snapshot.val().liked)
      });
}

const like = () => {
    const updateLike = firebase.database().ref('/users/event/' +postKey)
    updateLike.update({
        likes: likes +1 ,
        liked: true
    })
  };

  const dislike = () => {
    const updateLike = firebase.database().ref('/users/event/' +postKey)
    updateLike.update({
        likes: likes -1 ,
        liked: false
    })
  };
</code>```

the problem is when i press <TouchableOpacity onPress={()=> like() />  by one user . like transform to true in all users . i want to create a list if a user press like . the user id added to the list . and if the user id is in the list like is true . if the user id isn't in the list . like is false
give me a solve please
Thanks in advance!

答:
From your code what I understand is, you have initialised variable likes as string

```<code>const [likes,setLikes] = useState('');
</code>```

if you make this function work on this variable

```<code>const like = () => {
const updateLike = firebase.database().ref('/users/event/' +postKey)
updateLike.update({
    likes: likes +1 ,
    liked: true
})};

 const dislike = () => {
const updateLike = firebase.database().ref('/users/event/' +postKey)
updateLike.update({
    likes: likes -1 ,
    liked: false
})};
</code>```

then your addition will give you output like 111 if you clicked like button 3 times and dislike will give you 11 if clicked after.
So you need to initialise your variable as integer like this

```<code> const [likes,setLikes] = useState(0);
</code>```

If you are getting any other error feel free to comment.

ContentLicense: CC BY-SA 4.0

Body:
I'm beginner in react-native and I'm actually developing a event application in React-Native , i'm trying to create a like/dislike button . that's my code but not work

  const [likes,setLikes] = useState('');
const [liked,setLiked] = useState(false);

const eventInfo = ()=>{
    const getInfo = firebase.database().ref('/users/event/' +postKey)
    getInfo.on('value', snapshot => {
        console.log('User data: ', snapshot.val())
        setLikes(snapshot.val().likes)
       // setIntersted(snapshot.val().interested)
       // setInterestedNmb(snapshot.val().interestedNmb)
       // setInterestedName(snapshot.val().interestedName)
        setLiked(snapshot.val().liked)
      });
}

const like = () => {
    const updateLike = firebase.database().ref('/users/event/' +postKey)
    updateLike.update({
        likes: likes +1 ,
        liked: true
    })
  };

  const dislike = () => {
    const updateLike = firebase.database().ref('/users/event/' +postKey)
    updateLike.update({
        likes: likes -1 ,
        liked: false
    })
  };

the problem is when i press <TouchableOpacity onPress={()=> like() />  by one user . like transform to true in all users . i want to create a list if a user press like . the user id added to the list . and if the user id is in the list like is true . if the user id isn't in the list . like is false
give me a solve please
Thanks in advance!

Body:
From your code what I understand is, you have initialised variable likes as string

const [likes,setLikes] = useState('');

if you make this function work on this variable

const like = () => {
const updateLike = firebase.database().ref('/users/event/' +postKey)
updateLike.update({
    likes: likes +1 ,
    liked: true
})};

 const dislike = () => {
const updateLike = firebase.database().ref('/users/event/' +postKey)
updateLike.update({
    likes: likes -1 ,
    liked: false
})};

then your addition will give you output like 111 if you clicked like button 3 times and dislike will give you 11 if clicked after.
So you need to initialise your variable as integer like this

 const [likes,setLikes] = useState(0);

If you are getting any other error feel free to comment.


问:
How to send foreignkey data type in API by DRF
I have API written by Django Rest Framework:

models.py

```<code>STATUSES = (("F", "free"),
            ("R", "registered"),
            ("N", "not free")
            )
class Collector(models.Model):
    ip = models.TextField()

    class Meta:
        verbose_name = 'Коллектор'
        verbose_name_plural = 'Коллекторы'
        ordering = ('ip',)

    def __str__(self):
        return str(self.ip)

class Port(models.Model):
    port = models.CharField(max_length=1000)
    status = models.CharField(max_length=1, choices=STATUSES, default="F")
    collector_link = models.ForeignKey(Collector, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Порт'
        verbose_name_plural = 'Порты'
        ordering = ('port',)

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

serializers.py

```<code>class CollectorSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Collector
        fields = ("__all__")

class PortSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Port
        fields = ("__all__")
</code>```

views.py

```<code>class CollectorAPIView(APIView):
    serializer_class = serializers.CollectorSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        ip = request.POST['ip']
        obj = models.Collector(ip=request.POST['ip'])
        obj.save()
        return Response(status=status.HTTP_200_OK)

class PortAPIView(APIView):
    serializer_class = serializers.PortSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        port, status1, collector_link = request.POST["port"], request.POST["status"], request.POST["collector_link"]
        entry = models.Port(port=port, status=status1, collector_link=collector_link)
</code>```

entry.save()
            return Response(status=status.HTTP_201_CREATED)
In result, when I'm trying to send data to API in json format like {"port": "1", "status": "F", "collector_link": "10"} (collector_link=10 is id of collector instance in data base) I'm getting the next error:

ValueError at /sm/api/v1/port/ Cannot assign "'10'":
  "Port.collector_link" must be a "Collector" instance
  How I can to fix it?
  .

答:
You are using django rest framework's serializer class, but you don't have apply it in your views, also you are doing request.POST which is not convenient, rather you should use request.data. So update your PortAPIView as follows,

```<code>class PortAPIView(APIView):
    serializer_class = PortSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
</code>```

Body:
I have API written by Django Rest Framework:

models.py

STATUSES = (("F", "free"),
            ("R", "registered"),
            ("N", "not free")
            )
class Collector(models.Model):
    ip = models.TextField()

    class Meta:
        verbose_name = 'Коллектор'
        verbose_name_plural = 'Коллекторы'
        ordering = ('ip',)

    def __str__(self):
        return str(self.ip)

class Port(models.Model):
    port = models.CharField(max_length=1000)
    status = models.CharField(max_length=1, choices=STATUSES, default="F")
    collector_link = models.ForeignKey(Collector, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Порт'
        verbose_name_plural = 'Порты'
        ordering = ('port',)

    def __str__(self):
        return str(self.port)

serializers.py

class CollectorSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Collector
        fields = ("__all__")

class PortSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Port
        fields = ("__all__")

views.py

class CollectorAPIView(APIView):
    serializer_class = serializers.CollectorSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        ip = request.POST['ip']
        obj = models.Collector(ip=request.POST['ip'])
        obj.save()
        return Response(status=status.HTTP_200_OK)

class PortAPIView(APIView):
    serializer_class = serializers.PortSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        port, status1, collector_link = request.POST["port"], request.POST["status"], request.POST["collector_link"]
        entry = models.Port(port=port, status=status1, collector_link=collector_link)

entry.save()
            return Response(status=status.HTTP_201_CREATED)
In result, when I'm trying to send data to API in json format like {"port": "1", "status": "F", "collector_link": "10"} (collector_link=10 is id of collector instance in data base) I'm getting the next error:

ValueError at /sm/api/v1/port/ Cannot assign "'10'":
  "Port.collector_link" must be a "Collector" instance
  How I can to fix it?
  .

Body:
You are using django rest framework's serializer class, but you don't have apply it in your views, also you are doing request.POST which is not convenient, rather you should use request.data. So update your PortAPIView as follows,

class PortAPIView(APIView):
    serializer_class = PortSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)


问:
Why does a % percentage appear at the end of the output to standard out but not when I use endl?
Why is there a trailing % at the end of this output?  I've tried flushing the stream (not endl), however when I end the stream with a call to endl it gets rid of the %.  Any help here would be much appreciated.

```<code>template<class T>
void print_collection(T * t){
        for(int i = 0; i < t->size()-1; ++i){
                cout << t->at(i) << ", ";
        }
        std::cout<< t->at(t->size() -1);
        std::cout<<flush;
}

int main(){
        int n_A = 5;
        int A[] = {2, 3, -2, 34, -29};

        vector<int> vec(A, A + n_A);
        sort(vec.begin(), vec.end());

        print_collection(&vec);
        return 0;
}

OUTPUT
-29, -2, 2, 3, 34%
</code>```

Here is more information about the compiler, I'm using macOS 10.15.4:

```<code>g++ -Wall -std=c++11 array.cpp -o array

g++ Information:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.59)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
</code>```

答:
I noticed a similar question ages back.

This could potentially be from your export shell, not the output to the program itself.
So before you change anything major, take a look into that.

Depending on what you're doing-- a good way to prevent that from showing up would be by adding a newline to the output within your print function.

Body:
Why is there a trailing % at the end of this output?  I've tried flushing the stream (not endl), however when I end the stream with a call to endl it gets rid of the %.  Any help here would be much appreciated.

template<class T>
void print_collection(T * t){
        for(int i = 0; i < t->size()-1; ++i){
                cout << t->at(i) << ", ";
        }
        std::cout<< t->at(t->size() -1);
        std::cout<<flush;
}

int main(){
        int n_A = 5;
        int A[] = {2, 3, -2, 34, -29};

        vector<int> vec(A, A + n_A);
        sort(vec.begin(), vec.end());

        print_collection(&vec);
        return 0;
}

OUTPUT
-29, -2, 2, 3, 34%

Here is more information about the compiler, I'm using macOS 10.15.4:

g++ -Wall -std=c++11 array.cpp -o array

g++ Information:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.59)
Target: x86_64-apple-darwin19.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin


问:
Image Co-Ordinate System Design
I'm diving into something without sufficient background, but I feel like there may be simple solutions that don't require me to have in depth knowledge of the topic.

What I am trying to do is have an image co-ordinate system. Basically the user will supply an image, like a house plan. They can then click on points in the image and create markers (like google maps). The next time they retrieve the map, all the markers they added before are there and they can add new ones.

I need to identify the points these markers are located on so I can store that information. I also need to be able to create a layer on the image that contains the markers and renders them in the exact locations they were placed.

I imagine the easiest way to do this is to use pixel co-ordinates...the rub here is that the image won't be a fixed size since there is a web application and an IPad application, so the co-ordinate system needs to work as long as the image is in the same size ratio.

The server size is .NET and as mentioned there is an IPad app, so the solution needs to be viable given that tech stack.

Any ideas?

答: Instead of using pixel coordinates in absolute terms, you can use the 0 to 1 range. The top left corner is (0,0), bottom right is (1,1) and the center of the image is (0.5,0.5). This way not matter what image size (or zoom level) you have, the markers will always be in the same place.</p>

ContentLicense: CC BY-SA 3.0

Title: Image Co-Ordinate System Design


问:
"was unexpected at this time"
I am running
for blob in $(git fsck --lost-found | awk ‘$2 == “blob” { print $3 }’); do git cat-file -p $blob > $blob.txt; done
and getting a "blob was unexpected at this time". How do I resolve this?

答: Fix your quotes. It should be "blob", not “blob”. The first one is valid code, the second one is decorative typography.

Title: "was unexpected at this time"


问:
General insertion sort algorithm not moving the first object in list
I need to create a  general insertion sort algorithm using move semantics. I have it working for entire lists of different types of objects except for the very first object in the list.

```<code>template<typename Iter, typename Comparator>
void insertionSort(const Iter& begin, const Iter& end, Comparator compareFn)
{
    for (auto i = begin + 1; i < end; i++)
    {
        auto currentthing = std::move(*i);
        auto j = std::move(i - 1);

        while (j >= begin and compareFn(*j, currentthing))
        {
            *(j + 1) = std::move(*j);
            if (j == begin)
                break;
            j--;
        }
        *(j + 1) = std::move(currentthing);
    }
}
</code>```

Where comparing a list of strings from my main function:

```<code>int main()
{
    vector<int> numbers = { 0, 1, 8, 4, 2, 9, 5, 3, 6, 7, 10 };
    insertionSort(numbers.begin(), numbers.end(), std::less<int>());

    cout << "Sorted: " << numbers << "\n";

    vector<string> names = { "p", "a", "b", "d", "c", "f", "e" };
    insertionSort(names.begin(), names.end(), std::greater<string>());

    cout << "Sorted: " << names << "\n";

    return 0;
}

</code>```

Outputs the following

```<code>Sorted: [ 0 10 9 8 7 6 5 4 3 2 1 ]
Sorted: [  a b c d e f ]
</code>```

答:
The while loop should break when j equals i and not when j equals begin. So, the following:

```<code>if (j == begin)
    break;
</code>```

should actually be:

```<code>if (j == i)
    break;
</code>```

Body:
I need to create a  general insertion sort algorithm using move semantics. I have it working for entire lists of different types of objects except for the very first object in the list.

template<typename Iter, typename Comparator>
void insertionSort(const Iter& begin, const Iter& end, Comparator compareFn)
{
    for (auto i = begin + 1; i < end; i++)
    {
        auto currentthing = std::move(*i);
        auto j = std::move(i - 1);

        while (j >= begin and compareFn(*j, currentthing))
        {
            *(j + 1) = std::move(*j);
            if (j == begin)
                break;
            j--;
        }
        *(j + 1) = std::move(currentthing);
    }
}

Where comparing a list of strings from my main function:

int main()
{
    vector<int> numbers = { 0, 1, 8, 4, 2, 9, 5, 3, 6, 7, 10 };
    insertionSort(numbers.begin(), numbers.end(), std::less<int>());

    cout << "Sorted: " << numbers << "\n";

    vector<string> names = { "p", "a", "b", "d", "c", "f", "e" };
    insertionSort(names.begin(), names.end(), std::greater<string>());

    cout << "Sorted: " << names << "\n";

    return 0;
}

Outputs the following

Sorted: [ 0 10 9 8 7 6 5 4 3 2 1 ]
Sorted: [  a b c d e f ]

Body:
The while loop should break when j equals i and not when j equals begin. So, the following:

if (j == begin)
    break;

should actually be:

if (j == i)
    break;


问:
Disable dragging of image in entire project HTML pages
I want to disable dragging of all the images in my project which has a large amount of images. The results that I found on web was to disable a particular image. Putting draggable="false" inside every image tag would take a lot of time. So I want a solution to disable them together.

I was successful to disable dragging with this code but it's still draggable in Firefox .

```<code>img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}
</code>```

I've already gone through Disable dragging an image from an HTML page but found no answer to my question.

答:
You could add ondragstart attribute to single image & return false.

If you want to address multiple images

```<code>const imgs = document.getElementsByTagName('img');
for(let i = 0; i < imgs.length; i++ ) {
    imgs[i].setAttribute("ondragstart", "return false")
}
</code>```

Note from React Synthetic events

As of v0.14, returning false from an event handler will no longer stop event propagation. Instead, e.stopPropagation() or e.preventDefault() should be triggered manually, as appropriate.

So you need add to each image.

 e.preventDefault()} />

Body:
I want to disable dragging of all the images in my project which has a large amount of images. The results that I found on web was to disable a particular image. Putting draggable="false" inside every image tag would take a lot of time. So I want a solution to disable them together.

I was successful to disable dragging with this code but it's still draggable in Firefox .

img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}

I've already gone through Disable dragging an image from an HTML page but found no answer to my question.

Body:
You could add ondragstart attribute to single image & return false.

If you want to address multiple images

const imgs = document.getElementsByTagName('img');
for(let i = 0; i < imgs.length; i++ ) {
    imgs[i].setAttribute("ondragstart", "return false")
}

Note from React Synthetic events

As of v0.14, returning false from an event handler will no longer stop event propagation. Instead, e.stopPropagation() or e.preventDefault() should be triggered manually, as appropriate.

So you need add to each image.

<img src={source} onDragStart={e => e.preventDefault()} />


问:
Python flask: return values multiple times
I ran my code on Jupyter Notebook and I wanted to return different values on the web while running the function. However, it only returned one value. I also tried yield, but it had an error on the web.

```<code>from werkzeug.wrappers import Request, Response
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    list = [0,0,0]
    for i in range(10):
        list.append(i)
        return str(list)

if __name__ == "__main__":
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, app)
</code>```

Output:
[0,0,0,0]

Expected Output:
[0,0,0,0]
then change to:
[0,0,0,0,1]
then go on until it stops at:
[0,0,0,0,1,2,3,4,5,6,7,8,9]

答:
Your indent is a little off on the return of the list.  This is returning it on the first loop.  Corrected Code is below:</p>

```<code>from werkzeug.wrappers import Request, Response
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    list = [0,0,0]
    for i in range(10):
        list.append(i)
    return str(list)

if __name__ == "__main__":
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, app)
</code>```

Body:
I ran my code on Jupyter Notebook and I wanted to return different values on the web while running the function. However, it only returned one value. I also tried yield, but it had an error on the web.

from werkzeug.wrappers import Request, Response
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    list = [0,0,0]
    for i in range(10):
        list.append(i)
        return str(list)

if __name__ == "__main__":
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, app)

Output:
[0,0,0,0]

Expected Output:
[0,0,0,0]
then change to:
[0,0,0,0,1]
then go on until it stops at:
[0,0,0,0,1,2,3,4,5,6,7,8,9]

Body:
Your indent is a little off on the return of the list.  This is returning it on the first loop.  Corrected Code is below:

from werkzeug.wrappers import Request, Response
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    list = [0,0,0]
    for i in range(10):
        list.append(i)
    return str(list)

if __name__ == "__main__":
    from werkzeug.serving import run_simple
    run_simple('localhost', 9000, app)


问:
How to Update a value in array with specific index in react native
i want to create a program like a quiz. the scenario is the user will submit the answer and the answer will be store in array. the variable array is answer.

this.state = { answer : [] }```

the user will be give the answer and store to answer. maybe value will be like ['a','b','c'] this is just an example answer will be store in array. Nah, the feature the quiz can show the previous or next question, and the user can change the answer on the array. How to change the value in array in the specific index? In example the answer b in the second index on array will be change to a. How can i change the value?

答:
<pre class="lang-js prettyprint-override"><code>// Use react setState callback to ensure you get the updated state value
this.setState((state) => {
  // Create new array to prevent passing reference to make it pure
  const newAnswer = [...state.answer]
  // Chage value of new array
  newAnswer[index] = newValue

  return {answer: newAnswer}
 }
)
</code>```

Body:
i want to create a program like a quiz. the scenario is the user will submit the answer and the answer will be store in array. the variable array is answer.

this.state = { answer : [] }

the user will be give the answer and store to answer. maybe value will be like ['a','b','c'] this is just an example answer will be store in array. Nah, the feature the quiz can show the previous or next question, and the user can change the answer on the array. How to change the value in array in the specific index? In example the answer b in the second index on array will be change to a. How can i change the value?


问:
loop through sql query which save in the dataframe?

user save the sql query in the pd , i want execute each the sql query then put into the same pd
the dataframe like below

```<code>   colunm1 = 'id1' , 'id2 '
   column2 = 'select sum(total) from table where data_mothrn ='2020-04'' ,
             'select sum(total) from table2 where data_month ='2020-04'' ,
   column3 = 'result from column2'
             'result from column2'
</code>```

i want to literate this thing?
put the each column2 result into column3 by each row

```<code>list_para = []
def cacth_column2_sql():
    a = df_parameter['column2'].iloc[i]
    return a

def result_sql (p):
    df0 = pd.read_sql(p, conn)
    a = df0.iat[0, 0]
    list_para.append(a)

a = cacth_column2_sql()
result_sql(a)

</code>```

how can i create new column to save the result by automatic ?

答:
Your question requires more inputs from you. Please update it correctly.

Based on what I understand:

I have created a code that reads the input from user (Parameter-name, parameter-data) and shows it in the output. Each record can be accessed by Parameter-name

```<code>import pandas as pd

n_times = int(input("How many input queries you want to add"))

res = []
for i in range(0,n_times):

   paramname = input("Enter the id for the query ")
   paramdata = input("Enter the sql query ")
   #column3 = 'result from column2'
   result = pd.read_sql(paramdata, conn)
   #You can add code to check correct syntax here of input
   df1 = pd.DataFrame(data=[[paramname,paramdata,result]],columns=
   ["Parameter-Name", "Parameter-Data","Result"])
   df1.index = df1.index + 1

print(df1)
</code>```

You can access the queries by index like this

```<code>df1.iloc[0]
</code>```

Body:
user save the sql query in the pd , i want execute each the sql query then put into the same pd
the dataframe like below

   colunm1 = 'id1' , 'id2 '
   column2 = 'select sum(total) from table where data_mothrn ='2020-04'' ,
             'select sum(total) from table2 where data_month ='2020-04'' ,
   column3 = 'result from column2'
             'result from column2'

i want to literate this thing?
put the each column2 result into column3 by each row

list_para = []
def cacth_column2_sql():
    a = df_parameter['column2'].iloc[i]
    return a

def result_sql (p):
    df0 = pd.read_sql(p, conn)
    a = df0.iat[0, 0]
    list_para.append(a)

a = cacth_column2_sql()
result_sql(a)

how can i create new column to save the result by automatic ?

Body:
Your question requires more inputs from you. Please update it correctly.

Based on what I understand:

I have created a code that reads the input from user (Parameter-name, parameter-data) and shows it in the output. Each record can be accessed by Parameter-name

import pandas as pd

n_times = int(input("How many input queries you want to add"))

res = []
for i in range(0,n_times):

   paramname = input("Enter the id for the query ")
   paramdata = input("Enter the sql query ")
   #column3 = 'result from column2'
   result = pd.read_sql(paramdata, conn)
   #You can add code to check correct syntax here of input
   df1 = pd.DataFrame(data=[[paramname,paramdata,result]],columns=
   ["Parameter-Name", "Parameter-Data","Result"])
   df1.index = df1.index + 1

print(df1)

You can access the queries by index like this

df1.iloc[0]


问:
How to set random seed when it is in distributed training in PyTorch?
Now I am training a model using torch.distributed, but I am not sure how to set the random seeds. For example, this is my current code:

def main():
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    cudnn.enabled = True
    cudnn.benchmark = True
    cudnn.deterministic = True

    mp.spawn(main_worker, nprocs=args.ngpus, args=(args,))
```

<p>And should I move the</p>

<pre class="lang-py prettyprint-override"><code>    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    cudnn.enabled = True
    cudnn.benchmark = True
    cudnn.deterministic = True
</code>```

into the function main_worker() to make sure every process has the correct seed and cudnn settings? By the way, I have tried this, and this behavior will make the training 2 times slower, which really confused me.

Thank you very much for any help!

答:
The spawned child processes do not inherit the seed you set manually in the parent process, therefore you need to set the seed in the main_worker function.

The same logic applies to cudnn.benchmark and cudnn.deterministic, so if you want to use these, you have to set them in main_worker as well. If you want to verify that, you can just print their values in each process.

cudnn.benchmark = True tries to find the optimal algorithm for your model, by benchmarking various implementations of certain operations (e.g. available convolution algorithms). This will take time to find the best algorithm, but once that is done, further iterations will potentially be faster. The algorithm that was determined to be the best, only applies to the specific input size that was used. If in the next iteration you have a different input size, the benchmark needs to be run again, in order to determine the best algorithm for that specific input size, which might be a different one than for the first input size.

I'm assuming that your input sizes vary, which would explain the slow down, as the benchmark wasn't used when it was set in the parent process. cudnn.benchmark = True should only be used if your input sizes are fixed.

cudnn.determinstic = True may also have a negative impact on the performance, because certain underlying operations, that are non-deterministic, need to be replaced with a deterministic version, which tend to be slower, otherwise the deterministic version would be used in the first place, but that performance impact shouldn't be too dramatic.

Body:
Now I am training a model using torch.distributed, but I am not sure how to set the random seeds. For example, this is my current code:

def main():
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    cudnn.enabled = True
    cudnn.benchmark = True
    cudnn.deterministic = True

    mp.spawn(main_worker, nprocs=args.ngpus, args=(args,))

And should I move the

    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    cudnn.enabled = True
    cudnn.benchmark = True
    cudnn.deterministic = True

into the function main_worker() to make sure every process has the correct seed and cudnn settings? By the way, I have tried this, and this behavior will make the training 2 times slower, which really confused me.

Thank you very much for any help!


问:
why doesnt Stochastic gradient descent fluctuate
In batch gradient descent the parameters were updated based on the total/average loss of all the points
In Stochastic gradient descent or SGD
we are updating the parameters after every point instead of one epoch.
so lets say if the final point is an outlier woudnt that cause the whole fitted line to fluctuate drastically.
How is it reliable .
or converge on a contour like this SGD contour</p>

答:
While it is true that in its most pristine form SGD operates on just 1 sample point, in reality this is not the dominant practice. In practice, we use a mini-batch of say 256, 128 or 64 samples rather than operating on the full batch size containing all the samples in the database, which might be well over than 1 million samples. So clearly operating on a mini-batch of say 256 is much faster than operating on 1 million points and at the same time helps curb the variability caused due to just using 1 sample point.

A second point is that there is no final point. One simply keeps iterating over the dataset. The learning rate for SGD is generally quite small say 1e-3. So even if a sample point happens to be an outlier, the wrong gradients will be scaled by 1e-3 and hence SGD will not be too much off the correct trajectory. When it iterates over the upcoming sample points, which are not outliers, it will again head towards the correct direction.

So altogether using a medium-sized mini-batch and using a small learning rate helps SGD to not digress a lot from the correct trajectory.

Now the word stochastic in SGD can also imply various other measures. For example some practitioners also use gradient clipping i.e. they clamp the calculated gradient to maximum value if the gradients are well over this decided maximum threshold. You can find more on gradient clipping in this post. Now, this is just one trick amongst dozens of other techniques and if you are interested can read source code of popular implementation of SGD in PyTorch or TensorFlow.


问:
How to use Redux to represent Material UI Drawer?
I am trying to implement Drawer, which will appear on the left with a saving state of the Drawer using Redux. But unfortunately, I did something wrong and my onClick events just don`t respond. Code:

Reducer:

import { NEW_DATA_LOADED, DRAWER_TOGGLED } from '../actions/types';
import { initialState } from '../store';

export default function rootReducer(state = initialState, action) {
    console.log(state);
    console.log(action);
    switch (action.type) {
        case DRAWER_TOGGLED: {
            return { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: action.value };
        }
        case NEW_DATA_LOADED: {
            const keyValue = action.keyValue;
            const content = action.content;
            console.log(action);
            let newState = { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: state.drawerToggled };;
            newState[keyValue] = content;
            return newState;
        }
        default:
            return state;
    }
}
```

<p><br/>creators.js:<br/></p>

<pre class="lang-js prettyprint-override"><code>import { NEW_DATA_LOADED, DRAWER_TOGGLED } from "./types";

const newDataLoaded = (key, content) => ({ type: NEW_DATA_LOADED, content: content, keyValue: key });
const drawerToggled = (open) => ({ type: DRAWER_TOGGLED, value:open });

export { newDataLoaded , drawerToggled };
</code>```

store.js:

import { createStore, compose, applyMiddleware } from "redux";
import rootReducer from './reducers/root';
import ReduxThunk from 'redux-thunk';

const initialState = { articles:[], authors:[],categories:[],  drawerToggled: false };

export default function configStore() {
  return createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(ReduxThunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    )
  );
}
export { initialState };
```

<p><br/>
And NavBar.js:<br/></p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import { AppBar, Toolbar } from '@material-ui/core';
import FaceIcon from '@material-ui/icons/Face';
import MenuIcon from '@material-ui/icons/Menu';
import IconButton from 'material-ui/IconButton';
import Drawer from "@material-ui/core/Drawer";
import ListItem from "@material-ui/core/ListItem";
import List from "@material-ui/core/List";
import makeStyles from "@material-ui/styles/makeStyles";
import { BrowserRouter as Router } from "react-router-dom";
import ListItemText from "@material-ui/core/ListItemText";
import BackToTopButton from "../BackToTopButton/BackToTopButton";
import { connect } from 'react-redux';
import { toggleDrawer } from '../../actions';
import './NavBar.css';

const useStyles = makeStyles(theme => ({
    list: {
        width: 250
    },
    fullList: {
        width: "auto"
    },
    paper: {
        background: "#485461"
    }
}));
function NavBar(props){
        const toolbar = React.createRef();
        let toolbarElement = props.article === true ? <Toolbar id="back-to-top-anchor" ref={toolbar} /> : <Toolbar />;
        let button = null;
        if (props.article === true) {
            button = <BackToTopButton anchor={toolbar} />;
        }
        const classes  = useStyles;
        const navbar_links = [["Home", "/"], ["Categories", "/categories"], ["Interesting Posts For You", "/interesting"], ["Your Inbox", "/inbox"], ["Register account","/registration"]];
        const sideList = (
            <div className={classes.list} role="presentation" onClick={props.toggleDrawer(false)}
                onKeyDown={props.toggleDrawer(false)}>
                <List>
                    {navbar_links.map((text) => (
                        <ListItem component="a" button key={text[0]} href={text[1]}>
                            <ListItemText>{text[0]}</ListItemText>
                        </ListItem>
                    ))}
                </List>
            </div>
        );
    const toggleDrawer = (open) => { props.toggleDrawer(open) };
    const drawerToggled = props.drawerToggled;
        return (
            <React.Fragment>
                <Router>
                    <AppBar position="sticky">
                        <Toolbar>
                            <IconButton className={"menu"} aria-label="Menu" color="white"
                                onClick={toggleDrawer(true)}>
                                <MenuIcon />
                            </IconButton>
                            <Drawer
                                classes={{ paper: classes.paper }}
                                open={drawerToggled}
                                onClose={toggleDrawer(false)}
                            >
                                <div
                                    tabIndex={0}
                                    role="button"
                                    onClick={toggleDrawer(false)}
                                    onKeyDown={toggleDrawer(false)}
                                    className={{ root: classes.root }}
                                >
                                    {sideList}
                                </div>
                            </Drawer>

                            <section className={"rightToolBar"}>
                                <IconButton className={"profile"} aria-label="My profile" color={"black"} href="/profile">
                                    <FaceIcon />
                                </IconButton>
                            </section>
                        </Toolbar>
                    </AppBar>
                    {toolbarElement}
                </Router>
                {button}
            </React.Fragment>
        );
    }

const mapStateToProps = (state) => ({
    drawerToggled:state.drawerToggled
});
const mapDispatchToProps = (dispatch) => ({
    toggleDrawer: (open) => dispatch(toggleDrawer(open)),
});

export default connect(mapStateToProps, mapDispatchToProps)(NavBar);
</code>```

P.S. Version of this navbar, implemented with react state worked good, so the problem is somewhere in redux usage.

Can anyone help me to make it work?
CodeSandbox:

https://codesandbox.io/s/github/LilJohny/BlogUI/tree/develop_4

答:
From the code, toggleDrawer in mapDispatchToProps should actually be drawerToggled in creators like this:

```<code>toggleDrawer: (open) => dispatch(drawToggled(open)),
</code>```

You might want to rename the variable to match what you have in mapDispatchToProps, to avoid confusion.

If this is doesn't fix your problem, maybe setting up a codesandbox will help people troubleshoot your problem better.

Body:
I am trying to implement Drawer, which will appear on the left with a saving state of the Drawer using Redux. But unfortunately, I did something wrong and my onClick events just don`t respond. Code:

Reducer:

import { NEW_DATA_LOADED, DRAWER_TOGGLED } from '../actions/types';
import { initialState } from '../store';

export default function rootReducer(state = initialState, action) {
    console.log(state);
    console.log(action);
    switch (action.type) {
        case DRAWER_TOGGLED: {
            return { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: action.value };
        }
        case NEW_DATA_LOADED: {
            const keyValue = action.keyValue;
            const content = action.content;
            console.log(action);
            let newState = { categories: state.categories, authors: state.authors, articles: state.articles, drawerToggled: state.drawerToggled };;
            newState[keyValue] = content;
            return newState;
        }
        default:
            return state;
    }
}

creators.js:

import { NEW_DATA_LOADED, DRAWER_TOGGLED } from "./types";

const newDataLoaded = (key, content) => ({ type: NEW_DATA_LOADED, content: content, keyValue: key });
const drawerToggled = (open) => ({ type: DRAWER_TOGGLED, value:open });

export { newDataLoaded , drawerToggled };

store.js:

import { createStore, compose, applyMiddleware } from "redux";
import rootReducer from './reducers/root';
import ReduxThunk from 'redux-thunk';

const initialState = { articles:[], authors:[],categories:[],  drawerToggled: false };

export default function configStore() {
  return createStore(
    rootReducer,
    initialState,
    compose(
      applyMiddleware(ReduxThunk),
      window.devToolsExtension ? window.devToolsExtension() : f => f
    )
  );
}
export { initialState };

And NavBar.js:

import React from 'react';
import { AppBar, Toolbar } from '@material-ui/core';
import FaceIcon from '@material-ui/icons/Face';
import MenuIcon from '@material-ui/icons/Menu';
import IconButton from 'material-ui/IconButton';
import Drawer from "@material-ui/core/Drawer";
import ListItem from "@material-ui/core/ListItem";
import List from "@material-ui/core/List";
import makeStyles from "@material-ui/styles/makeStyles";
import { BrowserRouter as Router } from "react-router-dom";
import ListItemText from "@material-ui/core/ListItemText";
import BackToTopButton from "../BackToTopButton/BackToTopButton";
import { connect } from 'react-redux';
import { toggleDrawer } from '../../actions';
import './NavBar.css';

const useStyles = makeStyles(theme => ({
    list: {
        width: 250
    },
    fullList: {
        width: "auto"
    },
    paper: {
        background: "#485461"
    }
}));
function NavBar(props){
        const toolbar = React.createRef();
        let toolbarElement = props.article === true ? <Toolbar id="back-to-top-anchor" ref={toolbar} /> : <Toolbar />;
        let button = null;
        if (props.article === true) {
            button = <BackToTopButton anchor={toolbar} />;
        }
        const classes  = useStyles;
        const navbar_links = [["Home", "/"], ["Categories", "/categories"], ["Interesting Posts For You", "/interesting"], ["Your Inbox", "/inbox"], ["Register account","/registration"]];
        const sideList = (

                <List>
                    {navbar_links.map((text) => (
                        <ListItem component="a" button key={text[0]} href={text[1]}>
                            <ListItemText>{text[0]}</ListItemText>
                        </ListItem>
                    ))}
                </List>

        );
    const toggleDrawer = (open) => { props.toggleDrawer(open) };
    const drawerToggled = props.drawerToggled;
        return (
            <React.Fragment>
                <Router>
                    <AppBar position="sticky">
                        <Toolbar>
                            <IconButton className={"menu"} aria-label="Menu" color="white"
                                onClick={toggleDrawer(true)}>
                                <MenuIcon />
                            </IconButton>
                            <Drawer
                                classes={{ paper: classes.paper }}
                                open={drawerToggled}
                                onClose={toggleDrawer(false)}
                            >

                                    {sideList}

                            </Drawer>

                                <IconButton className={"profile"} aria-label="My profile" color={"black"} href="/profile">
                                    <FaceIcon />
                                </IconButton>

                        </Toolbar>
                    </AppBar>
                    {toolbarElement}
                </Router>
                {button}
            </React.Fragment>
        );
    }

const mapStateToProps = (state) => ({
    drawerToggled:state.drawerToggled
});
const mapDispatchToProps = (dispatch) => ({
    toggleDrawer: (open) => dispatch(toggleDrawer(open)),
});

export default connect(mapStateToProps, mapDispatchToProps)(NavBar);

P.S. Version of this navbar, implemented with react state worked good, so the problem is somewhere in redux usage.

Can anyone help me to make it work?
CodeSandbox:

https://codesandbox.io/s/github/LilJohny/BlogUI/tree/develop_4

Body:
From the code, toggleDrawer in mapDispatchToProps should actually be drawerToggled in creators like this:

toggleDrawer: (open) => dispatch(drawToggled(open)),

You might want to rename the variable to match what you have in mapDispatchToProps, to avoid confusion.

If this is doesn't fix your problem, maybe setting up a codesandbox will help people troubleshoot your problem better.


问:
can't able to mock a variable while testing
I am trying testing on node js I want to mock a variable outside of a function that is going to be unit tested.
for example

```<code>const sample = [];
function uploadDoc {
sample.push('fileLocation')
}
function toSave(){
for (i=0;i<sample.length;i++)
**some process read and access doc
}
</code>```

I am facing issue while unit testing the second function
I have tried rewire npm that is also not working

答:
Well, you face challenges to test both functions, then, what you need is to refactor the code. Because I think, your code is not testable.
I give you this long example, which contain both of your functions but testable.

Changes I made for refactor:

function uploadDoc now will output an array.

function toSave now will require 1 parameter, which is an array.

combine functions into class.

const sinon = require('sinon');
const { expect } = require('chai');

const Doc = {
  /**
   * @return array of file location.
   */
  uploadDoc: () => {
    const sample = [];
    sample.push('fileLocation');
    return sample;
  },

  /**
   * @param array samples
   * @return void
   */
  toSave: (samples) => {
    samples.forEach(() => {
      // Some process read and access doc.
    })
  },
}

/**
 * This is for example purposes.
 * @return void.
 */
function integrationBothFunction () {
  const samples = Doc.uploadDoc();
  Doc.toSave(samples);
}

describe('Unit Test', function () {
  it('uploadDoc fn', function () {
    const result = Doc.uploadDoc();
    // You expect the result to be an array.
    expect(result).to.be.an('array');
  });
  it('toSave fn', function () {
    const samples = [];
    const spySamples = sinon.spy(samples, 'forEach');
    // Call the function
    Doc.toSave(samples);
    // You expect: there is forEach called for samples.
    expect(spySamples.calledOnce).to.equal(true);
    // Do not forget to restore.
    spySamples.restore();
  });

  it('integrationBothFunction fn', function () {
    // This is just sample to check.
    const testSample = ['x'];
    // Now finally, you can stub uploadDoc.
    // Where real uploadDoc function not get called.
    const stubUploadDoc = sinon.stub(Doc, 'uploadDoc');
    stubUploadDoc.returns(testSample);

    // Spy on toSave fn.
    const spyToSave = sinon.spy(Doc, 'toSave');

    integrationBothFunction();

    // You expect that toSave is processing output from uploadDoc.
    expect(stubUploadDoc.calledOnce).to.equal(true);
    expect(spyToSave.calledOnce).to.equal(true);
    // Check argument toSave.
    const { args } = spyToSave;
    expect(args).to.have.lengthOf(1);
    expect(args[0]).to.have.lengthOf(1);
    expect(args[0][0]).to.include(testSample[0]);
    // Restore spy and stub.
    stubUploadDoc.restore();
    spyToSave.restore();
  });
});

```

<p>I you run using mocha:</p>

```$ npx mocha stackoverflow.js

  Unit Test
    ✓ uploadDoc fn
    ✓ toSave fn
    ✓ integrationBothFunction fn

  3 passing (13ms)
$
```

Hope this helps. Good luck!

Body:
I am trying testing on node js I want to mock a variable outside of a function that is going to be unit tested.
for example

const sample = [];
function uploadDoc {
sample.push('fileLocation')
}
function toSave(){
for (i=0;i<sample.length;i++)
**some process read and access doc
}

I am facing issue while unit testing the second function
I have tried rewire npm that is also not working

Body:
Well, you face challenges to test both functions, then, what you need is to refactor the code. Because I think, your code is not testable.
I give you this long example, which contain both of your functions but testable.

Changes I made for refactor:

function uploadDoc now will output an array.

function toSave now will require 1 parameter, which is an array.

combine functions into class.

const sinon = require('sinon');
const { expect } = require('chai');

const Doc = {
  /**
   * @return array of file location.
   */
  uploadDoc: () => {
    const sample = [];
    sample.push('fileLocation');
    return sample;
  },

  /**
   * @param array samples
   * @return void
   */
  toSave: (samples) => {
    samples.forEach(() => {
      // Some process read and access doc.
    })
  },
}

/**
 * This is for example purposes.
 * @return void.
 */
function integrationBothFunction () {
  const samples = Doc.uploadDoc();
  Doc.toSave(samples);
}

describe('Unit Test', function () {
  it('uploadDoc fn', function () {
    const result = Doc.uploadDoc();
    // You expect the result to be an array.
    expect(result).to.be.an('array');
  });
  it('toSave fn', function () {
    const samples = [];
    const spySamples = sinon.spy(samples, 'forEach');
    // Call the function
    Doc.toSave(samples);
    // You expect: there is forEach called for samples.
    expect(spySamples.calledOnce).to.equal(true);
    // Do not forget to restore.
    spySamples.restore();
  });

  it('integrationBothFunction fn', function () {
    // This is just sample to check.
    const testSample = ['x'];
    // Now finally, you can stub uploadDoc.
    // Where real uploadDoc function not get called.
    const stubUploadDoc = sinon.stub(Doc, 'uploadDoc');
    stubUploadDoc.returns(testSample);

    // Spy on toSave fn.
    const spyToSave = sinon.spy(Doc, 'toSave');

    integrationBothFunction();

    // You expect that toSave is processing output from uploadDoc.
    expect(stubUploadDoc.calledOnce).to.equal(true);
    expect(spyToSave.calledOnce).to.equal(true);
    // Check argument toSave.
    const { args } = spyToSave;
    expect(args).to.have.lengthOf(1);
    expect(args[0]).to.have.lengthOf(1);
    expect(args[0][0]).to.include(testSample[0]);
    // Restore spy and stub.
    stubUploadDoc.restore();
    spyToSave.restore();
  });
});

I you run using mocha:

$ npx mocha stackoverflow.js

  Unit Test
    ✓ uploadDoc fn
    ✓ toSave fn
    ✓ integrationBothFunction fn

  3 passing (13ms)
$

Hope this helps. Good luck!


问:
How can I enable CSS Modules in React 16.13.1?
everyone! I'm trying to watch tutorials and read articles on how to enable CSS Modules in React 16.13.1. I understand that to do this, I must run "npm run eject", which I have done. Next, I know that I have to edit the "webpack.config.js" file. However, my webpack.config.js file looks very different than those online. A snippet of my webpack.config.js file is below, so what lines must I add and where to enable CSS Modules? If you need more info, please let me know.</p>

```<code>test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
  importLoaders: 1,
  sourceMap: isEnvProduction && shouldUseSourceMap,
}),
</code>```

答: Name your file styles.module.css works in CRA</p>

Body:
everyone! I'm trying to watch tutorials and read articles on how to enable CSS Modules in React 16.13.1. I understand that to do this, I must run "npm run eject", which I have done. Next, I know that I have to edit the "webpack.config.js" file. However, my webpack.config.js file looks very different than those online. A snippet of my webpack.config.js file is below, so what lines must I add and where to enable CSS Modules? If you need more info, please let me know.

test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
  importLoaders: 1,
  sourceMap: isEnvProduction && shouldUseSourceMap,
}),


问:
BigQuery Clustered Tables: How to Create Multiple Clusters
My BigQuery table is commonly queried with different combinations of "where" conditions across 1 or more common columns, say across columns A, B, C (not in order). Hence, I would like to add individual clusters for columns A, B, and C respectively.

How can I create multiple clusters for BigQuery tables? (Similar to how multiple indexes can be created on a traditional rdbms table)

答:
Upon viewing some comments and pages it appears that there are no ways to have multiple independent clusters (vs how multiple indexes can be created on a traditional rdbms) on a single bigquery table.

This is because clusters pretty much just sort the data blocks of that table as per docs:

When data is written to a clustered table by a query job or a load job, BigQuery sorts the data using the values in the clustering columns. These values are used to organize the data into multiple blocks in BigQuery storage. When you submit a query that contains a clause that filters data based on the clustering columns, BigQuery uses the sorted blocks to eliminate scans of unnecessary data.

Hence, it appears that there is no way of applying multiple sorting logic for each independent cluster on the same set of data, and so what I require appears to be impossible as of now.


问:
Is it accurate to say JavaScript is a "single-thread" language?
I've heard this kind of statements many times, but personally I think this doesn't quite make sense.  I think people are confusing JavaScript as a language specification and JavaScript in practice (browser, Node, etc.).  Of course in most cases JavaScript are executed in a single-thread environment; but AFAIK nothing in the language specification requires it to be so.  I think this is just like saying Python is "interpreted", while it's in fact entirely a matter of implementation.

So, is it accurate to say JavaScript is a "single-thread" language?

答:
AFAIK nothing in the language specification requires it to be so.

In TC39 it says:

At any point in time, there is at most one execution context per agent that is actually executing code.

That appears to me to be the crucial guarantee that you never have to synchronize access to variables in ECMAScript. Which is what I expect is meant when someone says a language is single-threaded.

Of course, most ECMAScript host environments use more than one thread in their host environment implementation for things like garbage collection, etc. And, ECMAScript itself allows for multiple separate contexts of execution that could each be driven by their own thread--though the standard makes it clear you could also just drive all of them with the same thread.

The point, again, is you never have to protect any ECMAScript variable with a mutex, semaphore, or the like (which is why ECMAScript provides no such facilities) since the language promises there will never be two threads of control with simultaneous access to the same context.

I don't know of any JavaScript implementation that violates this promise either, though there certainly could be.


问:
Save Dataset to SQLite format file
I have a dataset with multiple tables.
I can obviously do a Dataset.WriteToXML("Somefile.xml")

What if I want to export the dataset to a SQLite formatted file.

In other words I want to be able to write (i.e. serialize) the contents of the dataset to a SQLite file.   Dataset.SerializeToSQLite("Sqliteformatted.bin")

Similarly I want to be able to read the SQLite file into a Dataset.

I would like to do this in c#.

Thanks in advance to any pointers.

Bob

答:
This example may answer your question.

```<code>using System;
using System.Data;
using System.Data.SQLite;

namespace DataAdapterExample
    {
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple dataset
            DataTable table = new DataTable("Students");
            table.Columns.Add("name", typeof(string));
            table.Columns.Add("id", typeof(int));
            table.Rows.Add("Bill Jones", 1);
            table.Rows.Add("Laurie Underwood", 2);
            table.Rows.Add("Jeffrey Sampson", 3);
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
            // Save in an SQLite file
            string desktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullPath = desktopPath + "\\class.db";
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fullPath);
            con.Open();
            // Create a table in the database to receive the information from the DataSet
            SQLiteCommand cmd = new SQLiteCommand(con);
            cmd.CommandText = "DROP TABLE IF EXISTS Students";
            cmd.ExecuteNonQuery();
            cmd.CommandText = "CREATE TABLE Students(name text, id integer PRIMARY  KEY)";
            cmd.ExecuteNonQuery();
            SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from Students", con);
            adaptor.InsertCommand = new SQLiteCommand("INSERT INTO Students  VALUES(:name, :id)", con);
            adaptor.InsertCommand.Parameters.Add("name", DbType.String, 0, "name");
            adaptor.InsertCommand.Parameters.Add("id", DbType.Int32, 0, "id");
            adaptor.Update(ds, "Students");
            // Check database by filling the dataset in the other direction and displaying
            ds = new DataSet();
            adaptor.Fill(ds, "Students");
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("Table {0}", dt.TableName);
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        Console.Write("{0,-18}", dr[dc]);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
</code>```

You can find a very similar example in the SQLiteDataAdapter Class documentation.

ContentLicense: CC BY-SA 2.5

Title: Save Dataset to SQLite format file

Body:
This example may answer your question.

using System;
using System.Data;
using System.Data.SQLite;

namespace DataAdapterExample
    {
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple dataset
            DataTable table = new DataTable("Students");
            table.Columns.Add("name", typeof(string));
            table.Columns.Add("id", typeof(int));
            table.Rows.Add("Bill Jones", 1);
            table.Rows.Add("Laurie Underwood", 2);
            table.Rows.Add("Jeffrey Sampson", 3);
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
            // Save in an SQLite file
            string desktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullPath = desktopPath + "\\class.db";
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fullPath);
            con.Open();
            // Create a table in the database to receive the information from the DataSet
            SQLiteCommand cmd = new SQLiteCommand(con);
            cmd.CommandText = "DROP TABLE IF EXISTS Students";
            cmd.ExecuteNonQuery();
            cmd.CommandText = "CREATE TABLE Students(name text, id integer PRIMARY  KEY)";
            cmd.ExecuteNonQuery();
            SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from Students", con);
            adaptor.InsertCommand = new SQLiteCommand("INSERT INTO Students  VALUES(:name, :id)", con);
            adaptor.InsertCommand.Parameters.Add("name", DbType.String, 0, "name");
            adaptor.InsertCommand.Parameters.Add("id", DbType.Int32, 0, "id");
            adaptor.Update(ds, "Students");
            // Check database by filling the dataset in the other direction and displaying
            ds = new DataSet();
            adaptor.Fill(ds, "Students");
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("Table {0}", dt.TableName);
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        Console.Write("{0,-18}", dr[dc]);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}

You can find a very similar example in the SQLiteDataAdapter Class documentation.


问:
Running into java.lang.NullPointerException Here
I am quite new to programming, at least on the level that I am currently attempting. I've been creating a character class for use in a 2D fighting game engine that will hold a BufferedImage arraylist of frames of character animation. Everything in the program compiles and runs fine, except that I keep running into a NullPointerException in the following code:

```<code>    public void addImage(String image) throws IOException
  {
    this.character.add(ImageIO.read(new File(image)));
  }
</code>```

I am not sure exactly how to fix this, as my low level of general Java knowledge (I only have 1 2 semester high school class by a shoddy teacher under my belt) prevents me from correctly understanding the descriptions on how to fix the problem on various websites. Could somebody describe how to solve this in a clean and concise way? Thank you!

答: NullPointerException is thrown when you try to pass an object ref that has a null value.. I would look to make sure the file you are passing it actually getting read.. try breaking it down then consolidating more after it is functional.. maybe store your file in a variable firs then add that.. if it works then go with it, if it doesn't and you still get the null, look to your new File</p>

Body:
I am quite new to programming, at least on the level that I am currently attempting. I've been creating a character class for use in a 2D fighting game engine that will hold a BufferedImage arraylist of frames of character animation. Everything in the program compiles and runs fine, except that I keep running into a NullPointerException in the following code:

    public void addImage(String image) throws IOException
  {
    this.character.add(ImageIO.read(new File(image)));
  }

I am not sure exactly how to fix this, as my low level of general Java knowledge (I only have 1 2 semester high school class by a shoddy teacher under my belt) prevents me from correctly understanding the descriptions on how to fix the problem on various websites. Could somebody describe how to solve this in a clean and concise way? Thank you!


问:
Flutter Launcher icon not getting changed?
Am new to Flutter. I gone through the flutter documentation and followed the steps to configure custom launcher icons for my flutter project but app Launcher icon is not getting changed? Not sure what am missing.

Code:

```<code>dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons: "^0.7.0"

flutter_icons:
  image_path: "icon/icon.png"
  android: true
  ios: true
</code>```

答:
I wasn't using flutter_launcher_icons, I was using just Image Asset Studio in the Android project. It seemed that in certain situations it wasn't updating my Adaptive Icon on Android.

To fix it, I opened the Android module (right click on the android/ folder in the Flutter view, then select Flutter | Open Android Module in Android Studio). From there, open the res/ folder and delete everything that looks like foreground.xml. AFAICT this is what is generated by Image Asset Studio as part of the Adaptive Icon.

Then recreate the Adaptive Icon via Image Asset Studio.

At this point my Flutter cache was corrupted, so I had to run flutter pub cache repair (I mention this because maybe somehow that is what fixed it, but I doubt it). Run the app and then voila, the icon updated.

Body:
Am new to Flutter. I gone through the flutter documentation and followed the steps to configure custom launcher icons for my flutter project but app Launcher icon is not getting changed? Not sure what am missing.

Code:

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons: "^0.7.0"

flutter_icons:
  image_path: "icon/icon.png"
  android: true
  ios: true


问:
Why `copy constructor` is used while `move constructor` has been removed?
As the subject,the related code is:

```<code>#include <iostream>

class ABC
{  public:
    ABC()
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(const ABC& a)
    {
        std::cout << "copy construction" << std::endl;
    }

    ABC(const ABC&& a)
    {
        std::cout << "move construction" << std::endl;
    }
};

int main()
{
   ABC c1 = ABC();

   return 0;
}
</code>```

Output with -fno-elide-constructors -std=c++11

```<code>default construction
move construction
</code>```

If i remove the move constructor above, then the output is:

```<code>default construction
copy construction
</code>```

why copy construction could be used while move constructor has been removed?You see, if there is a user defined move constructor, the compiler prefer to use move constructor.

As per some documentation,compiler provides a default move constructor.**So why don't the compiler use the default move constructor?
I am a novice in C++.I would be grateful to have some help with this question.

答:
As per some documentation,compiler provides a default move constructor.

Let's take a look at some documentation. The following is from cppreference.com.

If [conditions] then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).

You're right. The compiler does provide a defualt move constructor under the right conditions. However, those conditions are important. The first condition you seem to be aware of: there cannot be a user-defined move constructor. So that just leaves this list of conditions:

there are no user-declared copy constructors;

there are no user-declared copy assignment operators;

there are no user-declared move assignment operators;

there is no user-declared destructor;

And there you go. Your user-defined copy constructor is preventing the compiler from providing a default move constructor. Hence there is no move constructor to use.

Body:
As the subject,the related code is:

#include <iostream>

class ABC
{  public:
    ABC()
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(const ABC& a)
    {
        std::cout << "copy construction" << std::endl;
    }

    ABC(const ABC&& a)
    {
        std::cout << "move construction" << std::endl;
    }
};

int main()
{
   ABC c1 = ABC();

   return 0;
}

Output with -fno-elide-constructors -std=c++11

default construction
move construction

If i remove the move constructor above, then the output is:

default construction
copy construction

why copy construction could be used while move constructor has been removed?You see, if there is a user defined move constructor, the compiler prefer to use move constructor.

As per some documentation,compiler provides a default move constructor.**So why don't the compiler use the default move constructor?
I am a novice in C++.I would be grateful to have some help with this question.


问:
Nmap giving an error message "You are running a deprecated option"
I am currently making a golang program which is supposed to be able to run but for some reason even though I enter the same options which work (eg. -oN test.txt) in the cmd, it doesn't run and gives me this error message This is odd because in the command line that line works but the moment I try to run it in my program it doesn't.

The source code is here:

```<code>package main

import (
    "os/exec"
    "os"
    "fmt"
    "strings"
)
func main(){

    fmt.Println("Please enter which scanner tool you wish to use:")
    fmt.Println("nmap for nmap")

    var toolargs []string
    var ipaddress string
    var toolchoice string

    fmt.Scanln(&toolchoice)

    if toolchoice == "nmap" {
        toolargs = nmap()
        fmt.Println(toolargs)
    }else{
        fmt.Println("invalid input")
    }

    fmt.Println("Please enter the IP address you wish to scan:")
    fmt.Scanln(&ipaddress)

    fmt.Println(toolchoice)
    fmt.Println(toolargs)
    fmt.Println(ipaddress)

    funccmd(toolchoice, toolargs, ipaddress)

    fmt.Scanln()

}

func nmap() []string{
    var NoOfArgs int
    var args1 string
    var args2 string
    var args3 string
    var args4 string
    var args5 string
    var args []string
    fmt.Println("Please enter a number for how many arguments you wish to use:")
    fmt.Scanln(&NoOfArgs)

    switch NoOfArgs{
    case 1:
            fmt.Println("Please enter your argument")
        fmt.Scanf("%s", &args1)
        args = []string{args1}
    case 2:
            fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s", &args1, &args2)
        fmt.Println(args1)
        fmt.Println(args2)
        args = []string{args1, args2}
        fmt.Println(args)

        case 3:
            fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s %s", &args1, &args2, &args3)
        args = []string{args1, args2, args3}
    case 4:
        fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s %s %s", &args1, &args2, &args3, &args4)
        args = []string{args1, args2, args3, args4}
    case 5:
        fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s %s %s %s", &args1, &args2, &args3, &args4, &args5)
        args = []string{args1, args2, args3, args4, args5}
        }
    fmt.Println(args)
    return args
}

func funccmd(toolchoice string, args []string, ipaddress string){
    execpath, _ := exec.LookPath("/usr/bin/nmap")

    stringargs := strings.Join(args, " ")
    fmt.Println(stringargs)
    final := []string{execpath, stringargs, ipaddress}
    fmt.Println(final)
    cmdNmap := &exec.Cmd{
       Path: execpath,
       Args: []string{execpath, stringargs, ipaddress},
       Stdout: os.Stdout,
       Stderr: os.Stdout,
    }
    fmt.Println(args)
    if err := cmdNmap.Run(); err !=nil{
       fmt.Println("Error", err);
    }
}
</code>```

答: The problem is that you are joining the arguments together into a single string (stringargs) before passing them to exec.Cmd. They need to each be a separate argument in the Args array. Nmap is seeing the first arguments as "-oN results.txt" and parsing that as the deprecated option "-o" and the file name "N results.txt". The warning is precisely to prevent this kind of error, since you most likely do not mean to create an output file with the name "N results.txt".

Body:
I am currently making a golang program which is supposed to be able to run but for some reason even though I enter the same options which work (eg. -oN test.txt) in the cmd, it doesn't run and gives me this error message This is odd because in the command line that line works but the moment I try to run it in my program it doesn't.

The source code is here:

package main

import (
    "os/exec"
    "os"
    "fmt"
    "strings"
)
func main(){

    fmt.Println("Please enter which scanner tool you wish to use:")
    fmt.Println("nmap for nmap")

    var toolargs []string
    var ipaddress string
    var toolchoice string

    fmt.Scanln(&toolchoice)

    if toolchoice == "nmap" {
        toolargs = nmap()
        fmt.Println(toolargs)
    }else{
        fmt.Println("invalid input")
    }

    fmt.Println("Please enter the IP address you wish to scan:")
    fmt.Scanln(&ipaddress)

    fmt.Println(toolchoice)
    fmt.Println(toolargs)
    fmt.Println(ipaddress)

    funccmd(toolchoice, toolargs, ipaddress)

    fmt.Scanln()

}

func nmap() []string{
    var NoOfArgs int
    var args1 string
    var args2 string
    var args3 string
    var args4 string
    var args5 string
    var args []string
    fmt.Println("Please enter a number for how many arguments you wish to use:")
    fmt.Scanln(&NoOfArgs)

    switch NoOfArgs{
    case 1:
            fmt.Println("Please enter your argument")
        fmt.Scanf("%s", &args1)
        args = []string{args1}
    case 2:
            fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s", &args1, &args2)
        fmt.Println(args1)
        fmt.Println(args2)
        args = []string{args1, args2}
        fmt.Println(args)

        case 3:
            fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s %s", &args1, &args2, &args3)
        args = []string{args1, args2, args3}
    case 4:
        fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s %s %s", &args1, &args2, &args3, &args4)
        args = []string{args1, args2, args3, args4}
    case 5:
        fmt.Println("Please enter your arguments, separated with a blank space between arguments (eg. -sn -sS -O)")
        fmt.Scanf("%s %s %s %s %s", &args1, &args2, &args3, &args4, &args5)
        args = []string{args1, args2, args3, args4, args5}
        }
    fmt.Println(args)
    return args
}

func funccmd(toolchoice string, args []string, ipaddress string){
    execpath, _ := exec.LookPath("/usr/bin/nmap")

    stringargs := strings.Join(args, " ")
    fmt.Println(stringargs)
    final := []string{execpath, stringargs, ipaddress}
    fmt.Println(final)
    cmdNmap := &exec.Cmd{
       Path: execpath,
       Args: []string{execpath, stringargs, ipaddress},
       Stdout: os.Stdout,
       Stderr: os.Stdout,
    }
    fmt.Println(args)
    if err := cmdNmap.Run(); err !=nil{
       fmt.Println("Error", err);
    }
}


问:
First time creating a website with Flask, I keep coming up with 'Error: No such command 'init-db' when creating a database
I'm following this tutorial, but have still managed to mess it up. Go figure.

Done everything up to the third page where we create the database. I know init-db is the correct format, I have installed flask within the venv,  and I have no idea where I went wrong.
Edit: I have done the exports
db.py

```<code>import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as f:
        db.executescript(f.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    #clear the existing data and create new tables
    init_db()
    click.echo('Initialized the database.')

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)
</code>```

init.py

```<code>import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/hello')
    def hello():
        return 'Hello World'

    from . import db
    db.init_app(app)

    return app
</code>```

and schema.sql

```<code>DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS post;

CREATE TABLE user (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL
);

CREATE TABLE post (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    author_id INTEGER NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    FOREIGN KEY (author_id) REFERENCES user (id)
);
</code>```

complete error code:

(venv) root@pi:/home/pi/flaskr# flask init-db

Usage: flask [OPTIONS] COMMAND [ARGS]...

Try 'flask --help' for help.

Error: No such command 'init-db'.

答: So.. This took a while for me to recreate, however I have figured it out.  You are in the wrong directory in your terminal.  flask init-db needs to be ran from pi not flaskr... this is assuming that your venv environment is in pi.  </p>

Body:
I'm following this tutorial, but have still managed to mess it up. Go figure.

Done everything up to the third page where we create the database. I know init-db is the correct format, I have installed flask within the venv,  and I have no idea where I went wrong.
Edit: I have done the exports
db.py

import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as f:
        db.executescript(f.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    #clear the existing data and create new tables
    init_db()
    click.echo('Initialized the database.')

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

init.py

import os
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/hello')
    def hello():
        return 'Hello World'

    from . import db
    db.init_app(app)

    return app

and schema.sql

DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS post;

CREATE TABLE user (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL
);

CREATE TABLE post (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    author_id INTEGER NOT NULL,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    FOREIGN KEY (author_id) REFERENCES user (id)
);

complete error code:

(venv) root@pi:/home/pi/flaskr# flask init-db

Usage: flask [OPTIONS] COMMAND [ARGS]...

Try 'flask --help' for help.

Error: No such command 'init-db'.