问:
System.out.print output to console seen immediately. So PrintStream flushes after each print, not only println?
From the PrintStream documentation:

Optionally, a PrintStream can be created so as to flush automatically;
  this means that the flush method is automatically invoked after a byte
  array is written, one of the println methods is invoked, or a newline
  character or byte ('\n') is written.

Then given code

```<code>System.out.print("hi");   // gives console output: hi
System.out.print(7);      // gives console output: 7

// prevents flushing when stream wiil be closed at app shutdown
for (;;) {
}
</code>```

Why then I see output to my console?  Nothing shall be written to console (PrintStream instance from System.out), because nothing shall be flushed so far!

This didn't answer this.

I guess, the answer is in the source code (private utility method BufferedWriter.flushBuffer()), but I don't understand the comment to code: "Flushes the output buffer to the underlying character stream, without flushing the stream itself": if PrintStream (which is tied to console output), which is "stream itself" is not flushed, output to console shall not be refreshed!...

Source for PrintStream.print(String):

```<code>private void write(String s) {
        try {
            synchronized (this) {
                ensureOpen();
                textOut.write(s);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush && (s.indexOf('\n') >= 0))
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }
</code>```

Source for BufferedWriter.flushBuffer():

```<code>/**
     * Flushes the output buffer to the underlying character stream, without
     * flushing the stream itself.  This method is non-private only so that it
     * may be invoked by PrintStream.
     */
    void flushBuffer() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar == 0)
                return;
            out.write(cb, 0, nextChar);
            nextChar = 0;
        }
    }
</code>```

More details are also given here. It is very complicated, but seems like at some stage BufferedWriter is given to PrintStream constructor.

答:
I went step by step using debugger and this is what I found:

String s is displayed in the console after 527th line, so it's before line 528 in which the check of having \n is done.

In charOut.flushBuffer() deep inside, there is the following method called:

In which, the check about \n is missing.

The flow is as it follows:

System.out#print(String s) calls PrintStream#print(String s).

PrintStream#print(String s) calls PrintStream#write(String s).

PrintStream#write(String s) calls OutputSteamWriter#flushBuffer().

OutputStreamWriter#flushBuffer() calls StreamEncoder#flushBuffer().

StreamEncoder#flushBuffer() calls StreamEncoder#implFlushBuffer().

StreamEncoder#implFlushBuffer() calls StreamEncoder#writeBytes().

StreamEncoder#writeBytes() calls PrintStream#write(byte buf[], int off, int len) which flushes the buffor if(autoFlush).

The most important snippets are above. The BufferedWriter seems not to be called in this flow.

Body:
From the PrintStream documentation:

Optionally, a PrintStream can be created so as to flush automatically;
  this means that the flush method is automatically invoked after a byte
  array is written, one of the println methods is invoked, or a newline
  character or byte ('\n') is written.

Then given code

System.out.print("hi");   // gives console output: hi
System.out.print(7);      // gives console output: 7

// prevents flushing when stream wiil be closed at app shutdown
for (;;) {
}

Why then I see output to my console?  Nothing shall be written to console (PrintStream instance from System.out), because nothing shall be flushed so far!

This didn't answer this.

I guess, the answer is in the source code (private utility method BufferedWriter.flushBuffer()), but I don't understand the comment to code: "Flushes the output buffer to the underlying character stream, without flushing the stream itself": if PrintStream (which is tied to console output), which is "stream itself" is not flushed, output to console shall not be refreshed!...

Source for PrintStream.print(String):

private void write(String s) {
        try {
            synchronized (this) {
                ensureOpen();
                textOut.write(s);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush && (s.indexOf('\n') >= 0))
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }

Source for BufferedWriter.flushBuffer():

/**
     * Flushes the output buffer to the underlying character stream, without
     * flushing the stream itself.  This method is non-private only so that it
     * may be invoked by PrintStream.
     */
    void flushBuffer() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar == 0)
                return;
            out.write(cb, 0, nextChar);
            nextChar = 0;
        }
    }

More details are also given here. It is very complicated, but seems like at some stage BufferedWriter is given to PrintStream constructor.


来源: stackexchange

问:
reading two long sentences using scanf
I want to read two long sentences from input using scanf() which are in two new lines.

Code:

```<code>int main() {
    char a[100], b[100];
    scanf("%[^\n]s", a);
    scanf("%[^\n]s", b);
    printf("%s\n%s", a, b);
}
</code>```

Input:

```<code>she is beautiful
That is a flower
</code>```

Output:

```<code>she is beautiful
</code>```

The second input is not being read by the scanf() statement.

How to fix it?

答:
You could use fgets. And this could work for you.

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

int main() {
    char a[100], b[100];

    if (fgets(a, sizeof a, stdin) == NULL) {
        puts("fgets error");
        return -1;
    }

    if (fgets(b, sizeof b, stdin) == NULL) {   //Read blank lines
        puts("fgets error");
        return -1;
    }

    if (fgets(b, sizeof b, stdin) == NULL) {
        puts("fgets error");
        return -1;
    }

    printf("%s\n%s", a, b);

    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: reading two long sentences using scanf

Body:
I want to read two long sentences from input using scanf() which are in two new lines.

Code:

int main() {
    char a[100], b[100];
    scanf("%[^\n]s", a);
    scanf("%[^\n]s", b);
    printf("%s\n%s", a, b);
}

Input:

she is beautiful
That is a flower

Output:

she is beautiful

The second input is not being read by the scanf() statement.

How to fix it?

Body:
You could use fgets. And this could work for you.

#include <stdio.h>
#include <stdint.h>

int main() {
    char a[100], b[100];

    if (fgets(a, sizeof a, stdin) == NULL) {
        puts("fgets error");
        return -1;
    }

    if (fgets(b, sizeof b, stdin) == NULL) {   //Read blank lines
        puts("fgets error");
        return -1;
    }

    if (fgets(b, sizeof b, stdin) == NULL) {
        puts("fgets error");
        return -1;
    }

    printf("%s\n%s", a, b);

    return 0;
}


问:
Turbolinks, Rails, back button, footer from other source
I have an issue with turbolinks. When I click a 'back' button in browser there is one more footer appends.

In application.html.slim:

```<code>doctype html
html
  head
    title
      - unless content_for(:title).present?
        | Some text...
      - else
        == yield :title
    meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
    = csrf_meta_tags
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
    - if admin_admin_signed_in?
      = stylesheet_link_tag    'cms/application', media: 'all', 'data-turbolinks-track': 'reload'
      = javascript_include_tag 'cms/application', 'data-turbolinks-track': 'reload'
</code>```

I load a footer from the other source (application.coffee):

```<code>$(document).on 'turbolinks:load', ->
    $('footer').get(0).innerHTML = ''
    for src in ['//other_site.com/goc/us/other_site.com/responsive.js', '//other_site.com/footer-builder.js']
      s = document.createElement('script')
      s.async = true
      s.src = src
      document.getElementsByTagName('head')[0].appendChild s
</code>```

Thanks for attention in advance!

答:
By clearing the cache (as in https://stackoverflow.com/a/44398711/783009) you''ll be missing out on some of the performance benefits that Turbolinks offers.

@uzaif is correct in that the page is being cached. Here is what is happening:

Page 1 loads

Footer is loaded from other source

User clicks on a link to page 2

Turbolinks caches the page

Page 2 loads

User presses Back

Turbolinks loads the cached page (with the footer)

Footer is loaded again from other source :/

If you are adding HTML to a page on every page load, the idiomatic approach is to "teardown" the effects of any scripts on turbolinks:before-cache. It's a little tricky to write code for this without seeing what the footer scripts do, but the general idea is:

```<code>$(document).on 'turbolinks:load', ->
  # load your footer…

$(document).on 'turbolinks:before-cache', ->
  # teardown your footer
</code>```

For more information on this, see here: https://github.com/turbolinks/turbolinks#preparing-the-page-to-be-cached

Alternatively, if the footer doesn't change between page loads, you may wish to only load the content once (e.g. on $(document).ready), then keep it between page loads. To do this, you'll need to give the footer an ID, and a data-turbolinks-permanent attribute. As long as the footer with the ID is in every response from the server, the footer content with be maintained. For more on this, see here: https://github.com/turbolinks/turbolinks#persisting-elements-across-page-loads

Body:
I have an issue with turbolinks. When I click a 'back' button in browser there is one more footer appends.

In application.html.slim:

doctype html
html
  head
    title
      - unless content_for(:title).present?
        | Some text...
      - else
        == yield :title
    meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
    = csrf_meta_tags
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
    - if admin_admin_signed_in?
      = stylesheet_link_tag    'cms/application', media: 'all', 'data-turbolinks-track': 'reload'
      = javascript_include_tag 'cms/application', 'data-turbolinks-track': 'reload'

I load a footer from the other source (application.coffee):

$(document).on 'turbolinks:load', ->
    $('footer').get(0).innerHTML = ''
    for src in ['//other_site.com/goc/us/other_site.com/responsive.js', '//other_site.com/footer-builder.js']
      s = document.createElement('script')
      s.async = true
      s.src = src
      document.getElementsByTagName('head')[0].appendChild s

Thanks for attention in advance!

Body:
By clearing the cache (as in https://stackoverflow.com/a/44398711/783009) you''ll be missing out on some of the performance benefits that Turbolinks offers.

@uzaif is correct in that the page is being cached. Here is what is happening:

Page 1 loads

Footer is loaded from other source

User clicks on a link to page 2

Turbolinks caches the page

Page 2 loads

User presses Back

Turbolinks loads the cached page (with the footer)

Footer is loaded again from other source :/

If you are adding HTML to a page on every page load, the idiomatic approach is to "teardown" the effects of any scripts on turbolinks:before-cache. It's a little tricky to write code for this without seeing what the footer scripts do, but the general idea is:

$(document).on 'turbolinks:load', ->
  # load your footer…

$(document).on 'turbolinks:before-cache', ->
  # teardown your footer

For more information on this, see here: https://github.com/turbolinks/turbolinks#preparing-the-page-to-be-cached

Alternatively, if the footer doesn't change between page loads, you may wish to only load the content once (e.g. on $(document).ready), then keep it between page loads. To do this, you'll need to give the footer an ID, and a data-turbolinks-permanent attribute. As long as the footer with the ID is in every response from the server, the footer content with be maintained. For more on this, see here: https://github.com/turbolinks/turbolinks#persisting-elements-across-page-loads


问:
How do people protect against 307 redirect
If evilsite.com submits a form to evilsite.com/foo and then 307 redirects to goodsite.com/bar where a user is already logged in, this will send the POST with goodsites cookie to goodsite.com/bar.

How do people usually protect against this?
Do normal webframeworks django/flask do anything to protect against this?

I can see two ways of protecting against this:

put a token into your pages that is sent with every form (not cookie).
This seems like a lot of work.

look at the referrer header. But there are browser plugins that suppress the referrer or worse just pretend the destination is the referrer. And I'm not sure how reliable this referrer header is.

答: It's called CSRF. You should use anti CSRF tokens to prevent this kind of vulnerability. All modern frameworks can deal with it.</p>


问:
Handling Null Values in F#
I need to interop with some C# code with F#. Null is a possible value that it is given so I need to check if the value was null. The docs suggest using pattern matching as such:

```<code>match value with
| null -> ...
| _ -> ...
</code>```

The problem I'm having is the original code is structured in C# as:

```<code>if ( value != null ) {
    ...
}
</code>```

How do I do the equivalent in F#? Is there a no-op for pattern matching? Is there a way to check for null with an if statement?

答:
I've recently faced a similar dilemma. My issue was that I exposed an F#-developed API that could be consumed from C# code. C# has no issue passing null to a method that accepts interfaces or classes, but if the method and the types of its arguments are F# types, you are not allowed to properly do the null checks.

The reason is that F# types initially do not accept the null literal, while technically nothing in the CLR protects your API from being improperly invoked, especially from a more null-tolerant language such as C#. You would initially end up being unable to properly null-protect yourself unless you use the [<AllowNullLiteral>] attribute, which is quite an ugly approach.

So, I've come to this solution in the related topic, which allows me to keep my F# code clean and F#-friendly. In general I create a function that will accept any object and will convert it to an Option, then instead of null I will validate against None. This is similar to using the pre-defined in F# Option.ofObj function, but the latter does require the object passed to be explicitly nullable (thus annotated with the AllowNullLiteral uglyness).

Title: Handling Null Values in F#

Body:
I need to interop with some C# code with F#. Null is a possible value that it is given so I need to check if the value was null. The docs suggest using pattern matching as such:

match value with
| null -> ...
| _ -> ...

The problem I'm having is the original code is structured in C# as:

if ( value != null ) {
    ...
}

How do I do the equivalent in F#? Is there a no-op for pattern matching? Is there a way to check for null with an if statement?


问:
Laravel - How to CRUD records with ownership?
Let's say I've multiple users - Admin, Manager, User. User can CRUD records owned by him. Manager can CRUD records owned by him and his Users. Admin can CRUD records of all. How to achieve this in Laravel?</p>

答:
If you have only one role use middleware.

If you have multiple roles just like you are saying you have use gates/policies provided by Laravel out of the box.

To handle admin you will use before filter

```<code>public function before($user, $ability)
{
    return ($user->is_admin) ? true : null; //return null so we continue authorising further
}
</code>```

To handle manager || user you will use something along these lines (most tricky one):

```<code>public someCRUDaction(User $current, Item $item) {
    return $item->created_by == $current->id || $current->users->contains('id', $item->created_by); // you need to handle logic if item belongs to manager
}
</code>```

Note: $item->created_by == $current->id is self explanatory and handles if current user is owner of item

How to use policies (I would go with policies) and gates:

https://laravel.com/docs/5.4/authorization#writing-policies

Remember that you don't want to validate anything just simply can $current user do action X?

Using policies you will need to check if user can do action X at least two times (in views and in controllers/routes/customized form requests - where you handle validation).

Body:
If you have only one role use middleware.

If you have multiple roles just like you are saying you have use gates/policies provided by Laravel out of the box.

To handle admin you will use before filter

public function before($user, $ability)
{
    return ($user->is_admin) ? true : null; //return null so we continue authorising further
}

To handle manager || user you will use something along these lines (most tricky one):

public someCRUDaction(User $current, Item $item) {
    return $item->created_by == $current->id || $current->users->contains('id', $item->created_by); // you need to handle logic if item belongs to manager
}

Note: $item->created_by == $current->id is self explanatory and handles if current user is owner of item

How to use policies (I would go with policies) and gates:

https://laravel.com/docs/5.4/authorization#writing-policies

Remember that you don't want to validate anything just simply can $current user do action X?

Using policies you will need to check if user can do action X at least two times (in views and in controllers/routes/customized form requests - where you handle validation).


问:
Unable to display dropdown and popover AngularJS
I am new to this, can you help me figure out why my dropdown is not displaying properly and also the popover of the second value of dropdown is not working properly?
I am a bit confuse since it is my first time trying this.
Here is my code

```<code><ul class="nav site-nav">
<li class=flyout>
    <a href=#>Menu</a>

<!-- Flyout -->
<ul class="flyout-content nav stacked">
  <li>
    <div ng-app>
      <div ng-controller="popoverCtrl">
        <a href="#" ng-mouseover="showPopover=true;" ng-mouseleave="showPopover=false;">Real Account <div class="popover" ng-show="showPopover"><span>{{ popover.title }}</span>{{ popover.message }}</div></a>
      </div>
    </div>
  </li>
  <li>
    <div ng-app>
      <div ng-controller="popoverCtrl2">
        <a href="#" ng-mouseover="showPopover2=true;" ng-mouseleave="showPopover2=false;">Practice Account <div class="popover2" ng-show="showPopover2"><span>{{ popover2.title }}</span>{{ popover2.message }}</div></a>
      </div>
    </div>
  </li>

</ul>
</code>```

and my JS

```<code>function popoverCtrl($scope) {

  $scope.showPopover = false;

  $scope.popover = {
    title: 'Title',
    message: 'Message'
  };

}

function popoverCtrl2($scope2) {

  $scope2.showPopover2 = false;

  $scope2.popover2 = {
    title: 'Test',
    message: 'Sample'
  };
}
</code>```

Here is what I have done so far http://jsfiddle.net/fn1aj1e6/

答:
You can't use function popoverCtrl2($scope2), as Angular will parse the argument names for dependency injection, and it will not find a service with name $scope2. Just use:

```<code>function popoverCtrl2($scope) {

  $scope.showPopover2 = false;

  $scope.popover2 = {
    title: 'Test',
    message: 'Sample'
  };

}
</code>```

Body:
I am new to this, can you help me figure out why my dropdown is not displaying properly and also the popover of the second value of dropdown is not working properly?
I am a bit confuse since it is my first time trying this.
Here is my code

    Menu

        Real Account
{{ popover.title }}{{ popover.message }}

        Practice Account
{{ popover2.title }}{{ popover2.message }}

and my JS

function popoverCtrl($scope) {

  $scope.showPopover = false;

  $scope.popover = {
    title: 'Title',
    message: 'Message'
  };

}

function popoverCtrl2($scope2) {

  $scope2.showPopover2 = false;

  $scope2.popover2 = {
    title: 'Test',
    message: 'Sample'
  };
}

Here is what I have done so far http://jsfiddle.net/fn1aj1e6/

Body:
You can't use function popoverCtrl2($scope2), as Angular will parse the argument names for dependency injection, and it will not find a service with name $scope2. Just use:

function popoverCtrl2($scope) {

  $scope.showPopover2 = false;

  $scope.popover2 = {
    title: 'Test',
    message: 'Sample'
  };

}


问:
Page Unload Event in Cordova
I have a cordova app. I that I want do some task like stop the Location service when the user try to leave the page. I have tried the window.beforeunload but it didnt not work. Is there a way i can do this.

答: If you want to perform an action (do some task) before the user leaves your app, you can use the window.onunload event.

Title: Page Unload Event in Cordova


问:
shell_exec not working
Here's my command:

```<code>sudo /usr/local/bin/jpegoptim --max=50 /home/someuser/public_html/reports/images/r121662.jpg
</code>```

This command is supposed to compress an image. I tried running this command using backtick operator and shell_exec, neither will work. The file doesn't compress.

But this command runs when I run it directly in the shell logged in as someuser. I've modified sudoers to accept the command without requiring a password. The file is compressed when I run it in the shell.

Apache is configured to run with suPHP, and the PHP files belong to someuser as well. I've further ensured this by writing a test php script just saying system(id); and running it in the browser. That tells me that the script is indeed being run by someuser.

Also, safe_mode is off.

EDIT: Ok, I got it to output the error

```<code>sudo: sorry, you must have a tty to run sudo
</code>```

Now, what does it mean?!

答: Try sudo -S to see if setting it to read the password from stdin (even though it doesn't need one) will bypass the test for a tty.

ContentLicense: CC BY-SA 2.5

Title: shell_exec not working

Body:
Here's my command:

sudo /usr/local/bin/jpegoptim --max=50 /home/someuser/public_html/reports/images/r121662.jpg

This command is supposed to compress an image. I tried running this command using backtick operator and shell_exec, neither will work. The file doesn't compress.

But this command runs when I run it directly in the shell logged in as someuser. I've modified sudoers to accept the command without requiring a password. The file is compressed when I run it in the shell.

Apache is configured to run with suPHP, and the PHP files belong to someuser as well. I've further ensured this by writing a test php script just saying system(id); and running it in the browser. That tells me that the script is indeed being run by someuser.

Also, safe_mode is off.

EDIT: Ok, I got it to output the error

sudo: sorry, you must have a tty to run sudo

Now, what does it mean?!


问:
Exception in sending message via SCTP in Java
I am doing some testing with SCTP in a simple client server model.
My Server code is following:

```<code>public class SCTPServer extends Thread {

    InetSocketAddress serverSocketAddress=null;
    SctpServerChannel sctpServerChannel;
    SctpChannel sctpChannel;
    boolean running = false;
    ByteBuffer bf = ByteBuffer.allocateDirect(160);
    String id= null;
    public SCTPClient  sctpClient= null;
    public SCTPServer(String IP, int  port, String clientIp, int clientPort, String id) {

        try {
            serverSocketAddress = new InetSocketAddress(IP, port);
            sctpServerChannel = SctpServerChannel.open().bind(serverSocketAddress);

        } catch (Exception e) {
            System.out.println("Failed to open Sctp connection Reciver on IP:" + IP + " and Port:" + port+"  "+e);
            System.exit(0);
        }
    }

    public void run()
    {
        running = true;
        while (running) {

            try {
                sctpClient.sendAsp();
                sctpChannel = sctpServerChannel.accept();
                try {
                sctpChannel.receive(bf, null, null);
                bf.flip();
                byte[] barry = new byte[bf.limit()];   //we may keep the received data on this new byte arrray here or in some
                bf.get(barry, 0, bf.limit());
                bf.clear();
                System.out.println("new sctp message is received");
                System.out.println(new String(barry));

            } catch (IOException ex) {
                System.out.println("Failed to receive from sctp Channel " + ex);
            }

            } catch (Exception ex) {
                System.out.println("Exception at Starting SCTP Server channel"+ ex);
            }
        }
    }

}
</code>```

and the client code following:

```<code>public class SCTPClient extends Thread {

    SctpChannel sctpChannel;
    InetSocketAddress socketAddress;//= new InetSocketAddress("202.51.176.44", 5555);
    boolean runniung = false;
    ByteBuffer bf = ByteBuffer.allocateDirect(160);
    String id= null;

    public SCTPClient(String ip, int port, int maxInStream, int maxOutStream, String id) {
        socketAddress = new InetSocketAddress(ip, port);
        this.id = id;
        //InetSocketAddress sockAd = new InetSocketAddress("202.51.176.44",55556);
        try {
            sctpChannel = SctpChannel.open();
            System.out.println("SCTP  connection opened with IP==" + ip + " port == " + port);
            //sctpChannel.bind(sockAd);
            sctpChannel.connect(socketAddress, maxInStream, maxOutStream);

            runniung = true;
            sendMSG();

        } catch (Exception ex) {
            System.out.println("Exception at opening sctp connection:" + ex);
            System.exit(0);
        }
    }
    public void sendMSG()
    {
        MessageInfo messageInfo =null;
        /*try {
        } catch (IOException ex) {
            System.out.println("Failed to create Message Info " + ex.toString());
        }*/

            messageInfo = MessageInfo.createOutgoing( null, 0);
        ByteBuffer byteBuffer = buildMessage(1, "test");
        try {
            sctpChannel.send(byteBuffer, messageInfo);
            byteBuffer.clear();
            System.out.println("A message has been sent");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Failed to send the message due to :" + e.toString());
        }
    }

    public static ByteBuffer buildMessage(Integer id,String infoString)
    {

        //We can calculate the total length of the message hard codedly, even before building the total message.
        int totalLength = (id!=null) ? 16 : 8;
        totalLength += (infoString!=null) ? (4+infoString.length()) : 0;
        ByteBuffer data = ByteBuffer.allocateDirect(totalLength);

        //Own part of ASP Up message
        if(id!=null)
        {

            data.putInt(ASPIdentifier);
        }
        if(infoString!=null)
        {

            data.put(infoString.getBytes());
        }
        return data;
    }
}
</code>```

The problem here is that, when I try to connect to a remote PC the SCTP association is established successfully. But when the SendMSG function is called the system aborts with following exception

```<code>java.net.SocketException: Invalid argument
at sun.nio.ch.SctpChannelImpl.send0(Native Method) Failed to send the message due to :java.net.SocketException: Invalid argument
at sun.nio.ch.SctpChannelImpl.sendFromNativeBuffer(SctpChannelImpl.java:1027)
at sun.nio.ch.SctpChannelImpl.send(SctpChannelImpl.java:987)
at sun.nio.ch.SctpChannelImpl.send(SctpChannelImpl.java:967)
at sctptester.SCTPClient.sendMSG(SCTPClient.java:79)
at sctptester.SCTPClient.<init>(SCTPClient.java:40)
at test.main(test.java:66)
</code>```

答:
I think you should add the destination when sending in the client, </p>

```<code>        messageInfo = MessageInfo.createOutgoing( null, 0);
        //replace with
        msgInfo = MessageInfo.createOutgoing(new InetSocketAddress(ip, port), 0);
</code>```

Body:
I am doing some testing with SCTP in a simple client server model.
My Server code is following:

public class SCTPServer extends Thread {

    InetSocketAddress serverSocketAddress=null;
    SctpServerChannel sctpServerChannel;
    SctpChannel sctpChannel;
    boolean running = false;
    ByteBuffer bf = ByteBuffer.allocateDirect(160);
    String id= null;
    public SCTPClient  sctpClient= null;
    public SCTPServer(String IP, int  port, String clientIp, int clientPort, String id) {

        try {
            serverSocketAddress = new InetSocketAddress(IP, port);
            sctpServerChannel = SctpServerChannel.open().bind(serverSocketAddress);

        } catch (Exception e) {
            System.out.println("Failed to open Sctp connection Reciver on IP:" + IP + " and Port:" + port+"  "+e);
            System.exit(0);
        }
    }

    public void run()
    {
        running = true;
        while (running) {

            try {
                sctpClient.sendAsp();
                sctpChannel = sctpServerChannel.accept();
                try {
                sctpChannel.receive(bf, null, null);
                bf.flip();
                byte[] barry = new byte[bf.limit()];   //we may keep the received data on this new byte arrray here or in some
                bf.get(barry, 0, bf.limit());
                bf.clear();
                System.out.println("new sctp message is received");
                System.out.println(new String(barry));

            } catch (IOException ex) {
                System.out.println("Failed to receive from sctp Channel " + ex);
            }

            } catch (Exception ex) {
                System.out.println("Exception at Starting SCTP Server channel"+ ex);
            }
        }
    }

}

and the client code following:

public class SCTPClient extends Thread {

    SctpChannel sctpChannel;
    InetSocketAddress socketAddress;//= new InetSocketAddress("202.51.176.44", 5555);
    boolean runniung = false;
    ByteBuffer bf = ByteBuffer.allocateDirect(160);
    String id= null;

    public SCTPClient(String ip, int port, int maxInStream, int maxOutStream, String id) {
        socketAddress = new InetSocketAddress(ip, port);
        this.id = id;
        //InetSocketAddress sockAd = new InetSocketAddress("202.51.176.44",55556);
        try {
            sctpChannel = SctpChannel.open();
            System.out.println("SCTP  connection opened with IP==" + ip + " port == " + port);
            //sctpChannel.bind(sockAd);
            sctpChannel.connect(socketAddress, maxInStream, maxOutStream);

            runniung = true;
            sendMSG();

        } catch (Exception ex) {
            System.out.println("Exception at opening sctp connection:" + ex);
            System.exit(0);
        }
    }
    public void sendMSG()
    {
        MessageInfo messageInfo =null;
        /*try {
        } catch (IOException ex) {
            System.out.println("Failed to create Message Info " + ex.toString());
        }*/

            messageInfo = MessageInfo.createOutgoing( null, 0);
        ByteBuffer byteBuffer = buildMessage(1, "test");
        try {
            sctpChannel.send(byteBuffer, messageInfo);
            byteBuffer.clear();
            System.out.println("A message has been sent");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Failed to send the message due to :" + e.toString());
        }
    }

    public static ByteBuffer buildMessage(Integer id,String infoString)
    {

        //We can calculate the total length of the message hard codedly, even before building the total message.
        int totalLength = (id!=null) ? 16 : 8;
        totalLength += (infoString!=null) ? (4+infoString.length()) : 0;
        ByteBuffer data = ByteBuffer.allocateDirect(totalLength);

        //Own part of ASP Up message
        if(id!=null)
        {

            data.putInt(ASPIdentifier);
        }
        if(infoString!=null)
        {

            data.put(infoString.getBytes());
        }
        return data;
    }
}

The problem here is that, when I try to connect to a remote PC the SCTP association is established successfully. But when the SendMSG function is called the system aborts with following exception

java.net.SocketException: Invalid argument
at sun.nio.ch.SctpChannelImpl.send0(Native Method) Failed to send the message due to :java.net.SocketException: Invalid argument
at sun.nio.ch.SctpChannelImpl.sendFromNativeBuffer(SctpChannelImpl.java:1027)
at sun.nio.ch.SctpChannelImpl.send(SctpChannelImpl.java:987)
at sun.nio.ch.SctpChannelImpl.send(SctpChannelImpl.java:967)
at sctptester.SCTPClient.sendMSG(SCTPClient.java:79)
at sctptester.SCTPClient.<init>(SCTPClient.java:40)
at test.main(test.java:66)

Body:
I think you should add the destination when sending in the client,

        messageInfo = MessageInfo.createOutgoing( null, 0);
        //replace with
        msgInfo = MessageInfo.createOutgoing(new InetSocketAddress(ip, port), 0);


问:
How to automatically reload an iframe with embedded google presentation?
I use this bit of code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <script>
        window.setInterval("reloadIFrame();", 3000);
        function reloadIFrame() {
                     document.getElementsByName("testFrame")[0].contentWindow.location.reload();
        }
        </script>
        <iframe name="testFrame" src="https://docs.google.com/presentation/d/1jkNVBxAX57PjfxTNTkgO8zNnMFYoKUqUKQ4aJk8pCIs/embed?start=true&loop=true&delayms=5000" width="760px" height="920px"></iframe>
    </body>
</html>
</code>```

And it works well for some websites, but not for this google presntation.. What should I change to make it works?

答:
You can try this instead, otherwise you will have a cross origin issue:

```<code>document.getElementsByName("testFrame")[0].src="https://docs.google.com/presentation/d/1jkNVBxAX57PjfxTNTkgO8zNnMFYoKUqUKQ4aJk8pCIs/embed?start=true&loop=true&delayms=5000";
</code>```

regards

Body:
I use this bit of code:

<!DOCTYPE html>

        <title>Example</title>

And it works well for some websites, but not for this google presntation.. What should I change to make it works?

Body:
You can try this instead, otherwise you will have a cross origin issue:

document.getElementsByName("testFrame")[0].src="https://docs.google.com/presentation/d/1jkNVBxAX57PjfxTNTkgO8zNnMFYoKUqUKQ4aJk8pCIs/embed?start=true&loop=true&delayms=5000";

regards


问:
react native flex direction
Generally in the excel sheet..we have rows like below

```<code>Row1
Row2
Row3
</code>```

and columns like

```<code>column1  | column2 | column3
</code>```

But why in react native when using flexDirection: 'column' the box's/text are defined as

```<code>flexcolumn1
flexcolumn2
flexcolumn3
</code>```

and when using flexDirection: 'row' the box's/text are defined as

```<code>flexrow1  | flexrow2 | flexrow3
</code>```

i find this weird and getting confused... is this just standard difference in react native or there is different concept behind this ?

答:
From the docs:

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.

Title: react native flex direction

Body:
Generally in the excel sheet..we have rows like below

Row1
Row2
Row3

and columns like

column1  | column2 | column3

But why in react native when using flexDirection: 'column' the box's/text are defined as

flexcolumn1
flexcolumn2
flexcolumn3

and when using flexDirection: 'row' the box's/text are defined as

flexrow1  | flexrow2 | flexrow3

i find this weird and getting confused... is this just standard difference in react native or there is different concept behind this ?


问:
iOS Autolayout | View's height anchor
I'm using UITableViewAutomaticDimension to calculate cells height.
In my custom cell, height depends on it's content (text).
So i need to layout UIImageView height. I need to set UIImageView maximum height to some constant. But when text is short UIImageView's height becomes smaller to fit its superview with inset.

Current result

Needs to be

Playground code example:

```<code>//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = ["", "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(equalToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),
            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view
</code>```

Thanks everyone!

Final solution:

```<code>    //: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = [nil, "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    var detailImageViewBottomAnchor: NSLayoutConstraint!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        detailImageViewBottomAnchor = detailImageView.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4)
        detailImageViewBottomAnchor.priority = 749
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(lessThanOrEqualToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageViewBottomAnchor,
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view
</code>```

答:
I just found the solution which just works for me.

I have followed this solution to make it work.
All you have to do for your View.

Make your height constraint's less than or equal to a value(let's say,40) and priority default(1000)

Draw a bottom constraint which has high priority(750) and just give a value

And thats it.

This is how it looks.

And this is attribute of height constraint.

This is for bottom constraint.

This is my whole layout hierarchy(It's not important though just to let you know that you can use stack View for your text Label :))

And this is the output.

Title: iOS Autolayout | View's height anchor

Body:
I'm using UITableViewAutomaticDimension to calculate cells height.
In my custom cell, height depends on it's content (text).
So i need to layout UIImageView height. I need to set UIImageView maximum height to some constant. But when text is short UIImageView's height becomes smaller to fit its superview with inset.

Current result

Needs to be

Playground code example:

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = ["", "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(equalToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),
            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view

Thanks everyone!

Final solution:

    //: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let descriptions = [nil, "Curabitur.", "Senectus sit consectetur fermentum nisi suspendisse a condimentum at vestibulum a vestibulum a nostra fermentum molestie sodales molestie id viverra scelerisque consectetur.Penatibus a dictum metus mus commodo a hac morbi parturient parturient convallis ultrices a mi id.Fringilla lobortis suspendisse vestibulum quisque consectetur imperdiet.", "Condimentum adipiscing.", "Cras scelerisque parturient vitae class sollicitudin.", "Integer adipiscing a adipiscing parturient tempus condimentum a interdum facilisis feugiat.", "Donec eros eleifend a ullamcorper class scelerisque nisi nullam nisi sociis ante iaculis pharetra malesuada nibh sit consectetur condimentum.Nibh sollicitudin."]

    lazy var tableView: UITableView = {
        let tv = UITableView()
        tv.dataSource = self
        tv.estimatedRowHeight = 80
        tv.rowHeight = UITableViewAutomaticDimension
        tv.separatorStyle = .none
        tv.register(PrototypeCell.self, forCellReuseIdentifier: NSStringFromClass(PrototypeCell.self))
        return tv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        tableView.frame = view.frame
        view.addSubview(self.tableView)
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return descriptions.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PrototypeCell.self), for: indexPath) as! PrototypeCell
        cell.titleLabel.text = "Title #\(indexPath.row)"
        cell.subtitleLabel.text = "Subtitle #\(indexPath.row)"
        cell.descriptionLabel.text = descriptions[indexPath.row]
        return cell
    }
}

class PrototypeCell: UITableViewCell {

    let foregroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        return v
    }()

    let detailImageView: UIImageView = {
        let iv = UIImageView()
        iv.translatesAutoresizingMaskIntoConstraints = false
        iv.backgroundColor = .gray
        return iv
    }()

    let titleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Title"
        return lbl
    }()

    let subtitleLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 1
        lbl.text = "Subtitile"
        lbl.font = UIFont.systemFont(ofSize: 12)
        return lbl
    }()

    let descriptionLabel: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.font = UIFont.systemFont(ofSize: 10)
        return lbl
    }()

    var detailImageViewBottomAnchor: NSLayoutConstraint!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        detailImageViewBottomAnchor = detailImageView.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4)
        detailImageViewBottomAnchor.priority = 749
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none

        contentView.addSubview(foregroundView)
        foregroundView.addSubview(detailImageView)
        foregroundView.addSubview(titleLabel)
        foregroundView.addSubview(subtitleLabel)
        foregroundView.addSubview(descriptionLabel)

        NSLayoutConstraint.activate([
                foregroundView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
                foregroundView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -4),
                foregroundView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),
                foregroundView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 4),

                detailImageView.heightAnchor.constraint(lessThanOrEqualToConstant: 64),
                detailImageView.widthAnchor.constraint(equalToConstant: 64),
                detailImageView.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                detailImageViewBottomAnchor,
                detailImageView.leadingAnchor.constraint(equalTo: foregroundView.leadingAnchor, constant: 4),

                titleLabel.topAnchor.constraint(equalTo: foregroundView.topAnchor, constant: 4),
                titleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: 4),
                titleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 2),
                subtitleLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                subtitleLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

                descriptionLabel.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 2),
                descriptionLabel.trailingAnchor.constraint(equalTo: foregroundView.trailingAnchor, constant: -4),
                descriptionLabel.bottomAnchor.constraint(equalTo: foregroundView.bottomAnchor, constant: -4),
                descriptionLabel.leadingAnchor.constraint(equalTo: detailImageView.trailingAnchor, constant: 4),

            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var ctrl = ViewController()
PlaygroundPage.current.liveView = ctrl.view


问:
Logical Operations on Big Integers in MySQL
I'm using Apache XAMPP server. I need to perform logical operations on big integers, something like 5 (101) & 2 (010) = 0 (000). Unfortunately my big integers exceeds the maximum of MySQL BIGINT which is 18446744073709551615.

An example of my used numbers is 455214730926009756012878233, so instead of BIGINT i used VARCHAR, i need to perform logical operations on this VARCHAR.
I tried something like

```<code>SELECT number FROM table WHERE number & 12 = 12
</code>```

it doesn't return the right rows.
And  when i try something like

```<code>SELECT number FROM table WHERE number &  455214730926009756012878233 = 455214730926009756012878233
</code>```

it gives me no rows, while it should return the row in which the number is '455214730926009756012878233'

So, what is the right way to do logical operations on real big integers like this in MySQL?

答:
The question is not about logical operators (those handle Boolean values), but about bitwise operators.

In MySQL v5.7 bitwise operators are restricted to bigints:

Currently, bit functions and operators require BIGINT (64-bit integer)
  arguments and return BIGINT values, so they have a maximum range of 64
  bits. Arguments of other types are converted to BIGINT and truncation
  might occur.

1) You may consider upgrading to v8.0 because it supports binary strings as operands to bitwise operations:

In MySQL 8.0, bit functions and operators permit binary string type arguments (BINARY, VARBINARY, and the BLOB types) and return a value of like type, which enables them to take arguments and produce return values larger than 64 bits. Nonbinary string arguments are converted to BIGINT and processed as such, as before.

However, v8.0 is still under development at this moment, so this could be a risky move for a production database.

2) You may try to split your large number into multiple 64 bit numbers, perform the operations on each part. For this to work efficiently, I would store the numbers in a hexadecimal format as opposed to standard decimal format because you can get the various parts by reading a fixed number of characters (16) from the string and use it for the conversion.

```<code>    select * from yourtable
    where left(`fieldname`,16) & left(X'1788b7802c8530419999999',16)=left(X'1788b7802c8530419999999')
      and right(fieldname,char_length(fieldname)-16) & right(X'1788b7802c8530419999999',char_length(X'1788b7802c8530419999999')-16)=right(X'1788b7802c8530419999999',char_length(X'1788b7802c8530419999999')-16)
</code>```

Body:
I'm using Apache XAMPP server. I need to perform logical operations on big integers, something like 5 (101) & 2 (010) = 0 (000). Unfortunately my big integers exceeds the maximum of MySQL BIGINT which is 18446744073709551615.

An example of my used numbers is 455214730926009756012878233, so instead of BIGINT i used VARCHAR, i need to perform logical operations on this VARCHAR.
I tried something like

SELECT number FROM table WHERE number & 12 = 12

it doesn't return the right rows.
And  when i try something like

SELECT number FROM table WHERE number &  455214730926009756012878233 = 455214730926009756012878233

it gives me no rows, while it should return the row in which the number is '455214730926009756012878233'

So, what is the right way to do logical operations on real big integers like this in MySQL?

Body:
The question is not about logical operators (those handle Boolean values), but about bitwise operators.

In MySQL v5.7 bitwise operators are restricted to bigints:

Currently, bit functions and operators require BIGINT (64-bit integer)
  arguments and return BIGINT values, so they have a maximum range of 64
  bits. Arguments of other types are converted to BIGINT and truncation
  might occur.

1) You may consider upgrading to v8.0 because it supports binary strings as operands to bitwise operations:

In MySQL 8.0, bit functions and operators permit binary string type arguments (BINARY, VARBINARY, and the BLOB types) and return a value of like type, which enables them to take arguments and produce return values larger than 64 bits. Nonbinary string arguments are converted to BIGINT and processed as such, as before.

However, v8.0 is still under development at this moment, so this could be a risky move for a production database.

2) You may try to split your large number into multiple 64 bit numbers, perform the operations on each part. For this to work efficiently, I would store the numbers in a hexadecimal format as opposed to standard decimal format because you can get the various parts by reading a fixed number of characters (16) from the string and use it for the conversion.

    select * from yourtable
    where left(`fieldname`,16) & left(X'1788b7802c8530419999999',16)=left(X'1788b7802c8530419999999')
      and right(fieldname,char_length(fieldname)-16) & right(X'1788b7802c8530419999999',char_length(X'1788b7802c8530419999999')-16)=right(X'1788b7802c8530419999999',char_length(X'1788b7802c8530419999999')-16)


问:
IntelliJ IDEA and docker plugin
I am using IntelliJ IDEA 2017.1.4 with Docker plugin.
When I click debug, it will build the project, docker, it will start it up and I can see log from the container. Unfortunatelly, debugger is not attached to that container. Error message:

```<code>Cannot retrieve debug connection: java.net.MalformedURLException: unknown protocol: tcp
</code>```

When I create new remote debug configuration for the defined port 5001, I can attach to running container. Why it's not attached directly from plugin please?

My configuration:
container_settings.json

```<code>{
  "HostConfig": {
    "PortBindings": {
      "5001/tcp": [
        {
          "HostIp": "0.0.0.0",
          "HostPort": "5001"
        }
      ]
    }
  }
}
</code>```

Thank you.

答:
Issue solved.

In IntelliJ IDEA settings - Ctrl + Alt + S open Build, Execution, Deployment and Docker.

Previously my API url was tcp://localhost:2375, and it build and deployed container without any problem, but did not attach debugger to it. After changing to https://localhost:2376 everything works perfect.

Title: IntelliJ IDEA and docker plugin

Body:
I am using IntelliJ IDEA 2017.1.4 with Docker plugin.
When I click debug, it will build the project, docker, it will start it up and I can see log from the container. Unfortunatelly, debugger is not attached to that container. Error message:

Cannot retrieve debug connection: java.net.MalformedURLException: unknown protocol: tcp

When I create new remote debug configuration for the defined port 5001, I can attach to running container. Why it's not attached directly from plugin please?

My configuration:
container_settings.json

{
  "HostConfig": {
    "PortBindings": {
      "5001/tcp": [
        {
          "HostIp": "0.0.0.0",
          "HostPort": "5001"
        }
      ]
    }
  }
}

Thank you.


问:
Variable values inside selectInput in Shiny
Here is my R shiny code:

ui.R

```<code>shinyUI(bootstrapPage(
uiOutput("GD"),
hr(),
fluidRow(column(3, verbatimTextOutput("value")))
))
</code>```

server.R

```<code>shinyServer(function(input, output) {

  output$GD <- renderUI({
  nBads <- sum(tab[nrow(tab),3:ncol(tab)])
  nGoods <- sum(tab[(nrow(tab)-1),3:ncol(tab)])
  nTotal <- nBads + nGoods

  options(warn=-1)
  Outcome_color <- 0
  G <- 0
  st <-0
  ldate <- 0
  for (k in (1:(nrow(tab)/2))) {

  tabela <- data.frame(tab[1:2,3:(ncol(tab))])
  rownames(tabela) <- c("Goods", "Bads")

  wr <- (sum(tabela)^2 - (rowSums(tabela)[[1]]^2 + rowSums(tabela)[[2]]^2))
x <- which(tabela >= 0)
y <- x[lapply(x,"%%",2)==0]
y1 <- x[lapply(x,"%%",2)!=0]
n <-length(y)

a<-0; a1<-0; Nc<-0; A1x<-0; Nd<-0; D2x<-0;

for (i in n:2 ) {

  c <- a
  a <- tabela[2, (y[i]/2)] + c
  Nc[i-1] <- a * tabela[1, i-1]
  A1x[i-1] <- a

  c1 <- a1
  a1 <- tabela[1, ((y1[i]+1)/2)] + c1
  Nd[i-1] <- a1 * tabela[2, i-1]
  D2x[i-1] <- a1
}

A1x[length(y)] <- 0
D2x[length(y)] <- 0
NC <- sum(Nc)
ND <- sum(Nd)

a2 <- 0; A2x <- 0; a3 <- 0; D1x <- 0; A2x[1] <- 0; D1x[1] <- 0;

for (i in 1:(n-1)) {
  c2 <- a2
  a2 <- tabela[1, ((y1[i]+1)/2)] + c2
  A2x[i+1] <- a2

  c3 <- a3
  a3 <- tabela[2, (y[i]/2)] + c3
  D1x[i+1] <- a3

}

A <- t(cbind(A1x, A2x))
D <- t(cbind(D1x,D2x))
d <- A-D
PQ <- 2*(NC-ND)

SD <- PQ / wr;

var <- 0

for (i in 1:2) {
  for (j in i:n) {

    var <- (tabela[i,j] * ((wr * d[i,j] - (PQ * (sum(tabela) - rowSums(tabela)[[i]])))^2)) + var
  }
}

sterr <- sqrt(var * 4/(wr)^4)

G1 <- sprintf("%.2f%%", 100 * SD)
St1 <- sprintf("%.2f%%", 100 * sterr)

ldate[k] <-  paste(tab[[1]][[1]])
G[[k]] <- SD
st[[k]] <- sterr

tab <- tab[-c(1,2),]
  }

selectInput("gin", "Choose date", ldate)
  })

txt <- reactive({ input$gin })
output$value <- renderText({
  paste("G is ", "\n", txt())  })

})
</code>```

"ldate" variable is a list of dates formatted as characters, while "G" and "st" are lists of numeric values.

I get a select list with dates as a result, but when I select each date I get only date and "G is" in a sentence.

What I want to get as a result when I choose a date from select list is for example:

2009-12-05

"G is 0.55"

"st is 0.08"

I don't know how to come up to with a solution.
How to put G and st inside output$value part of the code?

Edit

Here is the sample data for tab:

```<code>head(tab, 2)

        Date Category 1 2  3  4   5   6 7
1 2008-11-28    Goods 1 3 28 47 132 123 1
2                Bads 0 0  1  4   9  27 2
</code>```

答:
Here is the modified code with reactive values. Hope it helps!</p>

```<code>tab <- data.frame(Date = c("2008-11-28","", "2008-11-29",""), Category = c("Goods", "Bads", "Goods", "Bads"),
                    "1"=c(1, 0, 2, 0), "2"=c(3,0,4, 0), "3"=c(28, 1, 29, 2), "4"=c(47,4, 48, 5),
                    "5"=c(132, 9, 133, 10), "6"=c(123, 27, 124, 28), "7"=c(1, 2, 1, 2))

  ui <-  shinyUI(bootstrapPage(
    uiOutput("GD"),
    hr(),
    fluidRow(column(3, verbatimTextOutput("value")))
  ))

  server <- shinyServer(function(input, output) {

    vals <- reactiveValues(G = 0, st = 0, ldate = 0)

    output$GD <- renderUI({
      nBads <- sum(tab[nrow(tab),3:ncol(tab)])
      nGoods <- sum(tab[(nrow(tab)-1),3:ncol(tab)])
      nTotal <- nBads + nGoods

      options(warn=-1)
      Outcome_color <- 0
      G <- 0
      st <-0
      ldate <- 0
      for (k in (1:(nrow(tab)/2))) {

        tabela <- data.frame(tab[1:2,3:(ncol(tab))])
        rownames(tabela) <- c("Goods", "Bads")

        wr <- (sum(tabela)^2 - (rowSums(tabela)[[1]]^2 + rowSums(tabela)[[2]]^2))
        x <- which(tabela >= 0)
        y <- x[lapply(x,"%%",2)==0]
        y1 <- x[lapply(x,"%%",2)!=0]
        n <-length(y)

        a<-0; a1<-0; Nc<-0; A1x<-0; Nd<-0; D2x<-0;

        for (i in n:2 ) {

          c <- a
          a <- tabela[2, (y[i]/2)] + c
          Nc[i-1] <- a * tabela[1, i-1]
          A1x[i-1] <- a

          c1 <- a1
          a1 <- tabela[1, ((y1[i]+1)/2)] + c1
          Nd[i-1] <- a1 * tabela[2, i-1]
          D2x[i-1] <- a1
        }

        A1x[length(y)] <- 0
        D2x[length(y)] <- 0
        NC <- sum(Nc)
        ND <- sum(Nd)

        a2 <- 0; A2x <- 0; a3 <- 0; D1x <- 0; A2x[1] <- 0; D1x[1] <- 0;

        for (i in 1:(n-1)) {
          c2 <- a2
          a2 <- tabela[1, ((y1[i]+1)/2)] + c2
          A2x[i+1] <- a2

          c3 <- a3
          a3 <- tabela[2, (y[i]/2)] + c3
          D1x[i+1] <- a3

        }

        A <- t(cbind(A1x, A2x))
        D <- t(cbind(D1x,D2x))
        d <- A-D
        PQ <- 2*(NC-ND)

        SD <- PQ / wr;

        var <- 0

        for (i in 1:2) {
          for (j in i:n) {

            var <- (tabela[i,j] * ((wr * d[i,j] - (PQ * (sum(tabela) - rowSums(tabela)[[i]])))^2)) + var
          }
        }

        sterr <- sqrt(var * 4/(wr)^4)

        G1 <- sprintf("%.2f%%", 100 * SD)
        St1 <- sprintf("%.2f%%", 100 * sterr)

        vals$ldate[k] <-  paste(tab[[1]][[1]])
        vals$G[[k]] <- SD
        vals$st[[k]] <- sterr

        tab <- tab[-c(1,2),]
      }

      selectInput("gin", "Choose date", vals$ldate)
    })

    txt <- reactive({ input$gin })
    output$value <- renderText({
      paste0(txt(), "\n G is" ,vals$G[which(vals$ldate == input$gin )], "\n st is", vals$st[which(vals$ldate == input$gin)])
    })

  })

  shinyApp(ui=ui, server=server)
</code>```

Body:
Here is my R shiny code:

ui.R

shinyUI(bootstrapPage(
uiOutput("GD"),
hr(),
fluidRow(column(3, verbatimTextOutput("value")))
))

server.R

shinyServer(function(input, output) {

  output$GD <- renderUI({
  nBads <- sum(tab[nrow(tab),3:ncol(tab)])
  nGoods <- sum(tab[(nrow(tab)-1),3:ncol(tab)])
  nTotal <- nBads + nGoods

  options(warn=-1)
  Outcome_color <- 0
  G <- 0
  st <-0
  ldate <- 0
  for (k in (1:(nrow(tab)/2))) {

  tabela <- data.frame(tab[1:2,3:(ncol(tab))])
  rownames(tabela) <- c("Goods", "Bads")

  wr <- (sum(tabela)^2 - (rowSums(tabela)[[1]]^2 + rowSums(tabela)[[2]]^2))
x <- which(tabela >= 0)
y <- x[lapply(x,"%%",2)==0]
y1 <- x[lapply(x,"%%",2)!=0]
n <-length(y)

a<-0; a1<-0; Nc<-0; A1x<-0; Nd<-0; D2x<-0;

for (i in n:2 ) {

  c <- a
  a <- tabela[2, (y[i]/2)] + c
  Nc[i-1] <- a * tabela[1, i-1]
  A1x[i-1] <- a

  c1 <- a1
  a1 <- tabela[1, ((y1[i]+1)/2)] + c1
  Nd[i-1] <- a1 * tabela[2, i-1]
  D2x[i-1] <- a1
}

A1x[length(y)] <- 0
D2x[length(y)] <- 0
NC <- sum(Nc)
ND <- sum(Nd)

a2 <- 0; A2x <- 0; a3 <- 0; D1x <- 0; A2x[1] <- 0; D1x[1] <- 0;

for (i in 1:(n-1)) {
  c2 <- a2
  a2 <- tabela[1, ((y1[i]+1)/2)] + c2
  A2x[i+1] <- a2

  c3 <- a3
  a3 <- tabela[2, (y[i]/2)] + c3
  D1x[i+1] <- a3

}

A <- t(cbind(A1x, A2x))
D <- t(cbind(D1x,D2x))
d <- A-D
PQ <- 2*(NC-ND)

SD <- PQ / wr;

var <- 0

for (i in 1:2) {
  for (j in i:n) {

    var <- (tabela[i,j] * ((wr * d[i,j] - (PQ * (sum(tabela) - rowSums(tabela)[[i]])))^2)) + var
  }
}

sterr <- sqrt(var * 4/(wr)^4)

G1 <- sprintf("%.2f%%", 100 * SD)
St1 <- sprintf("%.2f%%", 100 * sterr)

ldate[k] <-  paste(tab[[1]][[1]])
G[[k]] <- SD
st[[k]] <- sterr

tab <- tab[-c(1,2),]
  }

selectInput("gin", "Choose date", ldate)
  })

txt <- reactive({ input$gin })
output$value <- renderText({
  paste("G is ", "\n", txt())  })

})

"ldate" variable is a list of dates formatted as characters, while "G" and "st" are lists of numeric values.

I get a select list with dates as a result, but when I select each date I get only date and "G is" in a sentence.

What I want to get as a result when I choose a date from select list is for example:

2009-12-05

"G is 0.55"

"st is 0.08"

I don't know how to come up to with a solution.
How to put G and st inside output$value part of the code?

Edit

Here is the sample data for tab:

head(tab, 2)

        Date Category 1 2  3  4   5   6 7
1 2008-11-28    Goods 1 3 28 47 132 123 1
2                Bads 0 0  1  4   9  27 2

Body:
Here is the modified code with reactive values. Hope it helps!

tab <- data.frame(Date = c("2008-11-28","", "2008-11-29",""), Category = c("Goods", "Bads", "Goods", "Bads"),
                    "1"=c(1, 0, 2, 0), "2"=c(3,0,4, 0), "3"=c(28, 1, 29, 2), "4"=c(47,4, 48, 5),
                    "5"=c(132, 9, 133, 10), "6"=c(123, 27, 124, 28), "7"=c(1, 2, 1, 2))

  ui <-  shinyUI(bootstrapPage(
    uiOutput("GD"),
    hr(),
    fluidRow(column(3, verbatimTextOutput("value")))
  ))

  server <- shinyServer(function(input, output) {

    vals <- reactiveValues(G = 0, st = 0, ldate = 0)

    output$GD <- renderUI({
      nBads <- sum(tab[nrow(tab),3:ncol(tab)])
      nGoods <- sum(tab[(nrow(tab)-1),3:ncol(tab)])
      nTotal <- nBads + nGoods

      options(warn=-1)
      Outcome_color <- 0
      G <- 0
      st <-0
      ldate <- 0
      for (k in (1:(nrow(tab)/2))) {

        tabela <- data.frame(tab[1:2,3:(ncol(tab))])
        rownames(tabela) <- c("Goods", "Bads")

        wr <- (sum(tabela)^2 - (rowSums(tabela)[[1]]^2 + rowSums(tabela)[[2]]^2))
        x <- which(tabela >= 0)
        y <- x[lapply(x,"%%",2)==0]
        y1 <- x[lapply(x,"%%",2)!=0]
        n <-length(y)

        a<-0; a1<-0; Nc<-0; A1x<-0; Nd<-0; D2x<-0;

        for (i in n:2 ) {

          c <- a
          a <- tabela[2, (y[i]/2)] + c
          Nc[i-1] <- a * tabela[1, i-1]
          A1x[i-1] <- a

          c1 <- a1
          a1 <- tabela[1, ((y1[i]+1)/2)] + c1
          Nd[i-1] <- a1 * tabela[2, i-1]
          D2x[i-1] <- a1
        }

        A1x[length(y)] <- 0
        D2x[length(y)] <- 0
        NC <- sum(Nc)
        ND <- sum(Nd)

        a2 <- 0; A2x <- 0; a3 <- 0; D1x <- 0; A2x[1] <- 0; D1x[1] <- 0;

        for (i in 1:(n-1)) {
          c2 <- a2
          a2 <- tabela[1, ((y1[i]+1)/2)] + c2
          A2x[i+1] <- a2

          c3 <- a3
          a3 <- tabela[2, (y[i]/2)] + c3
          D1x[i+1] <- a3

        }

        A <- t(cbind(A1x, A2x))
        D <- t(cbind(D1x,D2x))
        d <- A-D
        PQ <- 2*(NC-ND)

        SD <- PQ / wr;

        var <- 0

        for (i in 1:2) {
          for (j in i:n) {

            var <- (tabela[i,j] * ((wr * d[i,j] - (PQ * (sum(tabela) - rowSums(tabela)[[i]])))^2)) + var
          }
        }

        sterr <- sqrt(var * 4/(wr)^4)

        G1 <- sprintf("%.2f%%", 100 * SD)
        St1 <- sprintf("%.2f%%", 100 * sterr)

        vals$ldate[k] <-  paste(tab[[1]][[1]])
        vals$G[[k]] <- SD
        vals$st[[k]] <- sterr

        tab <- tab[-c(1,2),]
      }

      selectInput("gin", "Choose date", vals$ldate)
    })

    txt <- reactive({ input$gin })
    output$value <- renderText({
      paste0(txt(), "\n G is" ,vals$G[which(vals$ldate == input$gin )], "\n st is", vals$st[which(vals$ldate == input$gin)])
    })

  })

  shinyApp(ui=ui, server=server)


问:
Python-3.x Count the frequency of a specific number from user input
I'm trying to make a program that will output how many times the number 7 appears from a series of numbers (of no particular range) inputted by the user. Each number would be a separate input, not as one.

I have searched far and wide but the solutions I found involved letters, words, or numbers from pre-made lists rather than int from user input and errored when I tried to modify for purpose. I'm sure I'm missing something really obvious but I can't figure out how to do this.

(I tried Counter, if num == 100, count(100), for i in range, etc etc - but I'm clearly on the wrong path)

My starting point was trying to modify this one that prints the highest number because I am aiming for a similar format:

```<code>x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))
</code>```

Thank you for any advice with this.

答:
you can use the below code sample. It expects the first input as the number which you want to search in the list. Followed by list of number each on a separate line.</p>

```<code>x = 0
done = False
count = 0
i = input("Which number to search: ")
print("Enter list of numbers to search number",i,", enter each on separate line and 0 to end): ")
while not done:
        j = input()
        num = int(j)
        if int(j) == 0 :
                print("exitting")
                break
        else:
                if j == i:
                        count += 1
print("Found number",i,"for",count,"number of times")
</code>```

Body:
I'm trying to make a program that will output how many times the number 7 appears from a series of numbers (of no particular range) inputted by the user. Each number would be a separate input, not as one.

I have searched far and wide but the solutions I found involved letters, words, or numbers from pre-made lists rather than int from user input and errored when I tried to modify for purpose. I'm sure I'm missing something really obvious but I can't figure out how to do this.

(I tried Counter, if num == 100, count(100), for i in range, etc etc - but I'm clearly on the wrong path)

My starting point was trying to modify this one that prints the highest number because I am aiming for a similar format:

x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))

Thank you for any advice with this.

Body:
you can use the below code sample. It expects the first input as the number which you want to search in the list. Followed by list of number each on a separate line.

x = 0
done = False
count = 0
i = input("Which number to search: ")
print("Enter list of numbers to search number",i,", enter each on separate line and 0 to end): ")
while not done:
        j = input()
        num = int(j)
        if int(j) == 0 :
                print("exitting")
                break
        else:
                if j == i:
                        count += 1
print("Found number",i,"for",count,"number of times")


问:
Allow unauthenticated users to access views that utilize current_user
I have lots of views that have elements that check if the current user isn't the same user that's being viewed, etc. For example, on the user show page there is a button that allows a user to follow another user, which doesn't appear if the user is looking at their own profile.

```<code><% if current_user != @user %>
  <div id="follow_form">
    <% if current_user.following?(@user) %>
      <%= render 'users/unfollow' %>
    <% else %>
      <%= render 'users/follow' %>
    <% end %>
  </div>
<% end %>
</code>```

The problem arises that if you're not logged in, rails throws an error.

```<code>undefined method `id' for nil:NilClass

  <% if current_user.id == @user.id %>
    <%= link_to "Edit Profile", edit_user_registration_path(@user) %>
  <% else %>
    <%= link_to 'message', new_message_path(receiver_id: @user.id) %>
  ...
</code>```

I don't want to have to force people to log in or sign up to view index or show pages. How can I get around this?

答:
You should try that: </p>

```<code><% if user_signed_in? %>
 <% if current_user != @user %>
  <div id="follow_form">
    <% if current_user.following?(@user) %>
      <%= render 'users/unfollow' %>
    <% else %>
      <%= render 'users/follow' %>
    <% end %>
  </div>
 <% end %>
<% end %>
</code>```

Body:
I have lots of views that have elements that check if the current user isn't the same user that's being viewed, etc. For example, on the user show page there is a button that allows a user to follow another user, which doesn't appear if the user is looking at their own profile.

<% if current_user != @user %>

    <% if current_user.following?(@user) %>
      <%= render 'users/unfollow' %>
    <% else %>
      <%= render 'users/follow' %>
    <% end %>

<% end %>

The problem arises that if you're not logged in, rails throws an error.

undefined method `id' for nil:NilClass

  <% if current_user.id == @user.id %>
    <%= link_to "Edit Profile", edit_user_registration_path(@user) %>
  <% else %>
    <%= link_to 'message', new_message_path(receiver_id: @user.id) %>
  ...

I don't want to have to force people to log in or sign up to view index or show pages. How can I get around this?

Body:
You should try that:

<% if user_signed_in? %>
 <% if current_user != @user %>
  <div id="follow_form">
    <% if current_user.following?(@user) %>
      <%= render 'users/unfollow' %>
    <% else %>
      <%= render 'users/follow' %>
    <% end %>
  </div>
 <% end %>
<% end %>


问:
Angular JS render JSON in tree like format
How do I render JSON in tree like way just like http://jsonviewer.stack.hu/ does using angular JS?</p>

答:
I wrote a function to display a JSON data in the angular-ui-tree component.

The key point is the following:

In your parse routine, keep the 'JSON string' of the current node in the node itself, every 'not parsed' node has this payload and a 'load' function.

```<code>function parse(name, value) {

  var node = {
    name: name
  };

  if (Array.isArray(value)) {
    node.isEmpty = value.length === 0;
    node.payload = value;
    node.props = [];
    node.load = function(node) {
      for (var i = 0; i < node.payload.length; i++) {
        node.props.push(parse(node.name + '[' + i + ']', node.payload[i]));
      }
      delete node.isEmpty;
      delete node.payload;
    }
  } else if (value !== undefined && value !== null && typeof value === 'object') {
    node.isEmpty = Object.keys(value).length === 0;
    node.payload = value;
    node.props = [];
    node.load = function(node) {
      var keys = Object.keys(node.payload);
      for (var i = 0; i < keys.length; i++) {
        node.props.push(parse(node.name + '.' + keys[i], node.payload[keys[i]]));
      }
      delete node.isEmpty;
      delete node.payload;
    }
  } else {
    node.value = value;
  }

  return node;
}
</code>```

Then, when the user click on the toggle button you can call this function to parse the next nodes in the tree and bind tha data to the HTML.

Can be more clear with a example:
https://jsfiddle.net/MatteoTosato/ghm4z606/

Body:
I wrote a function to display a JSON data in the angular-ui-tree component.

The key point is the following:

In your parse routine, keep the 'JSON string' of the current node in the node itself, every 'not parsed' node has this payload and a 'load' function.

function parse(name, value) {

  var node = {
    name: name
  };

  if (Array.isArray(value)) {
    node.isEmpty = value.length === 0;
    node.payload = value;
    node.props = [];
    node.load = function(node) {
      for (var i = 0; i < node.payload.length; i++) {
        node.props.push(parse(node.name + '[' + i + ']', node.payload[i]));
      }
      delete node.isEmpty;
      delete node.payload;
    }
  } else if (value !== undefined && value !== null && typeof value === 'object') {
    node.isEmpty = Object.keys(value).length === 0;
    node.payload = value;
    node.props = [];
    node.load = function(node) {
      var keys = Object.keys(node.payload);
      for (var i = 0; i < keys.length; i++) {
        node.props.push(parse(node.name + '.' + keys[i], node.payload[keys[i]]));
      }
      delete node.isEmpty;
      delete node.payload;
    }
  } else {
    node.value = value;
  }

  return node;
}

Then, when the user click on the toggle button you can call this function to parse the next nodes in the tree and bind tha data to the HTML.

Can be more clear with a example:
https://jsfiddle.net/MatteoTosato/ghm4z606/


问:
Angular 2+ one-time binding
In angular 1 we could do one time binding in this way: {{ ::myFunction() }}.

In angular 2 this is throwing:

```<code>EXCEPTION: Template parse errors:
Parser Error: Unexpected token : at column 2 in [{{ ::consent(false, undefined, box) }}] in CookieConsent@5:29 ("ull-right" href="" (click)="consent(true, $event, box)">De acuerdo</a>
        <span class="hidden">[ERROR ->]{{ ::consent(false, undefined, box) }}</span>
</code>```

How can we do one time binding in angular2?

答:
ChangeDetectionStrategy.CheckOnce is the solution for this problem.

This has been updated to OnPush see also comment in code:

```<code>export declare enum ChangeDetectionStrategy {
    /**
     * `OnPush` means that the change detector's mode will be set to `CheckOnce` during hydration.
     */
    OnPush = 0,
    /**
     * `Default` means that the change detector's mode will be set to `CheckAlways` during hydration.
     */
    Default = 1,
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular 2+ one-time binding

Body:
In angular 1 we could do one time binding in this way: {{ ::myFunction() }}.

In angular 2 this is throwing:

EXCEPTION: Template parse errors:
Parser Error: Unexpected token : at column 2 in [{{ ::consent(false, undefined, box) }}] in CookieConsent@5:29 ("ull-right" href="" (click)="consent(true, $event, box)">De acuerdo
        [ERROR ->]{{ ::consent(false, undefined, box) }}

How can we do one time binding in angular2?

Body:
ChangeDetectionStrategy.CheckOnce is the solution for this problem.

This has been updated to OnPush see also comment in code:

export declare enum ChangeDetectionStrategy {
    /**
     * `OnPush` means that the change detector's mode will be set to `CheckOnce` during hydration.
     */
    OnPush = 0,
    /**
     * `Default` means that the change detector's mode will be set to `CheckAlways` during hydration.
     */
    Default = 1,
}


问:
Android emulator access to IPv6 possible? Network is unreachable
I am running an Android 4.0 emulator on windows 7 with a valid global ipv6 address. The emulator can access the ipv4 of the host machine addresses but not the ipv6 address. Pinging the ipv6 address from a third party site works.

Is there some magic trick to tell the emulator to use IPv6 as well? The emulator hasn't really got a lot of configuration options.

I always get the message "Network is unreachable".

答:
Starting from SDK 25.3.0 running Android Emulator in IPv6-only environment is finally supported. I tested with Android emulator version 26.0.3.0 running in Docker container with IPv6-only host. The main thing you need to know to do the trick is that it is only supported with emulator command and not supported e.g. for emulator64-x86 command. So the following will work:

```<code>$ emulator -avd android6.0-1 -sdcard /200MB.img ...
</code>```

... and the following will not:

```<code>$ emulator64-x86 -avd android6.0-1 -sdcard /200MB.img ...
</code>```

Hope it helps somebody.

Body:
Starting from SDK 25.3.0 running Android Emulator in IPv6-only environment is finally supported. I tested with Android emulator version 26.0.3.0 running in Docker container with IPv6-only host. The main thing you need to know to do the trick is that it is only supported with emulator command and not supported e.g. for emulator64-x86 command. So the following will work:

$ emulator -avd android6.0-1 -sdcard /200MB.img ...

... and the following will not:

$ emulator64-x86 -avd android6.0-1 -sdcard /200MB.img ...

Hope it helps somebody.


问:
I got syntax error in update statement.Run-time error: 3144 I am using the following code

Dim strMyTable As String
Dim strMyField As String
Dim strMyCombo As Boolean
Dim strSQL As String
strMyTable = "ItemDetails"  '(or whatever the true names are...)
strMyField = "Chk"
strMyCombo = False
strSQL = "UPDATE " & strMyTable _ & "SET " & strMyField & "=" & strMyCombo & ";"
Application.CurrentDb.Execute strSQL
End Sub
```

答:
Try this:</p>

```<code>Dim strMyTable As String
Dim strMyField As String
Dim strMyCombo As String
Dim strSQL As String

strMyTable = "ItemDetails"  '(or whatever the true names are...)
strMyField = "Chk"
strMyCombo = "False"
strSQL = "UPDATE " & strMyTable & " SET " & strMyField & "=" & strMyCombo & ";"
Application.CurrentDb.Execute strSQL
</code>```

Body:
Try this:

Dim strMyTable As String
Dim strMyField As String
Dim strMyCombo As String
Dim strSQL As String

strMyTable = "ItemDetails"  '(or whatever the true names are...)
strMyField = "Chk"
strMyCombo = "False"
strSQL = "UPDATE " & strMyTable & " SET " & strMyField & "=" & strMyCombo & ";"
Application.CurrentDb.Execute strSQL


问:
How to make circular buttons with Font Awesome icons (and hover effect)?
I am trying to create buttons like the picture below.

I am using stacked Font Awesome icons to put the icons on top of a circle and it looks like this:

(Ignore the gray line at the bottom.  That's a result of poor screenshotting.)

However, as you can see, the icons are a tiny bit off.  Ideally, I want to push them up a bit so they are vertically centered in the circle and either make the circles bigger or the icons smaller to get the nice padding as in the example.  I also want to change the color of the circle which I don't know how to do and add hover effects (like change the icon to white).

Here is my code.

.footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<div class="row footer">
  <!-- FOOTER -->
  <div class="col-md-4"></div>
  <div class="col-md-4 text-center" id="copyright">
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
    </span>

    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-envelope-o fa-stack-1x fa-inverse" aria-hidden="true"></i>
    </span>
  </div>
</div></code>```

答:
For the first problem, you can use CSS line-height

```<code>span.fa-stack {
  line-height: 37px;
}
</code>```

As for the second problem, you can apply font-size to FA icons, like this:

```<code>span.fa-stack > i:nth-of-type(2) {
  font-size: 13px; /* Or whatever value looks best */
}
</code>```

Or if you wanted, you could even use transform: scale(); again:

```<code>span.fa-stack > i:nth-of-type(2) {
  transform: scale(0.8); /* Or whatever value looks best */
}
</code>```

For the :hover effect, you could use transform: scale();, which I belive is the best hover effect, along-side cursor: pointer;:

```<code>span.fa-stack:hover {
  transform: scale(1.3); /* Or whatever value looks best */
  cursor: pointer;
}
</code>```

And for applying color to the circle, it's a simple as this:

```<code>span.fa-stack:nth-of-type(1) {
  color: #2D79AF; /* Or whatever color looks best */
}
</code>```

.footer {
  position: fixed;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
  display: table;
  align-items: center;
}
span.fa-stack:hover {
  transform: scale(1.3);
  cursor: pointer;
}
span.fa-stack {
  line-height: 36px;
}
span.fa-stack:nth-of-type(1) {
  color: #2D79AF;
}
span.fa-stack > i:nth-of-type(2) {
  font-size: 14px;
}
#copyright {
  padding-top: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="row footer">
<!-- FOOTER -->
  <div class="col-md-4"></div>
  <div class="col-md-4 text-center" id="copyright">
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
    </span>
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-envelope-o fa-stack-1x fa-inverse" aria-hidden="true"></i>
    </span>
  </div>
</div></code>```

The icons are just text anyway.

Body:
I am trying to create buttons like the picture below.

I am using stacked Font Awesome icons to put the icons on top of a circle and it looks like this:

(Ignore the gray line at the bottom.  That's a result of poor screenshotting.)

However, as you can see, the icons are a tiny bit off.  Ideally, I want to push them up a bit so they are vertically centered in the circle and either make the circles bigger or the icons smaller to get the nice padding as in the example.  I also want to change the color of the circle which I don't know how to do and add hover effects (like change the icon to white).

Here is my code.

.footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
}

<link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>

Body:
For the first problem, you can use CSS line-height

span.fa-stack {
  line-height: 37px;
}

As for the second problem, you can apply font-size to FA icons, like this:

span.fa-stack > i:nth-of-type(2) {
  font-size: 13px; /* Or whatever value looks best */
}

Or if you wanted, you could even use transform: scale(); again:

span.fa-stack > i:nth-of-type(2) {
  transform: scale(0.8); /* Or whatever value looks best */
}

For the :hover effect, you could use transform: scale();, which I belive is the best hover effect, along-side cursor: pointer;:

span.fa-stack:hover {
  transform: scale(1.3); /* Or whatever value looks best */
  cursor: pointer;
}

And for applying color to the circle, it's a simple as this:

span.fa-stack:nth-of-type(1) {
  color: #2D79AF; /* Or whatever color looks best */
}

.footer {
  position: fixed;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
  display: table;
  align-items: center;
}
span.fa-stack:hover {
  transform: scale(1.3);
  cursor: pointer;
}
span.fa-stack {
  line-height: 36px;
}
span.fa-stack:nth-of-type(1) {
  color: #2D79AF;
}
span.fa-stack > i:nth-of-type(2) {
  font-size: 14px;
}
#copyright {
  padding-top: 6px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="row footer">
<!-- FOOTER -->
  <div class="col-md-4"></div>
  <div class="col-md-4 text-center" id="copyright">
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
    </span>
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-envelope-o fa-stack-1x fa-inverse" aria-hidden="true"></i>
    </span>
  </div>
</div>

The icons are just text anyway.