问:
UI5 TileContainer is blank in Chrome
I am using SAPUI5 with HANA DB to create a custom dashboard.

I need to add a CustomTile (with different layout and content) in the onInit function of my controller by the below code. It works perfectly fine in Firefox. But in Chrome, the tile is simply not shown and I also can't find it within the HTML elements:

onInit: function() {
  var oTileContainer = this.getView().byId("tileContainer");
  var quantTile = new sap.m.CustomTile({/* Some content ... */});
  oTileContainer.insertTile(quantTile, 0);
},
```
<p>For completeness, here is the relevant part of my XML view:</p>
<pre class="lang-xml prettyprint-override"><code><TileContainer id="tileContainer" tiles="{/TileCollection}">
  <CustomTile>
    <!-- Some content ... -->
  </CustomTile>
</TileContainer>
</code>```

Does anyone have any idea why it might not be shown/rendered within Chrome, but in Firefox? Is there any procedure that I can call that forces a re-render or something similar?

Thanks

答:
Maybe Chrome is mixing up the binding with the fixed tile.

You could create a local JSON model with the data from your hana service AND your fixed tile and then bind your tile container with your local service.

Title: UI5 TileContainer is blank in Chrome

Body:
I am using SAPUI5 with HANA DB to create a custom dashboard.

I need to add a CustomTile (with different layout and content) in the onInit function of my controller by the below code. It works perfectly fine in Firefox. But in Chrome, the tile is simply not shown and I also can't find it within the HTML elements:

onInit: function() {
  var oTileContainer = this.getView().byId("tileContainer");
  var quantTile = new sap.m.CustomTile({/* Some content ... */});
  oTileContainer.insertTile(quantTile, 0);
},

For completeness, here is the relevant part of my XML view:

<TileContainer id="tileContainer" tiles="{/TileCollection}">
  <CustomTile>

  </CustomTile>
</TileContainer>

Does anyone have any idea why it might not be shown/rendered within Chrome, but in Firefox? Is there any procedure that I can call that forces a re-render or something similar?

Thanks


来源: stackexchange

问:
Skip entity based on a certain attribute
I am trying to skip an entity. I tried to do so by returning undefined from idAttribute function however it won't skip. Is this possible?

```<code>var { schema, normalize } = require("normalizr")

// Define your article
const article = new schema.Entity('articles', undefined, {
  idAttribute: value => value.id
});

const reply = {
  articles: [ { id:1, commenter:'foo' }, { id:2, commenter:'bar' }, { dummy:true } ]
}

const normalizedData = normalize(reply, { articles: [ article ] });

console.log('normalizedData.entities:', JSON.stringify(normalizedData.entities));
</code>```

This gives us the data, normalizedData.entities of:

```<code>articles: {
  1: {commenter: "foo", id: 1}
  2: {commenter: "bar", id: 2}
  undefined: {dummy: true}
}
</code>```

However I want to skip any entries that don't have the key id to not be there. This is a very simplified case of my actual case.

答: Normalizr does not include complexities for your specific case. You will have to filter those out as another step after the normalization process. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to skip an entity. I tried to do so by returning undefined from idAttribute function however it won't skip. Is this possible?

var { schema, normalize } = require("normalizr")

// Define your article
const article = new schema.Entity('articles', undefined, {
  idAttribute: value => value.id
});

const reply = {
  articles: [ { id:1, commenter:'foo' }, { id:2, commenter:'bar' }, { dummy:true } ]
}

const normalizedData = normalize(reply, { articles: [ article ] });

console.log('normalizedData.entities:', JSON.stringify(normalizedData.entities));

This gives us the data, normalizedData.entities of:

articles: {
  1: {commenter: "foo", id: 1}
  2: {commenter: "bar", id: 2}
  undefined: {dummy: true}
}

However I want to skip any entries that don't have the key id to not be there. This is a very simplified case of my actual case.


问:
How can I tell pytest-dependency to temporarily ignore test dependencies?
I've got a functional test suite using pytest-dependency to skip tests when other tests they depend on fail. That way, for example, if the login page is broken, I get one test failure saying "The login page is broken" instead of a slew of test failures saying "I couldn't log into user X", "I couldn't log into user Y", etc.

This works great for running the entire suite, but I'm trying to shorten my edit-compile-test loop, and right now the slowest point is testing my tests. If the test I'm working on has a bunch of other tests it depends on, they all have to succeed in order to not skip the test I'm trying to test. So, I either have to run the entire dependency tree, or comment out my @pytest.mark.dependency(...) decorators (which is an additional thing that I, as a human, have to remember to do). Technically there's nothing these depended-on tests do that enables their dependers to run - the only reason I want these dependencies at all is to make it easier for me to triage test failures.

Is there a command-line argument that would tell pytest-dependency to not skip things on account of dependents, or to tell pytest to not use the pytest-dependency plugin on this run (and this run only)?

答:
The -p option allows disabling a particular plugin:

```<code>pytest -p no:dependency
</code>```

Body:
The -p option allows disabling a particular plugin:

pytest -p no:dependency


问:
Jenkins slave jobs failing on "Unexpected termination of channel"
I am currently seeing a set of errors across my builds.

Is this expected behaviour if you loose Jenkins (say to a box crash, or a kill -9)?

Or is there something worse going on (like a bad network connection)?

The stack and error is:

```<code>hudson.remoting.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:158)
        at $Proxy175.join(Unknown Source)   at
hudson.Launcher$RemoteLauncher$ProcImpl.join(Launcher.java:861)     at
hudson.Launcher$ProcStarter.join(Launcher.java:345)     at
hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:82)
        at
hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:58)
        at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:19)
        at
hudson.model.AbstractBuild$AbstractRunner.perform(AbstractBuild.java:703)
        at hudson.model.Build$RunnerImpl.build(Build.java:178)  at
hudson.model.Build$RunnerImpl.doRun(Build.java:139)     at
hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:473)
        at hudson.model.Run.run(Run.java:1410)  at
hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)     at
hudson.model.ResourceController.execute(ResourceController.java:88)
        at hudson.model.Executor.run(Executor.java:238) Caused by:
hudson.remoting.RequestAbortedException: java.io.IOException:
Unexpected termination of the channel   at
hudson.remoting.Request.abort(Request.java:273)     at
hudson.remoting.Channel.terminate(Channel.java:732)     at
hudson.remoting.Channel$ReaderThread.run(Channel.java:1157) Caused by:
java.io.IOException: Unexpected termination of the channel  at
hudson.remoting.Channel$ReaderThread.run(Channel.java:1133) Caused by:
java.io.EOFException    at
java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2554)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1297)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
        at hudson.remoting.Channel$ReaderThread.run(Channel.java:1127)
</code>```

答:
On CentOS Linux 7, I found that the Jenkins slave doesn't work with OpenJDK. I tried Java 7 and 8. It requires Oracle Java.

So, if you're on Linux, install Oracle Java, and set the path to point to it. You can do this in a number of ways, e.g.:

Set $JAVA_HOME for the user you're launching the slave as, and add it to $PATH.

Use update-alternatives to set the default java.

Set JavaPath, under the node's Advanced settings in Jenkins.

Body:
I am currently seeing a set of errors across my builds.

Is this expected behaviour if you loose Jenkins (say to a box crash, or a kill -9)?

Or is there something worse going on (like a bad network connection)?

The stack and error is:

hudson.remoting.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:158)
        at $Proxy175.join(Unknown Source)   at
hudson.Launcher$RemoteLauncher$ProcImpl.join(Launcher.java:861)     at
hudson.Launcher$ProcStarter.join(Launcher.java:345)     at
hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:82)
        at
hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:58)
        at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:19)
        at
hudson.model.AbstractBuild$AbstractRunner.perform(AbstractBuild.java:703)
        at hudson.model.Build$RunnerImpl.build(Build.java:178)  at
hudson.model.Build$RunnerImpl.doRun(Build.java:139)     at
hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:473)
        at hudson.model.Run.run(Run.java:1410)  at
hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)     at
hudson.model.ResourceController.execute(ResourceController.java:88)
        at hudson.model.Executor.run(Executor.java:238) Caused by:
hudson.remoting.RequestAbortedException: java.io.IOException:
Unexpected termination of the channel   at
hudson.remoting.Request.abort(Request.java:273)     at
hudson.remoting.Channel.terminate(Channel.java:732)     at
hudson.remoting.Channel$ReaderThread.run(Channel.java:1157) Caused by:
java.io.IOException: Unexpected termination of the channel  at
hudson.remoting.Channel$ReaderThread.run(Channel.java:1133) Caused by:
java.io.EOFException    at
java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2554)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1297)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
        at hudson.remoting.Channel$ReaderThread.run(Channel.java:1127)


问:
What is best practice for running multiple Docker containers with code from different repos?
I have a web app that consists of multiple services (including a postgres db and redis), in multiple repos. Ideally I'd like to have all the Docker stuff in one repo, and build from there. However, I'm running into trouble since building the containers involves compiling code in other directories (or repositories), and you can't ADD from a different directory. Symlinking doesn't work either. And I don't want to pull from github into a container to avoid having ssh keys in the wild. Is there a way to accomplish what I'm trying to do? Or does each repo need its own Dockerfile?

答:
Assuming that you have two directories parent/project1 and parent/project2, and have Dockerfile is at parent/project1/.

You can ADD both directories into a container.
If you are at parent/

```<code>$ docker build -f project1/Dockerfile .
</code>```

Dockerfile is something like following.

```<code>ADD project1 /path/to/directory1
ADD project2 /path/to/directory2
</code>```

Body:
Assuming that you have two directories parent/project1 and parent/project2, and have Dockerfile is at parent/project1/.

You can ADD both directories into a container.
If you are at parent/

$ docker build -f project1/Dockerfile .

Dockerfile is something like following.

ADD project1 /path/to/directory1
ADD project2 /path/to/directory2


问:
jQuery Validate - can I re-validate a group of fields after changing one?
I'm using jQuery Validate and would like to re-validate a group of fields whenever one of them is changed (or possibly, whenever one of them validates successfully). My attempts so far just create infinite loops.

Is this possible, or does the plugin design preclude it?

(Specifically, I've got a method that requires at least X of group Y to be filled out, and as soon as that's true, I'd like all those fields to re-validate. Currently I'm clearing out their error messages with my own code, but that's a hack - it also hides unrelated validation problems until the form is re-submitted.)

答:
Dont know how this worked but, just found that removing the below part:

```<code>if(!$(element).data('reval')) {
        var fields = $(options[1], element.form);
        fields.data('reval', true).valid();
        fields.data('reval', false);
}
</code>```

of code from the main code make all the validations to work as normal and expected. :)

ContentLicense: CC BY-SA 2.5

Body:
Dont know how this worked but, just found that removing the below part:

if(!$(element).data('reval')) {
        var fields = $(options[1], element.form);
        fields.data('reval', true).valid();
        fields.data('reval', false);
}

of code from the main code make all the validations to work as normal and expected. :)


问:
PlaybackNearlyFinished and PlaybackFinished occur almost at the same time?
It turns out, that sometimes (not always btw but very frequently) PlaybackNearlyFinished and PlaybackFinished occur almost at the same time. What also confuses is that both of the events convey exactly the same offset that represents the very end of the stream:

When this happens the next stream scheduled in PlaybackNearlyFinished does not go - the playback just finishes.

Unless this is a bug in Alexa/Infrastructure, I can not figure out how to implement a playback for a playlist - there's just no way to reliably schedule the upcoming track...

Is there anything I could do in my code to make it work well?

I am using Echo Dot 2 gen., physically located in Europe, use java SDK, AWS Lambda, Dynamo DB.

答:
Looks like it is figured out now - in order to queue the next stream properly one needs to come up with really unique stream tokens. This means that even the same file/url should be enqueued under a unique token.

In my example above, I used the index of the track in the playlist as an token. Once I solved it like below, everything started to work like a charm:

```<code>import org.apache.commons.lang3.RandomStringUtils;

public class TokenService {

    public String createToken(int playbackPosition) {
        String suffix = RandomStringUtils.randomAlphanumeric(16);
        return String.valueOf(playbackPosition) + ":" + suffix;
    }

    public int tokenToPlaybackIndex(String token) {
        String positionStr = token.split(":")[0];
        return Integer.valueOf(positionStr);
    }
}
</code>```

Hope it helps somebody!

Body:
Looks like it is figured out now - in order to queue the next stream properly one needs to come up with really unique stream tokens. This means that even the same file/url should be enqueued under a unique token.

In my example above, I used the index of the track in the playlist as an token. Once I solved it like below, everything started to work like a charm:

import org.apache.commons.lang3.RandomStringUtils;

public class TokenService {

    public String createToken(int playbackPosition) {
        String suffix = RandomStringUtils.randomAlphanumeric(16);
        return String.valueOf(playbackPosition) + ":" + suffix;
    }

    public int tokenToPlaybackIndex(String token) {
        String positionStr = token.split(":")[0];
        return Integer.valueOf(positionStr);
    }
}

Hope it helps somebody!


问:
Error with "null" in description when trying to Ping from vbscript
Why doesn't it work?

```<code>Dim HTTPobj

Set HTTPobj = CreateObject("Microsoft.XMLHTTP")

iPing = Ping("www.google.com")

If iPing=0 Then
    Call HTTPobj.Open("GET","www.example.com/command.php")
    Call HTTPobj.Send
    CreateObject("Scripting.FileSystemObject").CreateTextFile("vbs.vbs",True).Write(HTTPobj.ResponseText)
    WScript.CreateObject("Wscript.Shell").Run "vbs.vbs" , 0

End If

Function Ping (strTarget)
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set colPings = objWMIService.ExecQuery ("Select * From Win32_PingStatus where Address = '" & strTarget & "'")

    For Each objPing in colPings
        Ping = objPing.StatusCode
    Next
End Function
</code>```

It returns an error with (null) in description, line 8, character 2. It is a Call function, but I don't understand why it doesn't work.

答:
Try to put http:// in the url:

```<code>   Call HTTPobj.Open("GET","http://www.url.com/command.php")
</code>```

Then, set the HTTPobj to:

```<code> Set HTTPobj = CreateObject("MSXML2.ServerXMLHTTP.6.0")
</code>```

For me it worked.

Body:
Why doesn't it work?

Dim HTTPobj

Set HTTPobj = CreateObject("Microsoft.XMLHTTP")

iPing = Ping("www.google.com")

If iPing=0 Then
    Call HTTPobj.Open("GET","www.example.com/command.php")
    Call HTTPobj.Send
    CreateObject("Scripting.FileSystemObject").CreateTextFile("vbs.vbs",True).Write(HTTPobj.ResponseText)
    WScript.CreateObject("Wscript.Shell").Run "vbs.vbs" , 0

End If

Function Ping (strTarget)
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    Set colPings = objWMIService.ExecQuery ("Select * From Win32_PingStatus where Address = '" & strTarget & "'")

    For Each objPing in colPings
        Ping = objPing.StatusCode
    Next
End Function

It returns an error with (null) in description, line 8, character 2. It is a Call function, but I don't understand why it doesn't work.

Body:
Try to put http:// in the url:

   Call HTTPobj.Open("GET","http://www.url.com/command.php")

Then, set the HTTPobj to:

 Set HTTPobj = CreateObject("MSXML2.ServerXMLHTTP.6.0")

For me it worked.


问:
type object 'RadioSelect' has no attribute 'renderer'
I am trying to do a radioselect horizontal align and I am receiving the following error message:type object 'RadioSelect' has no attribute 'renderer'

What I am doing wrong?

```<code>from django.utils.safestring import mark_safe

class HorizontalRadioRenderer(forms.RadioSelect.renderer):
   def render(self):
     return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class ApprovalForm(forms.Form):
     approval = forms.ChoiceField(choices=APPROVAL_CHOICES,
             initial=0,
             widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
                             )
</code>```

答:
you are trying to inherit  forms.RadioSelect.renderer instead forms.RadioSelect. forms.RadioSelect is not instantiated so it doesn't have the attribute. So you are getting attribute error.

```<code>from django.utils.safestring import mark_safe

class HorizontalRadioRenderer(forms.RadioSelect):
   def render(self):
     return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class ApprovalForm(forms.Form):
     approval = forms.ChoiceField(
            choices=APPROVAL_CHOICES,
            initial=0,
           widget=forms.RadioSelect(
                 renderer=HorizontalRadioRenderer
           ),
         )
</code>```

Body:
I am trying to do a radioselect horizontal align and I am receiving the following error message:type object 'RadioSelect' has no attribute 'renderer'

What I am doing wrong?

from django.utils.safestring import mark_safe

class HorizontalRadioRenderer(forms.RadioSelect.renderer):
   def render(self):
     return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class ApprovalForm(forms.Form):
     approval = forms.ChoiceField(choices=APPROVAL_CHOICES,
             initial=0,
             widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
                             )

Body:
you are trying to inherit  forms.RadioSelect.renderer instead forms.RadioSelect. forms.RadioSelect is not instantiated so it doesn't have the attribute. So you are getting attribute error.

from django.utils.safestring import mark_safe

class HorizontalRadioRenderer(forms.RadioSelect):
   def render(self):
     return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class ApprovalForm(forms.Form):
     approval = forms.ChoiceField(
            choices=APPROVAL_CHOICES,
            initial=0,
           widget=forms.RadioSelect(
                 renderer=HorizontalRadioRenderer
           ),
         )


问:
Pattern matches by row name with multiple columns in multiple files
I have two files, one with a full list of gene names and three others with partial lists of gene names. I want to match these files all into one. All the partial files are different number of rows but have 3000 columns, all representing different cells. I have been trying to join these files completely but when I use awk only one column is kept.

mergedAll.txt

```<code>GENE
SOX2
BRCA1
BRCA2
RHO
</code>```

ultimatecontrolMed.txt

```<code>GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA2    400     234     73
RHO      12      2       0
</code>```

My Desired output would be

```<code>GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA1    0       0       0
BRCA2    400     234     73
RHO      12      2       0
</code>```

I run:

```<code>awk 'NR==FNR{k[$1];next}{b[$1]=$0;k[$1]}
END{for(x in k)
      if ( x== "GENE" )
         printf"%s %s\n",x,b[x]
      else
         printf"%s  %d\n",x,b[x]
}' mergedAll.txt ultimatecontrolMed.txt > test.txt
</code>```

And I get:

```<code>GENE CELL1 CELL 2 CELL3
SOX2 2000
BRCA1 0
BRCA2 73
RHO 0
</code>```

For some reason it will keep the last column of counts but not any of the other lines, and keep all the cell names. I don't have any experience with awk so this has been a major challenge for me overall and would love it if someone could offer a better solution.

答:
awk to the rescue!

```<code>$ awk 'NR==FNR {a[$1]=$0; next}
               {print (a[$1]?a[$1]:($1 FS 0 FS 0 FS 0))}' file2 file1 |
  column -t

GENE   CELL1  CELL2  CELL3
SOX2   30     152    2000
BRCA1  0      0      0
BRCA2  400    234    73
RHO    12     2      0
</code>```

final pipe to column is for pretty printing.  Note the order of the files.

Not to hard code the number of columns you can try this alternative

```<code>$ awk 'NR==1   {for(i=2;i<=NF;i++) missing=missing FS 0}
       NR==FNR {a[$1]=$0; next}
               {print (a[$1]?a[$1]:($1 missing))}' file2 file1
</code>```

Body:
I have two files, one with a full list of gene names and three others with partial lists of gene names. I want to match these files all into one. All the partial files are different number of rows but have 3000 columns, all representing different cells. I have been trying to join these files completely but when I use awk only one column is kept.

mergedAll.txt

GENE
SOX2
BRCA1
BRCA2
RHO

ultimatecontrolMed.txt

GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA2    400     234     73
RHO      12      2       0

My Desired output would be

GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA1    0       0       0
BRCA2    400     234     73
RHO      12      2       0

I run:

awk 'NR==FNR{k[$1];next}{b[$1]=$0;k[$1]}
END{for(x in k)
      if ( x== "GENE" )
         printf"%s %s\n",x,b[x]
      else
         printf"%s  %d\n",x,b[x]
}' mergedAll.txt ultimatecontrolMed.txt > test.txt

And I get:

GENE CELL1 CELL 2 CELL3
SOX2 2000
BRCA1 0
BRCA2 73
RHO 0

For some reason it will keep the last column of counts but not any of the other lines, and keep all the cell names. I don't have any experience with awk so this has been a major challenge for me overall and would love it if someone could offer a better solution.

Body:
awk to the rescue!

$ awk 'NR==FNR {a[$1]=$0; next}
               {print (a[$1]?a[$1]:($1 FS 0 FS 0 FS 0))}' file2 file1 |
  column -t

GENE   CELL1  CELL2  CELL3
SOX2   30     152    2000
BRCA1  0      0      0
BRCA2  400    234    73
RHO    12     2      0

final pipe to column is for pretty printing.  Note the order of the files.

Not to hard code the number of columns you can try this alternative

$ awk 'NR==1   {for(i=2;i<=NF;i++) missing=missing FS 0}
       NR==FNR {a[$1]=$0; next}
               {print (a[$1]?a[$1]:($1 missing))}' file2 file1


问:
Paramter pack unfolding correctly to initialize a std::array of std::strings
currently i am playing around with parameter packs in c++. I have wrote this little snippet:

```<code>template<typename ...Targs>
auto toString(Targs... args) -> std::array<std::string,sizeof...(Targs)>
{
    return {
              {
                 (std::forward<std::string>(std::to_string(args)),...)
              }
           };
}
</code>```

It has no real purpose but the exercise was/is to create an array of strings from the given parameter which can vary in count and type.

What I hoped to achieve was to do the following:

```<code>std::array<std::string,3> SomeName = { {std::to_string(1),std::to_string(2),std::to_string(3)} };
</code>```

but more generic. That was the idea for the toString function. Unfortunately the result I get is not what I expected. The returned std::array will only contain the last parameter given to toString with the rest of the strings being empty.

But what I actually expected was that each argument given to toString gets converted into an string and put into the element of the array.

What did I miss about parameter pack unfolding? Or do I have just annoyingly stupid mistake?

答:
You have an extra comma:

```<code>(std::forward<std::string>(std::to_string(args)),...)
//                                              ^
</code>```

This now becomes a fold expression over a comma, which is a single expression that gives you one string, where you want N strings. Also, the term isn't unfolding, the term is parameter pack expansion.

Removing the comma gives you what you want:

```<code>return {{std::to_string(args)...}};
</code>```

Note that the std::forward<> is unnecessary - so I removed that too.

Body:
currently i am playing around with parameter packs in c++. I have wrote this little snippet:

template<typename ...Targs>
auto toString(Targs... args) -> std::array<std::string,sizeof...(Targs)>
{
    return {
              {
                 (std::forward<std::string>(std::to_string(args)),...)
              }
           };
}

It has no real purpose but the exercise was/is to create an array of strings from the given parameter which can vary in count and type.

What I hoped to achieve was to do the following:

std::array<std::string,3> SomeName = { {std::to_string(1),std::to_string(2),std::to_string(3)} };

but more generic. That was the idea for the toString function. Unfortunately the result I get is not what I expected. The returned std::array will only contain the last parameter given to toString with the rest of the strings being empty.

But what I actually expected was that each argument given to toString gets converted into an string and put into the element of the array.

What did I miss about parameter pack unfolding? Or do I have just annoyingly stupid mistake?

Body:
You have an extra comma:

(std::forward<std::string>(std::to_string(args)),...)
//                                              ^

This now becomes a fold expression over a comma, which is a single expression that gives you one string, where you want N strings. Also, the term isn't unfolding, the term is parameter pack expansion.

Removing the comma gives you what you want:

return {{std::to_string(args)...}};

Note that the std::forward<> is unnecessary - so I removed that too.


问:
When should public variables be used?
Using the android developer page for ScanResult, https://developer.android.com/reference/android/net/wifi/ScanResult.html, I noticed that they have public variables BSSID, SSID, capabilities, etc. I thought this was weird, as using getters/setters over public variables is the java norm. Is there a broad, rule-based reason why public variables are sometimes used over getters/setters? </p>

答:
Keep variables private by default

Variables that need to be accessed from outside a package should use accessor methods (getters / setters)

Variables used only within a private package can safely be made "public"

Title: When should public variables be used?


问:
How to override updateSegmentRequestInfo for custom receiver?
I do not understand how it works in this context.The function I have used to override is not being called. Instead the default one is used.
Could someone give an example as to how to properly override updateSegmentRequestInfo().

答:
```<code>var host = new cast.player.api.Host({'mediaElement':mediaElement, 'url':url});
host.updateSegmentRequestInfo = function(requestInfo) {
  // example of setting CORS withCredentials
  requestInfo.withCredentials = true;
  // example of setting headers
  requestInfo.headers = {};
  requestInfo.headers['content-type'] = 'text/xml;charset=utf-8';
};
</code>```


问:
How to require non-anonymous user in .Net Core?
In .Net Core, the controller attribute [AllowAnonymous] lets you set a controller to allow non-logged in users to access the controller.

Is there a way to do the opposite, to require a user to be logged in? Without giving all users a role and then checking every single controller with [Authorize(Roles = "WarmBody")], I can't see how to require a login?

答:
You don't need role based authorization, just use the [Authorize] attribute on the controller or actions you want to limit to logged in users.

https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple


问:
How to inflate a file with zlib.NET?
I'm using the zlib.NET library to try and inflate files that are compressed by zlib (on a Linux box, perhaps).  Here's what I'm doing:

```<code>zlib.ZInputStream zinput =
    new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));

while (stopByte != (data = zinput.ReadByte()))
{
  // check data here
}

zinput.Close();
</code>```

The data bytes match the compressed data bytes, so I must be doing something wrong.

答:
The below code could help you guys. Instantiate the object and make use of the functions.</p>

```<code>public class FileCompressionUtility
{
    public FileCompressionUtility()
    {
    }

    public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
    {
        byte[] buffer = new byte[2000];
        int len;
        while ((len = input.Read(buffer, 0, 2000)) > 0)
        {
            output.Write(buffer, 0, len);
        }
        output.Flush();
    }

    public void compressFile(string inFile, string outFile)
    {
        System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
        zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream, zlib.zlibConst.Z_DEFAULT_COMPRESSION);
        System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open);
        try
        {
            CopyStream(inFileStream, outZStream);
        }
        finally
        {
            outZStream.Close();
            outFileStream.Close();
            inFileStream.Close();
        }
    }

    public void uncompressFile(string inFile, string outFile)
    {
        int data = 0;
        int stopByte = -1;
        System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
        zlib.ZInputStream inZStream = new zlib.ZInputStream(System.IO.File.Open(inFile, System.IO.FileMode.Open, System.IO.FileAccess.Read));
        while (stopByte != (data = inZStream.Read()))
        {
            byte _dataByte = (byte)data;
            outFileStream.WriteByte(_dataByte);
        }

        inZStream.Close();
        outFileStream.Close();
    }
}
</code>```

OwnerDisplayName: Ben Collins

Title: How to inflate a file with zlib.NET?

Body:
I'm using the zlib.NET library to try and inflate files that are compressed by zlib (on a Linux box, perhaps).  Here's what I'm doing:

zlib.ZInputStream zinput =
    new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));

while (stopByte != (data = zinput.ReadByte()))
{
  // check data here
}

zinput.Close();

The data bytes match the compressed data bytes, so I must be doing something wrong.

Body:
The below code could help you guys. Instantiate the object and make use of the functions.

public class FileCompressionUtility
{
    public FileCompressionUtility()
    {
    }

    public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
    {
        byte[] buffer = new byte[2000];
        int len;
        while ((len = input.Read(buffer, 0, 2000)) > 0)
        {
            output.Write(buffer, 0, len);
        }
        output.Flush();
    }

    public void compressFile(string inFile, string outFile)
    {
        System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
        zlib.ZOutputStream outZStream = new zlib.ZOutputStream(outFileStream, zlib.zlibConst.Z_DEFAULT_COMPRESSION);
        System.IO.FileStream inFileStream = new System.IO.FileStream(inFile, System.IO.FileMode.Open);
        try
        {
            CopyStream(inFileStream, outZStream);
        }
        finally
        {
            outZStream.Close();
            outFileStream.Close();
            inFileStream.Close();
        }
    }

    public void uncompressFile(string inFile, string outFile)
    {
        int data = 0;
        int stopByte = -1;
        System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
        zlib.ZInputStream inZStream = new zlib.ZInputStream(System.IO.File.Open(inFile, System.IO.FileMode.Open, System.IO.FileAccess.Read));
        while (stopByte != (data = inZStream.Read()))
        {
            byte _dataByte = (byte)data;
            outFileStream.WriteByte(_dataByte);
        }

        inZStream.Close();
        outFileStream.Close();
    }
}

OwnerDisplayName: Vijay


问:
jQuery each() behavior if changing DOM within loop
What is the behavior of jquery when using each() loop? Is it:

look for the first object, execute function, look for the next object...

gather all objects in a container, then execute the function on each of them

other (what exactly?)

An example, where it is relevant:

```<code><div id="a">
   A
   <div id="b">
      B
   </div>
</div>
<div id="c">
    C
</div>
</code>```

If I execute this javascript:

```<code>$('div').each(function(index){
   alert($(this).html());
   $(this).remove();
}
</code>```

Will I see three alerts or only two?

答:
jQuery will behave as you've described in #2. You'll see three alerts:

"A
 B
"

"B"

"C"

However, since div B is inside div A, it will be removed with div A. jQuery still knows about it, and will alert its contents, but it will have already been removed by that time. So, although you get three alerts, you only have two removes (since it removes child elements).

Body:
What is the behavior of jquery when using each() loop? Is it:

look for the first object, execute function, look for the next object...

gather all objects in a container, then execute the function on each of them

other (what exactly?)

An example, where it is relevant:

   A

      B

    C

If I execute this javascript:

$('div').each(function(index){
   alert($(this).html());
   $(this).remove();
}

Will I see three alerts or only two?

Body:
jQuery will behave as you've described in #2. You'll see three alerts:

"A <div> B </div>"

"B"

"C"

However, since div B is inside div A, it will be removed with div A. jQuery still knows about it, and will alert its contents, but it will have already been removed by that time. So, although you get three alerts, you only have two removes (since it removes child elements).


问:
Converting to geojson from db values in PostgreSQL
I am new to postgreSQL.In my project i have a table and i need to make all field as a json format. I tried below code

```<code>SELECT row_to_json(f) As feature
 FROM (SELECT 'Feature' As type
 , ST_AsGeoJSON(geom)::json As geometry
 , row_to_json((SELECT l FROM (SELECT objectid) As l)) As properties
 FROM plutoreferencedata As l WHERE l.objectid = '3') As f;
</code>```

I got result like below

"{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[979999.082000002,196493.280000001],[979897.966399997,196147.8204],[979718.105800003,196197.441599995],[979823.056799993,196549.6884],[979999.082000002,196493.280000001]]]]},"properties": (...)"

Just look the result. Inside properties it shows some ... only.. Please help me to get the values inside the property. Desired output looks like below

```<code>>   {    "geometry":{
>       "type":"MultiPolygon",
>       "coordinates":[
>          [
>             [
>                [
>                   -309443.24253826,
>                   388111.579584133
>                ],
>                [
>                   -134666.391073443,
>                   239616.414560895
>                ],
>                [
>                   -308616.222736376,
>                   238788.813082666
>                ],
>                [
>                   -309443.24253826,
>                   388111.579584133
>                ]
>             ]
>          ]
>       ]    },    "type":"Feature",    "properties":{
>       "objectid":'3'    } }
</code>```

In my case object id is a text value.. Please help me for this. This will be great if u can give me the solution...

Thanks in advance

答:
If you are saying that the output includes the (...) instead of listing your properties, that is a side effect of whatever GUI you are using to run the query.  pgAdmin for example will only show you so much output before adding the (...).

Double clicking on the field (...) will open a dialog box that shows the entire query result and will allow you to copy it all.

Body:
I am new to postgreSQL.In my project i have a table and i need to make all field as a json format. I tried below code

SELECT row_to_json(f) As feature
 FROM (SELECT 'Feature' As type
 , ST_AsGeoJSON(geom)::json As geometry
 , row_to_json((SELECT l FROM (SELECT objectid) As l)) As properties
 FROM plutoreferencedata As l WHERE l.objectid = '3') As f;

I got result like below

"{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[[[[979999.082000002,196493.280000001],[979897.966399997,196147.8204],[979718.105800003,196197.441599995],[979823.056799993,196549.6884],[979999.082000002,196493.280000001]]]]},"properties": (...)"

Just look the result. Inside properties it shows some ... only.. Please help me to get the values inside the property. Desired output looks like below

>   {    "geometry":{
>       "type":"MultiPolygon",
>       "coordinates":[
>          [
>             [
>                [
>                   -309443.24253826,
>                   388111.579584133
>                ],
>                [
>                   -134666.391073443,
>                   239616.414560895
>                ],
>                [
>                   -308616.222736376,
>                   238788.813082666
>                ],
>                [
>                   -309443.24253826,
>                   388111.579584133
>                ]
>             ]
>          ]
>       ]    },    "type":"Feature",    "properties":{
>       "objectid":'3'    } }

In my case object id is a text value.. Please help me for this. This will be great if u can give me the solution...

Thanks in advance


问:
POST an image to PHP using only the URL from Cordova app
Given just the URL, or the FileEntry object.  How do I POST an image to a PHP script?  I have no form or DOM to draw on, just the URL to the image from FileEntry.nativeURL.
I tried following this but it seems to require the DOM.
POST an image to PHP in AJAX
This script will run detached from any page, so it can't use anything from any specific page.

Thanks.

答:
Solved, had to request the file from myself to convert it to a blob, then place it in a FormData object and post it.

```<code>imageData.image_path='file://etc'
return new Promise(function (resolve, reject) {
    var oReq = new XMLHttpRequest();
    oReq.responseType = "blob";
    oReq.onload = function (oEvent) {
         var blob = oReq.response;
         var formData = new FormData();
         formData.append("image", blob);
         var sendImage = new XMLHttpRequest();
         sendImage.open("POST", "https://website/upload-handler");
         sendImage.onload = function (oEvent) {
             resolve(oEvent);
         };
         sendImage.onerror = function (e) {
             reject(e);
         };
         sendImage.send(formData);
    };
    oReq.onerror = function (e) {
        reject(e);
    };
    oReq.open("GET", imageData.image_path, true);
    oReq.send();
});
</code>```

This is a snip of the solution.  The promise returned is used by my queuing system to keep retrying until successful.

Body:
Solved, had to request the file from myself to convert it to a blob, then place it in a FormData object and post it.

imageData.image_path='file://etc'
return new Promise(function (resolve, reject) {
    var oReq = new XMLHttpRequest();
    oReq.responseType = "blob";
    oReq.onload = function (oEvent) {
         var blob = oReq.response;
         var formData = new FormData();
         formData.append("image", blob);
         var sendImage = new XMLHttpRequest();
         sendImage.open("POST", "https://website/upload-handler");
         sendImage.onload = function (oEvent) {
             resolve(oEvent);
         };
         sendImage.onerror = function (e) {
             reject(e);
         };
         sendImage.send(formData);
    };
    oReq.onerror = function (e) {
        reject(e);
    };
    oReq.open("GET", imageData.image_path, true);
    oReq.send();
});

This is a snip of the solution.  The promise returned is used by my queuing system to keep retrying until successful.


问:
assimp issue exporting model textures
I'm trying to export via assimp command line tool two models: one from .fbx (2013) and one from .lwo both to .obj file format.

However I'm not able to extract the textures from the original files.

The command that I perform is:

assimp export INPUT_FILE.xxx OUTPUT_FILE.obj -cts, -gsn, -jiv, -icl, -lbw, -rrm, -slm, -tri, -guv, -sbpt, -fd, -fiv, -fi, -vds -om

The model are:

https://nasa3d.arc.nasa.gov/detail/cubesat-1RU

and

https://nasa3d.arc.nasa.gov/detail/acrimsat

previously converted to the .fbx 2013 file format via FbxConverterUI

答: At the moment we do not export the embedded textures as far as I know. We opened an issue to get this fixed. </p>

Title: assimp issue exporting model textures


问:
How do I load google drive api with javascript?
I load gapi like this:

```<code>gapi.load('client:auth2', () => {
      var auth2 = gapi.auth2.init({
          client_id: `${MYKEY}.apps.googleusercontent.com`,
          scope: 'profile https://www.googleapis.com/auth/drive.appfolder'
      });
      console.log(gapi.client.drive)
}
</code>```

expecting that gapi.client.drive will be available after it loads, but it resolves to null. Any ideas what I'm missing?

答:
Ok, I figured it out - I was missing gapi.client.init step after loading the library:

```<code>gapi.client.init({
        'apiKey': 'API_KEY',
        'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
        'clientId': 'CLIENT_ID.apps.googleusercontent.com',
        'scope': 'https://www.googleapis.com/auth/drive.appfolder',
      }).then(SOME_CALLBACK);
</code>```

Body:
I load gapi like this:

gapi.load('client:auth2', () => {
      var auth2 = gapi.auth2.init({
          client_id: `${MYKEY}.apps.googleusercontent.com`,
          scope: 'profile https://www.googleapis.com/auth/drive.appfolder'
      });
      console.log(gapi.client.drive)
}

expecting that gapi.client.drive will be available after it loads, but it resolves to null. Any ideas what I'm missing?

Body:
Ok, I figured it out - I was missing gapi.client.init step after loading the library:

gapi.client.init({
        'apiKey': 'API_KEY',
        'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
        'clientId': 'CLIENT_ID.apps.googleusercontent.com',
        'scope': 'https://www.googleapis.com/auth/drive.appfolder',
      }).then(SOME_CALLBACK);


问:
Unable to verify leaf signature
I'm using node.js request.js to reach an api. I'm getting this error

[Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE]

All of my credentials are accurate and valid, and the server's fine. I made the same request with postman.

```<code>request({
    "url": domain+"/api/orders/originator/"+id,
    "method": "GET",
    "headers":{
        "X-API-VERSION": 1,
        "X-API-KEY": key
    },
}, function(err, response, body){
    console.log(err);
    console.log(response);
    console.log(body);
});
</code>```

This code is just running in an executable script ex. node ./run_file.js, Is that why? Does it need to run on a server?

答:
I had an issue with my Apache configuration after installing a GoDaddy certificate on a subdomain. I originally thought it might be an issue with Node not sending a Server Name Indicator (SNI), but that wasn't the case. Analyzing the subdomain's SSL certificate with https://www.ssllabs.com/ssltest/ returned the error Chain issues:   Incomplete.

After adding the GoDaddy provided gd_bundle-g2-g1.crt file via the SSLCertificateChainFile Apache directive, Node was able to connect over HTTPS and the error went away.

ContentLicense: CC BY-SA 4.0

Title: Unable to verify leaf signature

Body:
I'm using node.js request.js to reach an api. I'm getting this error

[Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE]

All of my credentials are accurate and valid, and the server's fine. I made the same request with postman.

request({
    "url": domain+"/api/orders/originator/"+id,
    "method": "GET",
    "headers":{
        "X-API-VERSION": 1,
        "X-API-KEY": key
    },
}, function(err, response, body){
    console.log(err);
    console.log(response);
    console.log(body);
});

This code is just running in an executable script ex. node ./run_file.js, Is that why? Does it need to run on a server?


问:
How to print out the reordered affinity matrix after fitting in spectral clustering?
How can I see my new reordered matrix (affinity matrix) after using spectral clustering? How do I print it?</p>

Body:
It is easy to access the affinity matrix after using Spectral Clustering.

Example using the iris data:

from sklearn.datasets import load_iris
from sklearn.cluster import SpectralClustering

#load data
data = load_iris()
x = data.data
y = data.target

#define model and fit data
model = SpectralClustering(n_clusters = 4, random_state = 0)
model.fit(x,y)

#get the Affinity matrix used for clustering
print(model.affinity_matrix_)
print(model.affinity_matrix_.shape)

#get the Labels of each point
print(model.labels_)

Results

#Affinity matrix

[[  1.00000000e+00   7.48263568e-01   7.71051586e-01 ...,   2.30082059e-09
    4.03840951e-10   3.59908895e-08]
 [  7.48263568e-01   1.00000000e+00   9.13931185e-01 ...,   1.62136087e-09
    2.15082380e-10   3.22418674e-08]
 [  7.71051586e-01   9.13931185e-01   1.00000000e+00 ...,   3.65410404e-10
    6.16221335e-11   9.42405852e-09]
 ...,
 [  2.30082059e-09   1.62136087e-09   3.65410404e-10 ...,   1.00000000e+00
    6.83861409e-01   6.63650250e-01]
 [  4.03840951e-10   2.15082380e-10   6.16221335e-11 ...,   6.83861409e-01
    1.00000000e+00   5.54327285e-01]
 [  3.59908895e-08   3.22418674e-08   9.42405852e-09 ...,   6.63650250e-01
    5.54327285e-01   1.00000000e+00]]

(150, 150)

#Labels

[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 3 1 3 1 3 1 3 3 3 3 1 3 1 3 3 1 3 1 3 1 1
 1 1 1 1 1 3 3 3 3 1 3 1 1 3 3 3 3 1 3 3 3 3 3 3 3 3 0 1 0 1 0 0 3 0 0 0 1
 1 0 1 1 1 1 0 0 1 0 1 0 1 0 0 1 1 1 0 0 0 1 1 1 0 1 1 1 0 0 1 1 0 0 1 1 1
 1 1]


问:
C - How to detect EOF in pipe when reading only single char?
As explained in this answer, I'd be expecting the reader process to catch the EOF right after the writer process closes all related file descriptors.

But that doesn't happen and this program ends up stuck in an endless loop.
Parent waits for it's child to finish & child waits for EOF signalizing closed pipe.

Why the reader process doesn't receive EOF?

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

#define STRING_TO_SEND "Hello, world!\n"

int main() {
    int fd[2], i = 0;
    __pid_t pid;
    char _char;
    ssize_t nbytes;

    pipe(fd);
    pid = fork();

    if (pid == -1) {
        // Error
        perror("Error forking!");
        return EXIT_FAILURE;

    } else if (pid == 0) {

        // Child
        close(fd[1]);
        while ((nbytes = read(fd[0], &_char, 1)) != EOF) {
            if (nbytes == 0)
                continue;
            putchar(_char);
        }
        close(fd[0]);

    } else {

        // Parent
        close(fd[0]);

        for(;;) {
            _char = STRING_TO_SEND[i++];
            write(fd[1], &_char, 1);
            if (_char == '\0')
                break;
        }

        close(fd[1]);
        close(STDOUT_FILENO);

        while (wait(NULL)>0) {}
    }
    return 0;
}
</code>```

答:
You simply misunderstood the "end of file" indication of read() which simply means nothing more to read for read() (read() returns 0 in that case). But read() doesn't actually return the value EOF. So your condition should be:

```<code>while ((nbytes = read(fd[0], &_char, 1)) > 0) {
</code>```

Also __pid_t is an internal type of your C library. You shouldn't use that; just use pid_t.

See read(2)'s man page for details.

Body:
As explained in this answer, I'd be expecting the reader process to catch the EOF right after the writer process closes all related file descriptors.

But that doesn't happen and this program ends up stuck in an endless loop.
Parent waits for it's child to finish & child waits for EOF signalizing closed pipe.

Why the reader process doesn't receive EOF?

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

#define STRING_TO_SEND "Hello, world!\n"

int main() {
    int fd[2], i = 0;
    __pid_t pid;
    char _char;
    ssize_t nbytes;

    pipe(fd);
    pid = fork();

    if (pid == -1) {
        // Error
        perror("Error forking!");
        return EXIT_FAILURE;

    } else if (pid == 0) {

        // Child
        close(fd[1]);
        while ((nbytes = read(fd[0], &_char, 1)) != EOF) {
            if (nbytes == 0)
                continue;
            putchar(_char);
        }
        close(fd[0]);

    } else {

        // Parent
        close(fd[0]);

        for(;;) {
            _char = STRING_TO_SEND[i++];
            write(fd[1], &_char, 1);
            if (_char == '\0')
                break;
        }

        close(fd[1]);
        close(STDOUT_FILENO);

        while (wait(NULL)>0) {}
    }
    return 0;
}

Body:
You simply misunderstood the "end of file" indication of read() which simply means nothing more to read for read() (read() returns 0 in that case). But read() doesn't actually return the value EOF. So your condition should be:

while ((nbytes = read(fd[0], &_char, 1)) > 0) {

Also __pid_t is an internal type of your C library. You shouldn't use that; just use pid_t.

See read(2)'s man page for details.


答:
Could you please try following awk and let me know if this helps you.

```<code>awk 'FNR==NR{a[$0];next} ($1 in a){print;delete a[$1];next} END{for(i in a){print i,"0 0 0"}}' mergedAll.txt  ultimatecontrolMed.txt
</code>```

Title: Pattern matches by row name with multiple columns in multiple files

Body:
Could you please try following awk and let me know if this helps you.

awk 'FNR==NR{a[$0];next} ($1 in a){print;delete a[$1];next} END{for(i in a){print i,"0 0 0"}}' mergedAll.txt  ultimatecontrolMed.txt


问:
Optimistic vs Multi Version Concurrency Control - Differences?
I am trying to find out, what the difference between optimistic concurrency control (OCC) and multi version concurrency control (MVCC) is?

So far I know that both is based on version checking for updates.

In OCC, I read about transactions that acquire no locks for reading access, only for the later update which will fail if in between the version was incremented and version checking fails. In this case the transaction will be rolled back.

In MVCC, it is basically the same, or not? Where is the difference?

答: Just to rectify Dimos's answer: timestamp based concurrency control is still a pessimistic method (it may still abort/block transactions during their execution phase).  </p>


问:
6-byte little-endian sequence from 32-bit timestamp multiplied by 1000
Take y = 1510751840.  Suppose you want the 6-byte little-endian sequence of bytes of the number y*1000.  You're using Lua 5.1.  How can you get it?  There is no integer datatype, only double, which is Lua's default.  How can that be done?

For example, if y = 1510743753, the 6-byte sequence should be: 01 5f bf 58 41 28.

Thank you!

Why do I ask?  I must produce a little-endian sequence for the number of miliseconds since the UNIX epoch using a Lua embedded system.  I have only the number of seconds and so I can produce a little-endian 4-byte sequence of this number.  But I must produce a 6-byte, 48-bit byte sequence.  So my idea is to multiply the 32-bit timestamp by 1000, but I can't seem to be able to multiply that number in my Lua 5.1 embeddable system.  So I'm hoping for a hack that allows me to get the 6-byte sequence corresponding to the timestamp * 1000.

Body:
local y = 1510743753

local lo16 = y % 2^16 * 1000 % 2^16
local hi32 = (y - y % 2^16) / 2^16 * 1000 + (y % 2^16 * 1000 - lo16) / 2^16

print(("%08x %04x"):format(hi32, lo16))   -->  015fbf58 4128


问:
how i can show object in gridview or in any usful contro
```<code>public class EventDetail
{
    private Int64 logID;

    public Int64 LogID
    {
        get { return logID; }
        set { logID = value; }
    }
    private Object logedObject;

    public Object LogedObject
    {
        get { return logedObject; }
        set { logedObject = value; }
    }

}
</code>```

答:
First off, you dont need to use fields if you do nothing in the property other then set it.

```<code>public Object LogedObject { get; set; }
</code>```

is enough.

Secondly, to show a list of your objects in a DataGrid, as example.

```<code>protected void Page_Load(object sender, EventArgs e)
{
    DataGrid dg = new DataGrid();
    dg.DataSource = getModels();
    dg.DataBind();
}

public List<EventDetail> getModels()
{
    var m = new List<EventDetail>();
    for (int a = 0; a < 15; a++)
    {
        m.Add(new EventDetail() { prop1 = a, prop2 = string.Format("Prop2 {0}", a) });
    }
    return m;
}

public class EventDetail
{
    public Int64 LogID { get; set; }
    public Object LogedObject { get; set; }
}
</code>```

Body:
First off, you dont need to use fields if you do nothing in the property other then set it.

public Object LogedObject { get; set; }

is enough.

Secondly, to show a list of your objects in a DataGrid, as example.

protected void Page_Load(object sender, EventArgs e)
{
    DataGrid dg = new DataGrid();
    dg.DataSource = getModels();
    dg.DataBind();
}

public List<EventDetail> getModels()
{
    var m = new List<EventDetail>();
    for (int a = 0; a < 15; a++)
    {
        m.Add(new EventDetail() { prop1 = a, prop2 = string.Format("Prop2 {0}", a) });
    }
    return m;
}

public class EventDetail
{
    public Int64 LogID { get; set; }
    public Object LogedObject { get; set; }
}


问:
Convert a string to a matrix in C#
I have a string like this:

```<code> people="Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!
 Dr. Elon Musk;elon@tesla.com;Tesle Inc.!
 Dr.Mehdi Karakoç;mehdi@tetra.com.tr;Tetra Yazılım!";
</code>```

And I want to convert this data to 3x3 matrix like below:

```<code>Prof. Dr. Bill Gates    bill@microsoft.com  Microsoft Corporation
Assoc. Dr. Elon Musk    elon@teslacar.com   Tesle Inc.
Dr. Mehmet Mehdi Kara   mehdi@tetra.com.tr  Tetra Yazılım
</code>```

Each '!' is an 'End of Line' and ';' is the end of each elements
How can I do this in a simple way?

答:
I'm not familiar with Matrix objects, but this is how you would parse that string into a 2d string array. Hope it helps get you on the right track.</p>

```<code>string people = "Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!Dr.Elon Musk; elon @tesla.com; Tesle Inc.!Dr.Mehdi Karakoç; mehdi @tetra.com.tr; Tetra Yazılım!";
string[] tmp;
int maxWidth = 0;
int row;
List<string[]> everybody = new List<string[]>();
string[] folks = people.Split('!');
string[,] matrix;

foreach (string person in folks)
{
    tmp = person.Split(';');
    maxWidth = Math.Max(maxWidth, tmp.Length);
    everybody.Add(tmp);
}

matrix = new string[everybody.Count, maxWidth];
row = 0;

foreach (string[] body in everybody)
{
    for (int i = 0; i < maxWidth; i++)
    {
        if (i < body.Length)
        {
            matrix[row, i] = body[i];
        }//if this person has enough entries
    }//for each value in person
    row++;
}//for each person

//Result is now a 2 dimensional string array, parsed per value per person.
</code>```

Title: Convert a string to a matrix in C#

Body:
I have a string like this:

 people="Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!
 Dr. Elon Musk;elon@tesla.com;Tesle Inc.!
 Dr.Mehdi Karakoç;mehdi@tetra.com.tr;Tetra Yazılım!";

And I want to convert this data to 3x3 matrix like below:

Prof. Dr. Bill Gates    bill@microsoft.com  Microsoft Corporation
Assoc. Dr. Elon Musk    elon@teslacar.com   Tesle Inc.
Dr. Mehmet Mehdi Kara   mehdi@tetra.com.tr  Tetra Yazılım

Each '!' is an 'End of Line' and ';' is the end of each elements
How can I do this in a simple way?

Body:
I'm not familiar with Matrix objects, but this is how you would parse that string into a 2d string array. Hope it helps get you on the right track.

string people = "Prof. Dr. Bill Gates;bill@microsoft.com;Microsoft Corporation!Dr.Elon Musk; elon @tesla.com; Tesle Inc.!Dr.Mehdi Karakoç; mehdi @tetra.com.tr; Tetra Yazılım!";
string[] tmp;
int maxWidth = 0;
int row;
List<string[]> everybody = new List<string[]>();
string[] folks = people.Split('!');
string[,] matrix;

foreach (string person in folks)
{
    tmp = person.Split(';');
    maxWidth = Math.Max(maxWidth, tmp.Length);
    everybody.Add(tmp);
}

matrix = new string[everybody.Count, maxWidth];
row = 0;

foreach (string[] body in everybody)
{
    for (int i = 0; i < maxWidth; i++)
    {
        if (i < body.Length)
        {
            matrix[row, i] = body[i];
        }//if this person has enough entries
    }//for each value in person
    row++;
}//for each person

//Result is now a 2 dimensional string array, parsed per value per person.


问:
React App : Start API server with React server
I'm working on a pretty simple react App (my first), but I can't figure out how to get both the API and the react server to start...

I'm using react-router for client routes and I've used express on another project so I've started my React project with it to setup the API.

But I was wondering if there was a way to use react-router to handle API routes and return some data...

I've googled and looked around but I can seem to find anything about that (nor confirming nor refuting).

Does anyone have any input about that?

(I know it isn't a proper SO question but I can't seem to find any info to close the nagging wonder)

答:
There's a way to start both API server and react. In your express main file in my case server.js. You'd need to install webpack-dev-middleware and webpack-hot-middleware.

```<code>// server.js
import path from 'path';
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './webpack.config';

const app = express(),
  DIST_DIR = path.join(__dirname, 'client'),
  HTML_FILE = path.join(DIST_DIR, 'index.html'),
  compiler = webpack(config),
  isDevelopment = process.env.NODE_ENV === 'development';

if (isDevelopment) {
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  }));

  app.use(webpackHotMiddleware(compiler));
} else {
  app.use(express.static(DIST_DIR));
}

app.get('/', (req, res) => res.sendFile(HTML_FILE));
app.get('*', (req, res) => res.redirect(301, '/'));

app.listen(process.env.PORT || 4200);
</code>```

Then in your webpack.config.js, you can follow my settings below:

```<code>const path = require('path');
const webpack = require('webpack');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    './app/app.jsx',
  ],
  externals: {
    jquery: 'jQuery',
    'react/addons': 'react',
    'react/lib/ExecutionEnvironment': 'react',
    'react/lib/ReactContext': 'react',
  },
  output: {
    path: path.resolve(__dirname, 'client'),
    filename: 'bundle.js',
    publicPath: '/',
    sourceMapFilename: 'bundle.map',
  },
  devtool: process.env.NODE_ENV === 'production'
    ? undefined : 'cheap-module-eval-source-map',
  resolve: {
    modules: ['node_modules', './app/components'],
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /(\.js$|\.jsx$)/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['react', 'es2015', 'stage-0', 'airbnb'],
            },
          },
        ],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]'
          }
        }
      }
    ],
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      minimize: true,
      compressor: {
        warnings: false,
      },
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      },
    }),
  ],
};
</code>```

Then in your package.json scripts:

```<code>// package.json
"scripts": {
    "build": "webpack",
    "postinstall": "npm run build",
    "start": "babel-node server.js",
    "start:dev": "nodemon -e js --exec babel-node -- ./server.js",
    "test": "karma start"
  }
</code>```

Now when you start your express server, your API and react will run together.

Body:
There's a way to start both API server and react. In your express main file in my case server.js. You'd need to install webpack-dev-middleware and webpack-hot-middleware.

// server.js
import path from 'path';
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './webpack.config';

const app = express(),
  DIST_DIR = path.join(__dirname, 'client'),
  HTML_FILE = path.join(DIST_DIR, 'index.html'),
  compiler = webpack(config),
  isDevelopment = process.env.NODE_ENV === 'development';

if (isDevelopment) {
  app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  }));

  app.use(webpackHotMiddleware(compiler));
} else {
  app.use(express.static(DIST_DIR));
}

app.get('/', (req, res) => res.sendFile(HTML_FILE));
app.get('*', (req, res) => res.redirect(301, '/'));

app.listen(process.env.PORT || 4200);

Then in your webpack.config.js, you can follow my settings below:

const path = require('path');
const webpack = require('webpack');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    './app/app.jsx',
  ],
  externals: {
    jquery: 'jQuery',
    'react/addons': 'react',
    'react/lib/ExecutionEnvironment': 'react',
    'react/lib/ReactContext': 'react',
  },
  output: {
    path: path.resolve(__dirname, 'client'),
    filename: 'bundle.js',
    publicPath: '/',
    sourceMapFilename: 'bundle.map',
  },
  devtool: process.env.NODE_ENV === 'production'
    ? undefined : 'cheap-module-eval-source-map',
  resolve: {
    modules: ['node_modules', './app/components'],
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /(\.js$|\.jsx$)/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['react', 'es2015', 'stage-0', 'airbnb'],
            },
          },
        ],
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
        use: {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]'
          }
        }
      }
    ],
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      minimize: true,
      compressor: {
        warnings: false,
      },
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      },
    }),
  ],
};

Then in your package.json scripts:

// package.json
"scripts": {
    "build": "webpack",
    "postinstall": "npm run build",
    "start": "babel-node server.js",
    "start:dev": "nodemon -e js --exec babel-node -- ./server.js",
    "test": "karma start"
  }

Now when you start your express server, your API and react will run together.


问:
Problems with int/String linked lists and variables
I am having some trouble creating a linked list in Java. All of the guides I am following give examples using some kind of variable of type String, but the list I must create needs a type int. Using the type int will produce an error message when I try to call something like position.link because it says it cannot convert an int to a string.

For clarity, the main program should have Scanner ask for the int, and use that int to create a loop that creates each node. I have messed around with iterators and with just simple singular linked lists but I am not getting anywhere.

```<code>import java.util.NoSuchElementException;
public class SuitorLinkedList<Integer>
{
   private class SuitorListNode
   {
      private int suitor;
      private SuitorListNode link;

      public SuitorListNode()
      {
         suitor = 0;
         link = null;
      }

      public SuitorListNode(int newSuitor, SuitorListNode linkValue)
      {
         suitor = newSuitor;
         link = linkValue;
      }
   } // End of SuitorListNode inner class

   public class SuitorListIterator
   {
      public SuitorListNode position;
      private SuitorListNode previous; // previous value of position

      public SuitorListIterator()
      {
         position = head; // variable head of outer class
         previous = null;
      }

      public void restart()
      {
         position = head;
         previous = null;
      }

      public String next()
      {
         if(!hasNext())
            throw new NoSuchElementException();

         String toReturn = position.suitor;
         previous = position;
         position = position.link;
         return toReturn;
      }

      public boolean hasNext()
      {
         return (position != null); // Throws IllegalStateExpression if false
      } // Returns next value to be returned by next()

      public String peak()
      {
         if(!hasNext())
            throw new IllegalStateException();
         return position.suitor;
      }

      public void addHere(int newData)
      {
         if(position == null && previous != null) // At end of list, add to end
            previous.link = new SuitorListNode(newData, null);
         else if(position == null || previous == null) // List empty or position is head node
            head = new SuitorListNode(newData, head);
         else // previous and position are consecutive nodes
         {
            SuitorListNode temp = new SuitorListNode(newData, position);
            previous.link = temp;
            previous = temp;
         }
      }

      public void delete()
      {
         if(position == null)
            throw new IllegalStateException();
         else if (previous == null) // remove node at head
         {
            head = head.link;
            position = head;
         }
         else // previous and position are consecutive nodes
         {
            previous.link = position.link;
            position = position.link;
         }
      }

      private SuitorListNode head;
   }
   public SuitorListIterator iterator()
   {
      return new SuitorListIterator();
   }
}
</code>```

I get this error every time I try, I've tried searching it up and using the toString() to help but it won't work:

```<code>SuitorLinkedList.java:60: error: incompatible types: int cannot be converted to String
         return position.suitor;
                        ^
</code>```

I have tried creating the regular linked list and got this far:

```<code>public class SuitorList
{
   public class SuitorNode
   {
      public int suitor;
      public SuitorNode link;

      public SuitorNode()
      {
         suitor = 0;
         link = null;
      } // Initialize veriables

      public SuitorNode(int newSuitor, SuitorNode linkValue)
      {
         suitor = newSuitor;
         link = linkValue;
      } // Assigns values sent in from main
   } // End inner class

   private SuitorNode head; // Variable head of type SuitorNode (callback to Node program)
   // Allows head to point to a node

   public SuitorList()
   {
      head = null;
   } // Initialize variables
   // Memory space called head filled with null

   public void addToStart(int suitorNum)
   {
      head = new SuitorNode(suitorNum, head);
   }

   // Creates node with head pointing to it at start of list
   // head will have a definition as an object with a suitor and link = head
   // If head = null, then link = null
   // head is repositioned to point to node

   public int size() // Reads size of list
   {
      int count = 0;
      SuitorNode position = head; // Variable position of type SuitorNode will equal value at head; position points where head is pointing
      while(position != null) // While list is not empty/ended
      {
         count++; // increase number of entries detected
         position = position.link; // getLink will make position = link, leading to next entry in list
      }
      return count; // Display size.
   }

   public void outputList()
   {
      SuitorNode position = head; // Position points to same thing head points to

      while(position != null) // While list is not empty/ended
      {
         System.out.println(position.suitor); // Print suitor
         position = position.link; // Go to next entry
      }
   }

   public void deleteNode(int count)
   {
      int moveCount = count - 1;
      SuitorNode position = head;

      while(head != link) // not winning
      {
         moveCount = count;
         checkEnd(); // Checks for win before causing potential problem with 1 suitor left
         checkTwoNumbersLeft(moveCount); // Takes care of movement when two nodes are left
         checkEndNode(moveCount); // Checks when, for example, 2 nodes away

         if(moveCount == count) // If checkEndNode and checkTwoNumbersLeft fail
         {
            position = position.link; // Move for first time
            moveCount = moveCount - 1;
         }

         checkEnd();
         checkEndNode2(moveCount); // When one movement is made already, deletes end node after

         if(moveCount == moveCount - 1) // if checkEndNode2 fails
            position = position.link.link; // 2nd deletion
         count = moveCount;
      }

      isWinner();
   } // End method deleteNode()

   public void checkTwoNumbersLeft(int moveCount)
   {
      SuitorNode position;
      if(position.link.link == null) // example: 1 5
      {
         createLoop();
         position = position.link.link; // Deletes the 5
         moveCount = moveCount - 2;
      } // Used just in case only two numbers are present
   } // End method checkTwoNumbersLeft()

   public void checkEnd()
   {
      SuitorNode position;
      if(position.link == null) // If at end of list
      {
         createLoop(); // creates a loop if the initial number has no next value
         isWinner(); // If a 1 is used, the entire if statement will trigger
      } // if true, head == link which will fall out of while in deleteNode()
   } // End method checkEnd()

   public void isWinner()
   {
      SuitorNode link;
      SuitorNode position;
      if(position == position.link)
      {
         head = link;
         System.out.println("The winner is Suitor " + position + "!");
      }
   } // End method isWinner()

   public void checkEndNode2(int moveCount)
   {
      SuitorNode position;
      SuitorNode link;

      if(position.link.link == null) // 1 movement
      {
         position.link = null;
         createLoop();
         isWinner();
         moveCount = moveCount - 1;
      }
   } // End checkEndNode2()

   public void checkEndNode(int moveCount)
   {
      SuitorNode position;
      SuitorNode link;

      if(position.link.link.link == null) // no movements
      {
         position = position.link;
         position.link = null;
         createLoop();
         isWinner();
         moveCount = moveCount - 2;
      }
   } // End checkEndNode()

   public void createLoop()
   {
      SuitorNode position;
      SuitorNode link;

      if(link == null) // if at the end of the list
         link = head; // Sets link to point to where head points, AKA beginning of list
   } // End createLoop()
}
</code>```

But when I do this, the variables link, position, and head always say they are not initialized unless I place them inside the method (which can mess up my code if I call the method while in the middle of the list).

My questions boil down to 1) How would I be able to convert the ints to strings in order to work with a linked list? and 2) Why are the variables in the program SuitorList requiring me to reinitialize them in every instance when I've tried placing them everywhere I could?

答:
The variable suitor is given the variable type of int. It is possible to turn it into a string. By converting it;

```<code>public String peak() { if(!hasNext()) throw new IllegalStateException(); return Integer.toString(position.suitor); }
</code>```

This method should get rid of that error. Or using String.valueOf(position.suitor);.

Body:
I am having some trouble creating a linked list in Java. All of the guides I am following give examples using some kind of variable of type String, but the list I must create needs a type int. Using the type int will produce an error message when I try to call something like position.link because it says it cannot convert an int to a string.

For clarity, the main program should have Scanner ask for the int, and use that int to create a loop that creates each node. I have messed around with iterators and with just simple singular linked lists but I am not getting anywhere.

import java.util.NoSuchElementException;
public class SuitorLinkedList<Integer>
{
   private class SuitorListNode
   {
      private int suitor;
      private SuitorListNode link;

      public SuitorListNode()
      {
         suitor = 0;
         link = null;
      }

      public SuitorListNode(int newSuitor, SuitorListNode linkValue)
      {
         suitor = newSuitor;
         link = linkValue;
      }
   } // End of SuitorListNode inner class

   public class SuitorListIterator
   {
      public SuitorListNode position;
      private SuitorListNode previous; // previous value of position

      public SuitorListIterator()
      {
         position = head; // variable head of outer class
         previous = null;
      }

      public void restart()
      {
         position = head;
         previous = null;
      }

      public String next()
      {
         if(!hasNext())
            throw new NoSuchElementException();

         String toReturn = position.suitor;
         previous = position;
         position = position.link;
         return toReturn;
      }

      public boolean hasNext()
      {
         return (position != null); // Throws IllegalStateExpression if false
      } // Returns next value to be returned by next()

      public String peak()
      {
         if(!hasNext())
            throw new IllegalStateException();
         return position.suitor;
      }

      public void addHere(int newData)
      {
         if(position == null && previous != null) // At end of list, add to end
            previous.link = new SuitorListNode(newData, null);
         else if(position == null || previous == null) // List empty or position is head node
            head = new SuitorListNode(newData, head);
         else // previous and position are consecutive nodes
         {
            SuitorListNode temp = new SuitorListNode(newData, position);
            previous.link = temp;
            previous = temp;
         }
      }

      public void delete()
      {
         if(position == null)
            throw new IllegalStateException();
         else if (previous == null) // remove node at head
         {
            head = head.link;
            position = head;
         }
         else // previous and position are consecutive nodes
         {
            previous.link = position.link;
            position = position.link;
         }
      }

      private SuitorListNode head;
   }
   public SuitorListIterator iterator()
   {
      return new SuitorListIterator();
   }
}

I get this error every time I try, I've tried searching it up and using the toString() to help but it won't work:

SuitorLinkedList.java:60: error: incompatible types: int cannot be converted to String
         return position.suitor;
                        ^

I have tried creating the regular linked list and got this far:

public class SuitorList
{
   public class SuitorNode
   {
      public int suitor;
      public SuitorNode link;

      public SuitorNode()
      {
         suitor = 0;
         link = null;
      } // Initialize veriables

      public SuitorNode(int newSuitor, SuitorNode linkValue)
      {
         suitor = newSuitor;
         link = linkValue;
      } // Assigns values sent in from main
   } // End inner class

   private SuitorNode head; // Variable head of type SuitorNode (callback to Node program)
   // Allows head to point to a node

   public SuitorList()
   {
      head = null;
   } // Initialize variables
   // Memory space called head filled with null

   public void addToStart(int suitorNum)
   {
      head = new SuitorNode(suitorNum, head);
   }

   // Creates node with head pointing to it at start of list
   // head will have a definition as an object with a suitor and link = head
   // If head = null, then link = null
   // head is repositioned to point to node

   public int size() // Reads size of list
   {
      int count = 0;
      SuitorNode position = head; // Variable position of type SuitorNode will equal value at head; position points where head is pointing
      while(position != null) // While list is not empty/ended
      {
         count++; // increase number of entries detected
         position = position.link; // getLink will make position = link, leading to next entry in list
      }
      return count; // Display size.
   }

   public void outputList()
   {
      SuitorNode position = head; // Position points to same thing head points to

      while(position != null) // While list is not empty/ended
      {
         System.out.println(position.suitor); // Print suitor
         position = position.link; // Go to next entry
      }
   }

   public void deleteNode(int count)
   {
      int moveCount = count - 1;
      SuitorNode position = head;

      while(head != link) // not winning
      {
         moveCount = count;
         checkEnd(); // Checks for win before causing potential problem with 1 suitor left
         checkTwoNumbersLeft(moveCount); // Takes care of movement when two nodes are left
         checkEndNode(moveCount); // Checks when, for example, 2 nodes away

         if(moveCount == count) // If checkEndNode and checkTwoNumbersLeft fail
         {
            position = position.link; // Move for first time
            moveCount = moveCount - 1;
         }

         checkEnd();
         checkEndNode2(moveCount); // When one movement is made already, deletes end node after

         if(moveCount == moveCount - 1) // if checkEndNode2 fails
            position = position.link.link; // 2nd deletion
         count = moveCount;
      }

      isWinner();
   } // End method deleteNode()

   public void checkTwoNumbersLeft(int moveCount)
   {
      SuitorNode position;
      if(position.link.link == null) // example: 1 5
      {
         createLoop();
         position = position.link.link; // Deletes the 5
         moveCount = moveCount - 2;
      } // Used just in case only two numbers are present
   } // End method checkTwoNumbersLeft()

   public void checkEnd()
   {
      SuitorNode position;
      if(position.link == null) // If at end of list
      {
         createLoop(); // creates a loop if the initial number has no next value
         isWinner(); // If a 1 is used, the entire if statement will trigger
      } // if true, head == link which will fall out of while in deleteNode()
   } // End method checkEnd()

   public void isWinner()
   {
      SuitorNode link;
      SuitorNode position;
      if(position == position.link)
      {
         head = link;
         System.out.println("The winner is Suitor " + position + "!");
      }
   } // End method isWinner()

   public void checkEndNode2(int moveCount)
   {
      SuitorNode position;
      SuitorNode link;

      if(position.link.link == null) // 1 movement
      {
         position.link = null;
         createLoop();
         isWinner();
         moveCount = moveCount - 1;
      }
   } // End checkEndNode2()

   public void checkEndNode(int moveCount)
   {
      SuitorNode position;
      SuitorNode link;

      if(position.link.link.link == null) // no movements
      {
         position = position.link;
         position.link = null;
         createLoop();
         isWinner();
         moveCount = moveCount - 2;
      }
   } // End checkEndNode()

   public void createLoop()
   {
      SuitorNode position;
      SuitorNode link;

      if(link == null) // if at the end of the list
         link = head; // Sets link to point to where head points, AKA beginning of list
   } // End createLoop()
}

But when I do this, the variables link, position, and head always say they are not initialized unless I place them inside the method (which can mess up my code if I call the method while in the middle of the list).

My questions boil down to 1) How would I be able to convert the ints to strings in order to work with a linked list? and 2) Why are the variables in the program SuitorList requiring me to reinitialize them in every instance when I've tried placing them everywhere I could?

Body:
The variable suitor is given the variable type of int. It is possible to turn it into a string. By converting it;

public String peak() { if(!hasNext()) throw new IllegalStateException(); return Integer.toString(position.suitor); }

This method should get rid of that error. Or using String.valueOf(position.suitor);.


答:
EOF is a constant usually defined to -1 that stdio (the C library buffering layer around the raw system calls) uses to signal end of file in functions like getchar() which conflate the returned character with an end-of-file signal.

read signals end-of-file by simply returning 0. Note that it can also return -1 if there's an error (e.g., you can get EINTR if the read is interrupted by a signal handler before it read anything).

Consequently, what you want is something like:

```<code>while ((nbytes = read(fd[0], &_char, 1)) > 0){ /*...*/ }
if (0>nread) { /*report error (or maybe repeat if it's EINTR)*/ }
</code>```

Manpages (read(2)) or the POSIX spec for read document all this.

Title: C - How to detect EOF in pipe when reading only single char?

Body:
EOF is a constant usually defined to -1 that stdio (the C library buffering layer around the raw system calls) uses to signal end of file in functions like getchar() which conflate the returned character with an end-of-file signal.

read signals end-of-file by simply returning 0. Note that it can also return -1 if there's an error (e.g., you can get EINTR if the read is interrupted by a signal handler before it read anything).

Consequently, what you want is something like:

while ((nbytes = read(fd[0], &_char, 1)) > 0){ /*...*/ }
if (0>nread) { /*report error (or maybe repeat if it's EINTR)*/ }

Manpages (read(2)) or the POSIX spec for read document all this.


问:
Run each Docker container in a specific user namespace configuration
Problem:

I am trying to mount a directory as Docker volume in such a way,
that a user, which is created inside a container could write
into a file in that volume. And at the same time, the file should
be at least readable to my user lape outside the container.

Essentially, I need to remap a user UID from container user namespace to a specific UID on the host user namespace.

How can I do that?

I would prefer answers that:

do not involve changing the way how Docker daemon is run;

and allows a possibility to configure container user namespace for each container separately;

do not require rebuilding the image;

I would accept answer that shows a nice solution using Access Control Lists as well;

Setup:

This is how the situation can be replicated.

I have my Linux user lape, assigned to docker group, so I
can run Docker containers without being root.

```<code>lape@localhost ~ $ id
uid=1000(lape) gid=1000(lape) groups=1000(lape),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),121(lpadmin),131(sambashare),999(docker)
</code>```

Dockerfile:

```<code>FROM alpine
RUN apk add --update su-exec && rm -rf /var/cache/apk/*

# I create a user inside the image which i want to be mapped to my `lape`
RUN adduser -D -u 800 -g 801 insider
VOLUME /data

COPY ./entrypoint.sh /entrypoint.sh
ENTRYPOINT ["sh", "/entrypoint.sh"]
</code>```

entrypoint.sh:

```<code>#!/bin/sh
chmod 755 /data
chown insider:insider /data

# This will run as `insider`, and will touch a file to the shared volume
# (the name of the file will be current timestamp)
su-exec insider:insider sh -c 'touch /data/$(date +%s)'

# Show permissions of created files
ls -las /data
</code>```

Once the is built with:

```<code>docker build -t nstest
</code>```

I run the container:

```<code>docker run --rm -v $(pwd)/data:/data nstest
</code>```

The output looks like:

```<code>total 8
 4 drwxr-xr-x    2 insider  insider       4096 Aug 26 08:44 .
 4 drwxr-xr-x   31 root     root          4096 Aug 26 08:44 ..
 0 -rw-r--r--    1 insider  insider          0 Aug 26 08:44 1503737079
</code>```

So the file seems to be created as user insider.

From my host the permissions look like this:

```<code>lape@localhost ~ $ ls -las ./data
total 8
4 drwxr-xr-x 2  800  800 4096 Aug 26 09:44 .
4 drwxrwxr-x 3 lape lape 4096 Aug 26 09:43 ..
0 -rw-r--r-- 1  800  800    0 Aug 26 09:44 1503737079
</code>```

Which indicates that the file belongs to uid=800 (that is the insider user which does not even exist outside the Docker namespace).

Things I tried already:

I tried specifying --user parameter to docker run, but it seems it can only map which user on the host is mapped to uid=0 (root) inside the docker namespace, in my case the insider is not root. So it did not really work in this case.

The only way how I achieved insider(uid=800) from within container, to be seen as lape(uid=1000) from host, was by adding --userns-remap="default" to the dockerd startup script, and adding dockremap:200:100000 to files /etc/subuid and /etc/subgid as suggested in documentation for --userns-remap. Coincidentally this worked for me, but it is not sufficient solution, because:

it requires reconfigure the way how the Docker daemon runs;

requires to do some arithmetic on user ids: '200 = 1000 - 800', where 1000 is the UID my user on the host, and 800 the UID is of the insider user;

that would not even work if the insider user would need to have a higher UID than my host user;

it can only configure how user namespaces are mapped globally, without a way to have unique configuration per container;

this solution kind of works but it is a bit too ugly for practical usage.

答:
If you just need a read access for your user, the simplest will be to add the read permissions for all files and subdirectories in /data with acls outside of docker.

Add default acl: setfacl -d -m u:lape:-rx /data.

You will also need to give access to the directory itself: setfacl -m u:lape:-rx /data.

Are there any obstacles for such a solution?

Body:
Problem:

I am trying to mount a directory as Docker volume in such a way,
that a user, which is created inside a container could write
into a file in that volume. And at the same time, the file should
be at least readable to my user lape outside the container.

Essentially, I need to remap a user UID from container user namespace to a specific UID on the host user namespace.

How can I do that?

I would prefer answers that:

do not involve changing the way how Docker daemon is run;

and allows a possibility to configure container user namespace for each container separately;

do not require rebuilding the image;

I would accept answer that shows a nice solution using Access Control Lists as well;

Setup:

This is how the situation can be replicated.

I have my Linux user lape, assigned to docker group, so I
can run Docker containers without being root.

lape@localhost ~ $ id
uid=1000(lape) gid=1000(lape) groups=1000(lape),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),121(lpadmin),131(sambashare),999(docker)

Dockerfile:

FROM alpine
RUN apk add --update su-exec && rm -rf /var/cache/apk/*

# I create a user inside the image which i want to be mapped to my `lape`
RUN adduser -D -u 800 -g 801 insider
VOLUME /data

COPY ./entrypoint.sh /entrypoint.sh
ENTRYPOINT ["sh", "/entrypoint.sh"]

entrypoint.sh:

#!/bin/sh
chmod 755 /data
chown insider:insider /data

# This will run as `insider`, and will touch a file to the shared volume
# (the name of the file will be current timestamp)
su-exec insider:insider sh -c 'touch /data/$(date +%s)'

# Show permissions of created files
ls -las /data

Once the is built with:

docker build -t nstest

I run the container:

docker run --rm -v $(pwd)/data:/data nstest

The output looks like:

total 8
 4 drwxr-xr-x    2 insider  insider       4096 Aug 26 08:44 .
 4 drwxr-xr-x   31 root     root          4096 Aug 26 08:44 ..
 0 -rw-r--r--    1 insider  insider          0 Aug 26 08:44 1503737079

So the file seems to be created as user insider.

From my host the permissions look like this:

lape@localhost ~ $ ls -las ./data
total 8
4 drwxr-xr-x 2  800  800 4096 Aug 26 09:44 .
4 drwxrwxr-x 3 lape lape 4096 Aug 26 09:43 ..
0 -rw-r--r-- 1  800  800    0 Aug 26 09:44 1503737079

Which indicates that the file belongs to uid=800 (that is the insider user which does not even exist outside the Docker namespace).

Things I tried already:

I tried specifying --user parameter to docker run, but it seems it can only map which user on the host is mapped to uid=0 (root) inside the docker namespace, in my case the insider is not root. So it did not really work in this case.

The only way how I achieved insider(uid=800) from within container, to be seen as lape(uid=1000) from host, was by adding --userns-remap="default" to the dockerd startup script, and adding dockremap:200:100000 to files /etc/subuid and /etc/subgid as suggested in documentation for --userns-remap. Coincidentally this worked for me, but it is not sufficient solution, because:

it requires reconfigure the way how the Docker daemon runs;

requires to do some arithmetic on user ids: '200 = 1000 - 800', where 1000 is the UID my user on the host, and 800 the UID is of the insider user;

that would not even work if the insider user would need to have a higher UID than my host user;

it can only configure how user namespaces are mapped globally, without a way to have unique configuration per container;

this solution kind of works but it is a bit too ugly for practical usage.


问:
Checking if 2 variables out 3 are equal in python
I am making a code where three dice are rolled and if all three dice are equal the values are added. If 2 of the dice are equal then the 2 equal dice values are added and the odd dice value is subtracted from the sum.

This is my code so far

```<code>import random

d1 = random.randint(1,6)
d2 = random.randint(1,6)
d3 = random.randint(1,6)

print(d1)
print(d2)
print(d3)

if d1 == d2 and d2 == d3:
    score = d1 + d2 + d3
elif d1 == d2 or d1 == d3 or d2 == d3:
</code>```

Now I don't know how I would find out which of the 2 dice are equal to be able to add them together. How would I do this?

答:
You can use a sequence of if-statements:

```<code>if d1 == d2:
    if d2 == d3:
        score = d1 + d2 + d3
    else:
        score = (d1 + d2) - d3
elif d2 == d3:
    score = (d2 + d3) - d1
elif d1 == d3:
    score = (d1 + d3) - d2
else:
    score = 0
</code>```

The brackets aren't necessary, just make it a bit clearer

Body:
I am making a code where three dice are rolled and if all three dice are equal the values are added. If 2 of the dice are equal then the 2 equal dice values are added and the odd dice value is subtracted from the sum.

This is my code so far

import random

d1 = random.randint(1,6)
d2 = random.randint(1,6)
d3 = random.randint(1,6)

print(d1)
print(d2)
print(d3)

if d1 == d2 and d2 == d3:
    score = d1 + d2 + d3
elif d1 == d2 or d1 == d3 or d2 == d3:

Now I don't know how I would find out which of the 2 dice are equal to be able to add them together. How would I do this?

Body:
You can use a sequence of if-statements:

if d1 == d2:
    if d2 == d3:
        score = d1 + d2 + d3
    else:
        score = (d1 + d2) - d3
elif d2 == d3:
    score = (d2 + d3) - d1
elif d1 == d3:
    score = (d1 + d3) - d2
else:
    score = 0

The brackets aren't necessary, just make it a bit clearer


问:
Pattern matches by row name with multiple columns in multiple files
I have two files, one with a full list of gene names and three others with partial lists of gene names. I want to match these files all into one. All the partial files are different number of rows but have 3000 columns, all representing different cells. I have been trying to join these files completely but when I use awk only one column is kept.

mergedAll.txt

```<code>GENE
SOX2
BRCA1
BRCA2
RHO
</code>```

ultimatecontrolMed.txt

```<code>GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA2    400     234     73
RHO      12      2       0
</code>```

My Desired output would be

```<code>GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA1    0       0       0
BRCA2    400     234     73
RHO      12      2       0
</code>```

I run:

```<code>awk 'NR==FNR{k[$1];next}{b[$1]=$0;k[$1]}
END{for(x in k)
      if ( x== "GENE" )
         printf"%s %s\n",x,b[x]
      else
         printf"%s  %d\n",x,b[x]
}' mergedAll.txt ultimatecontrolMed.txt > test.txt
</code>```

And I get:

```<code>GENE CELL1 CELL 2 CELL3
SOX2 2000
BRCA1 0
BRCA2 73
RHO 0
</code>```

For some reason it will keep the last column of counts but not any of the other lines, and keep all the cell names. I don't have any experience with awk so this has been a major challenge for me overall and would love it if someone could offer a better solution.

答:
The problem is that you're printing b[x] with %d format. That's for printing a single integer, so it will ignore all the other integers in b[x]. Change

```<code>     printf"%s  %d\n",x,b[x]
</code>```

to:

```<code>    if (b[x]) {
        printf "%s\t%s\n", x, b[x]
    } else {
        printf "%s" x;
        for (i = 0; i < 3000; i++) printf "\t0"
        print ""
    }
</code>```

so that it will print the entire value. If there's no corresponding value, it will print zeroes.

Replace 3000 with the appropriate number of cells. If you don't want to hard-code it, you can get it from NF-1 when FNR == 1 && FNR != NR (the first line of the second file).

Body:
I have two files, one with a full list of gene names and three others with partial lists of gene names. I want to match these files all into one. All the partial files are different number of rows but have 3000 columns, all representing different cells. I have been trying to join these files completely but when I use awk only one column is kept.

mergedAll.txt

GENE
SOX2
BRCA1
BRCA2
RHO

ultimatecontrolMed.txt

GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA2    400     234     73
RHO      12      2       0

My Desired output would be

GENE     CELL1   CELL2   CELL3
SOX2     30      152     2000
BRCA1    0       0       0
BRCA2    400     234     73
RHO      12      2       0

I run:

awk 'NR==FNR{k[$1];next}{b[$1]=$0;k[$1]}
END{for(x in k)
      if ( x== "GENE" )
         printf"%s %s\n",x,b[x]
      else
         printf"%s  %d\n",x,b[x]
}' mergedAll.txt ultimatecontrolMed.txt > test.txt

And I get:

GENE CELL1 CELL 2 CELL3
SOX2 2000
BRCA1 0
BRCA2 73
RHO 0

For some reason it will keep the last column of counts but not any of the other lines, and keep all the cell names. I don't have any experience with awk so this has been a major challenge for me overall and would love it if someone could offer a better solution.

Body:
The problem is that you're printing b[x] with %d format. That's for printing a single integer, so it will ignore all the other integers in b[x]. Change

     printf"%s  %d\n",x,b[x]

to:

    if (b[x]) {
        printf "%s\t%s\n", x, b[x]
    } else {
        printf "%s" x;
        for (i = 0; i < 3000; i++) printf "\t0"
        print ""
    }

so that it will print the entire value. If there's no corresponding value, it will print zeroes.

Replace 3000 with the appropriate number of cells. If you don't want to hard-code it, you can get it from NF-1 when FNR == 1 && FNR != NR (the first line of the second file).