问:
What is the easiest/most effective way to learn Delphi?
I am totally new to programming and I have chosen Delphi as the programming language that I would like to learn.

I basically want to build tools that will fill and submit web forms using sockets and I want them to be multi threaded as well.

I would love for them to be feature rich and perform correctly.

I am in no real rush to do this as I do understand that it takes time to become efficient at anything (especially programming). However, I do want to take the shortest path that I can in learning.

If it were possible I would love to go to school to learn the language but it seems like there are no schools in the US that teach it.

I have found quite a good bit of information on the internet that has helped me gain a basic knowledge of how things work inside the IDE and how to build basic apps but I want to be able to build really good apps that these tutorial do not teach me how to do.

So.. My question is how do I go about becoming an expert Delphi programmer without having any "Real Teacher" to guide me? How did you guys learn?

Would learning another programming language with the help of a teacher and them coming back to delphi make sense?

答:
A couple years ago I tried to learn Delphi and then gave up in frustration.  I was learning on my own and had a difficult time with the incomplete docs and few current books.  In hindsight, outdated books weren't as problematic as the more current books because the more current books are written for an audience that knows both Pascal and Delphi and thus leave out a lot of crucial info for the newbie.  I was working on porting a VB6 project and ended up using .Net which was more familiar given my experience in VB and Java.

Just recently I had to write a quick little utility that needed some direct Win32 functionality and I thought it would be a good project for Delphi.  Small, fast, Win32.  I dusted off my license and started poking around again.  In the intervening years I've learned a few more languages and was less stumped by the Pascal syntax than my previous attempt.  In a few hours I had finished my task and I decided to try to learn a little more.

So far, I've been really impressed with the Delphi 5 Developer Guide.  It has opened my eyes to the elegance of the VCL and Delphi.  There are more recent versions, but I think this one is perhaps the best because it deals with a version of Delphi before the now defunct Kylix project.  Books that are written for version 6 thru 2006 spend way too much time describing either Kylix or Delphi.Net, both of which are dead and useless to spend time learning.  The Delphi 5 books are equally as long as later editions, but spend all of those pages on the Win32 features of the VCL and some very valuable tutorials on Pascal (which is handy for those of us that went through our school years without learning Pascal).

How do you learn any of the new stuff that has happened since Delphi 5?  I think Bob Swart's short update books are probably best.  You can find them here.  A lot of folks like Marco Cantu's books as well, but I personally haven't found his books very useful.

Good luck!  I look forward to reading more suggestions.


来源: stackexchange

问:
How can I sure my background colour fills whole webpage background?
I was wondering how I can ensure that section 1 and two's background colour fills the whole of the webpage like in this example. As you can see on my site, the background colour on covers half of the webpage I want the background colour for section one and two to full the whole background of that section.

I have tried using the CSS. However, this doesn't work.

```<code>.one {
  background-color:#c00;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
  width: 100%;
}
</code>```

SITE CODE

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<style>
.body {
  font-family: 'Roboto', sans-serif;
  color: black;
}
.navbar.navbar-default {
  background-color: #FFFFFF;
  height: 10vh;
  z-index: 100;
}

.navbar.navbar-default ul {
  list-style-type: none;
  text-align: center;
}

.navbar.navbar-default ul li {
  display: inline-block;
}

.dropdown-menu li {
  text-align: center;
}

.dropdown .dropdown-menu {
  background-color: #FFFFFF;
}

.dropdown .dropdown-menu a {
  color: white;
}

.navbar.navbar-default ul li a {
  display: inline-block;
  padding: 3.5vh 8px 4px;
  color: black;
  text-decoration: none;
  font-size: 14pt;
  font-family: 'Roboto', sans-serif;
}

.navbar.navbar-default ul li:after {
  content: '';
  position: absolute;
  right: 50%;
  bottom: 0;
  left: 50%;
  height: 3px;
  background-color: black;
  border-radius: 9px;
  transition: all .2s;
}

.nav.navbar-nav,
.nav.navbar-nav>li {
  float: none;
}

.navbar.navbar-default ul li:hover:after {
  right: 0;
  left: 0;
}

.navbar.navbar-default ul.dropdown-menu li,
.navbar.navbar-default ul.dropdown-menu li a {
  position: relative;
  display: block;
}

.one {
  background-color:#c00;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
  width: 100%;
}

.two {
  background: #563D7C;
}
</style>
<body>
  <div class="container">
    <nav class="navbar navbar-default navbar-fixed-top">
       <div class="container-fluid">
         <!-- Brand and toggle get grouped for better mobile display -->
         <div class="navbar-header">
           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                           <span class="sr-only">Toggle navigation</span>
                           <span class="icon-bar"></span>
                           <span class="icon-bar"></span>
                           <span class="icon-bar"></span>
           </button>
         </div>
         <!-- Collect the nav links, forms, and other content for toggling -->
         <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
           <ul class="nav navbar-nav">
             <li><a href="#">Home</a>
             </li>
             <li class="dropdown">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">About Me <span class="caret"></span></a>
               <ul class="dropdown-menu">
                 <li><a href="#">Action</a>
                 </li>
                 <li><a href="#section3">Contact</a>
                 </li>
                 <li><a href="#">Something else here</a>
                 </li>
                 <li><a href="#">Separated link</a>
                 </li>
                 <li><a href="#">One more separated link</a>
                 </li>
               </ul>
             </li>
             <li class="dropdown">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Units <span class="caret"></span></a>
               <ul class="dropdown-menu">
                 <li><a href="#">Action</a>
                 </li>
                 <li><a href="#">Another action</a>
                 </li>
                 <li><a href="#">Something else here</a>
                 </li>
                 <li><a href="#">Separated link</a>
                 </li>

                 <li><a href="#">One more separated link</a>
                 </li>
               </ul>
             </li>
             <li><a href="#">Clients</a>
             </li>
             <li><a href="#contact-me">Contact Me</a>
             </li>
           </ul>
         </div>
         <!-- /.navbar-collapse -->
       </div>
       <!-- /.container-fluid -->
     </nav>
     <div id="sections">
            <div class="section one">
              <div class="jumbotron text-center">
                <h1>My First Bootstrap Page</h1>
                <p>Resize this responsive page to see the effect!</p>
              </div>

            <a href="#section two"> <i class="fa fa-angle-down" style="font-size:100px;"></i></a>

            </div>
            <div class="section two"></div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>

        <script>
            $(document).ready(function() {
                $('#sections').fullpage();
            });
        </script>

</body>
</html>
</code>```

答:
It looks like you are loading jQuery twice. Once in the header (in the Bootstrap links) and once in the footer, for fullpage.js. Since you already loaded it once, you don't need it the second time.

Wrapping all your content in a .container will add a 15px left and right padding to your content, unless you don't place everything in it inside .row (which compensates), as in all the Bootstrap examples.

Make sure your markup is correct and validates. I also added a small CSS:

```<code>#sections .section {
  padding-top: 10vh;
}
</code>```

...to compensate for the height of the navbar.

However, please note it is not recommended to have the navbar in scalable units(vh). You should just stick to Bootstrap's defaults (50px). The problem with having a fixed navigation of 10vh is it will eat up too much real estate on mobile devices in portrait mode while not being tall enough for touch events in landscape mode. So, IMHO, you should change both the top padding of the .sections and the navbar height back to ~50px (min 42px). The important part is you should use px instead of vh for navbar height.

Here it is:

$(document).ready(function() {
  $('#sections').fullpage();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.body {
  font-family: 'Roboto', sans-serif;
  color: black;
}
.navbar.navbar-default {
  background-color: #FFFFFF;
  height: 10vh;
  z-index: 100;
}

.navbar.navbar-default ul {
  list-style-type: none;
  text-align: center;
}

.navbar.navbar-default ul li {
  display: inline-block;
}

.dropdown-menu li {
  text-align: center;
}

.dropdown .dropdown-menu {
  background-color: #FFFFFF;
}

.dropdown .dropdown-menu a {
  color: white;
}

.navbar.navbar-default ul li a {
  display: inline-block;
  padding: 3.5vh 8px 4px;
  color: black;
  text-decoration: none;
  font-size: 14pt;
  font-family: 'Roboto', sans-serif;
}

.navbar.navbar-default ul li:after {
  content: '';
  position: absolute;
  right: 50%;
  bottom: 0;
  left: 50%;
  height: 3px;
  background-color: black;
  border-radius: 9px;
  transition: all .2s;
}

.nav.navbar-nav,
.nav.navbar-nav>li {
  float: none;
}

.navbar.navbar-default ul li:hover:after {
  right: 0;
  left: 0;
}

.navbar.navbar-default ul.dropdown-menu li,
.navbar.navbar-default ul.dropdown-menu li a {
  position: relative;
  display: block;
}

.one {
  background-color:#c00;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
  width: 100%;
}

.two {
  background: #563D7C;
}
#sections .section {
  padding-top: 10vh;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

Home

                    About Me

Action

Contact

Something else here

Separated link

One more separated link

                    Units

Action

Another action

Something else here

Separated link

One more separated link

Clients

Contact Me

My First Bootstrap Page

Resize this responsive page to see the effect!

```
</div>
</div>
</p>

<hr>

<p><strong>Additional note:</strong></p>

<p><code>fullpage.js</code> takes care of the fullpage thing for you. However, I happen to believe this is something <code>CSS</code> is capable of doing without any <code>js</code>, using, in principle:</p>

```.section {
   min-height: 100vh;
}
```

...and probably flexbox to center align or distribute children nicely.

But, by using fullpage.js, you don't need to do it via CSS.

ContentLicense: CC BY-SA 3.0

Body:
I was wondering how I can ensure that section 1 and two's background colour fills the whole of the webpage like in this example. As you can see on my site, the background colour on covers half of the webpage I want the background colour for section one and two to full the whole background of that section.

I have tried using the CSS. However, this doesn't work.

.one {
  background-color:#c00;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
  width: 100%;
}

SITE CODE

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                           Toggle navigation

           </button>

Home

               About Me

Action

Contact

Something else here

Separated link

One more separated link

               Units

Action

Another action

Something else here

Separated link

One more separated link

Clients

Contact Me

My First Bootstrap Page

Resize this responsive page to see the effect!

Body:
It looks like you are loading jQuery twice. Once in the header (in the Bootstrap links) and once in the footer, for fullpage.js. Since you already loaded it once, you don't need it the second time.

Wrapping all your content in a .container will add a 15px left and right padding to your content, unless you don't place everything in it inside .row (which compensates), as in all the Bootstrap examples.

Make sure your markup is correct and validates. I also added a small CSS:

#sections .section {
  padding-top: 10vh;
}

...to compensate for the height of the navbar.

However, please note it is not recommended to have the navbar in scalable units(vh). You should just stick to Bootstrap's defaults (50px). The problem with having a fixed navigation of 10vh is it will eat up too much real estate on mobile devices in portrait mode while not being tall enough for touch events in landscape mode. So, IMHO, you should change both the top padding of the .sections and the navbar height back to ~50px (min 42px). The important part is you should use px instead of vh for navbar height.

Here it is:

$(document).ready(function() {
  $('#sections').fullpage();
});

.body {
  font-family: 'Roboto', sans-serif;
  color: black;
}
.navbar.navbar-default {
  background-color: #FFFFFF;
  height: 10vh;
  z-index: 100;
}

.navbar.navbar-default ul {
  list-style-type: none;
  text-align: center;
}

.navbar.navbar-default ul li {
  display: inline-block;
}

.dropdown-menu li {
  text-align: center;
}

.dropdown .dropdown-menu {
  background-color: #FFFFFF;
}

.dropdown .dropdown-menu a {
  color: white;
}

.navbar.navbar-default ul li a {
  display: inline-block;
  padding: 3.5vh 8px 4px;
  color: black;
  text-decoration: none;
  font-size: 14pt;
  font-family: 'Roboto', sans-serif;
}

.navbar.navbar-default ul li:after {
  content: '';
  position: absolute;
  right: 50%;
  bottom: 0;
  left: 50%;
  height: 3px;
  background-color: black;
  border-radius: 9px;
  transition: all .2s;
}

.nav.navbar-nav,
.nav.navbar-nav>li {
  float: none;
}

.navbar.navbar-default ul li:hover:after {
  right: 0;
  left: 0;
}

.navbar.navbar-default ul.dropdown-menu li,
.navbar.navbar-default ul.dropdown-menu li a {
  position: relative;
  display: block;
}

.one {
  background-color:#c00;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
  width: 100%;
}

.two {
  background: #563D7C;
}
#sections .section {
  padding-top: 10vh;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>

<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="#">Home</a>
                </li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">About Me <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">Action</a>
                        </li>
                        <li><a href="#section3">Contact</a>
                        </li>
                        <li><a href="#">Something else here</a>
                        </li>
                        <li><a href="#">Separated link</a>
                        </li>
                        <li><a href="#">One more separated link</a>
                        </li>
                    </ul>
                </li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Units <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">Action</a>
                        </li>
                        <li><a href="#">Another action</a>
                        </li>
                        <li><a href="#">Something else here</a>
                        </li>
                        <li><a href="#">Separated link</a>
                        </li>

                        <li><a href="#">One more separated link</a>
                        </li>
                    </ul>
                </li>
                <li><a href="#">Clients</a>
                </li>
                <li><a href="#contact-me">Contact Me</a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
</nav>
<div id="sections">
    <div class="section one">
        <div class="jumbotron text-center">
            <h1>My First Bootstrap Page</h1>
            <p>Resize this responsive page to see the effect!</p>
        </div>
        <a href="#section two"> <i class="fa fa-angle-down" style="font-size:100px;"></i></a>
    </div>
    <div class="section two"></div>
</div>

Additional note:

fullpage.js takes care of the fullpage thing for you. However, I happen to believe this is something CSS is capable of doing without any js, using, in principle:

.section {
   min-height: 100vh;
}

...and probably flexbox to center align or distribute children nicely.

But, by using fullpage.js, you don't need to do it via CSS.


问:
How to list object's array properties by sorted?
Each user has some professionals in array:

```<code>users  idxxx
           -A
           -prof: name: x
                  name: y
       idyyy
           -B
           -prof: name :y
                  name :z
                  name :x
</code>```

how to sort prof arrays lists by name order.

something like:

```<code>prof list:
x (2)
y (2)
z (1)
</code>```

答:
You should denormalize your data model, i.e. create a dedicated extra "proflist" node in your database where you will increment the number of the corresponding profession(s) when you create a new user.

Actually it corresponds to the way you have explained your problem.

Better use a transaction as detailed here https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

Body:
Each user has some professionals in array:

users  idxxx
           -A
           -prof: name: x
                  name: y
       idyyy
           -B
           -prof: name :y
                  name :z
                  name :x

how to sort prof arrays lists by name order.

something like:

prof list:
x (2)
y (2)
z (1)


问:
String in list, into a function
```<code>myList = ['100', 'sin(x)', '0', '1']
</code>```

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

```<code>myList[1].replace("'", "")
</code>```

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

```<code>from math import sin
def f(x):
    return myList[1]
</code>```

Thus f(x) will give the computed value of sin(x) from this list.

答:
The safest way I can see to do this is to store the expected functions in a dictionary like this:

```<code>math_dict = {'sin(x)':sin, 'cos(x)':cos}
</code>```

then you can call sin from the list like this:

```<code>def f(x):
    return math_dict[myList[1]](x)
</code>```

I just added cos(x) to show you can do this with any arbitrary function. You could then do something like this to generalize it:

```<code>def f(x):
    return math_dict[x] if x in math_dict else None
</code>```

Title: String in list, into a function

Body:
myList = ['100', 'sin(x)', '0', '1']

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

myList[1].replace("'", "")

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

from math import sin
def f(x):
    return myList[1]

Thus f(x) will give the computed value of sin(x) from this list.

Body:
The safest way I can see to do this is to store the expected functions in a dictionary like this:

math_dict = {'sin(x)':sin, 'cos(x)':cos}

then you can call sin from the list like this:

def f(x):
    return math_dict[myList[1]](x)

I just added cos(x) to show you can do this with any arbitrary function. You could then do something like this to generalize it:

def f(x):
    return math_dict[x] if x in math_dict else None


问:
Driving motors with image processing on raspberry pi
I have a question about processing the image while driving a motor. I did some researches, probably I need to use multiprocessing. However, I couldn't find out how to run two processors together.

Let's say I have two functions as imageProcessing() and DrivingMotor(). With coming information from imageProcessing(), I need to update my DrivingMotor() function simultaneously. How can I handle this issue?

答:
In multiprocessing, you must create two process(process means program in execution) and must implement  interproccesing communication  methods to communicate process each other, this is tedious,hard and inefficient way .Multiproccesing less efficient than multithreading.Therefore I think you should multithread ,it is very efficient way ,communication  between thread is very  easy, you can use global data for communication.

You shall create  two threads, one thread is handle imageProcessing() ,and other thread DrivingMotor().Operating system  handled execution of thread,Operating system run  synchronous these threads.

there is basic tutorial for multithreading below links

https://www.tutorialspoint.com/python/python_multithreading.htm


问:
looping through csv file
I'm very new to R and Rstudio. What I'm trying to do is loop through a csv file.

The file has 3 columns. 1) user 2) event (success or fail) 3) randNum

So basically every user starts off with a fail and once they reach a success it moves on to the next user.

Ex:

```<code>user:   |  event:  | randNum

user1  |   fail    |  6

user1  |   fail    |  4

user1  |  fail     |  1

user1   | success  |  2

user2 | ...        |
</code>```

Basically what I need to do is this. I need to store the first random number (6) and than the last random number (2) which will be whenever the user succeeds. How would I do that? And i need to do this for each user because I will be doing something with these numbers.

答:
The quickest way would be to use table to get counts:

```<code>table(df$user)
</code>```

Example code:

```<code>> df <- data.frame(user=c(rep("john",4),rep("jane",3)), event=c(rep("failed",3), "success", rep("failed",2), "success"))
> df
  user   event
1 john  failed
2 john  failed
3 john  failed
4 john success
5 jane  failed
6 jane  failed
7 jane success
> table(df$user)

jane john
   3    4
</code>```

EDIT: To address latest edits you made that substantially modified the question:

```<code>> df <- data.frame(user=c(rep("john",4),rep("jane",3)), event=c(rep("failed",3), "success", rep("failed",2), "success"), randNum=c(4,6,1,2,9,3,5))

> library(dplyr)

> df <- df %>% group_by(user) %>% mutate(trial = 1:n())

> df[df$trial==1 | df$event=="success",]
Source: local data frame [4 x 4]
Groups: user [2]

    user   event randNum trial
  <fctr>  <fctr>   <dbl> <int>
1   john  failed       4     1
2   john success       2     4
3   jane  failed       9     1
4   jane success       5     3
</code>```

Title: looping through csv file

Body:
I'm very new to R and Rstudio. What I'm trying to do is loop through a csv file.

The file has 3 columns. 1) user 2) event (success or fail) 3) randNum

So basically every user starts off with a fail and once they reach a success it moves on to the next user.

Ex:

user:   |  event:  | randNum

user1  |   fail    |  6

user1  |   fail    |  4

user1  |  fail     |  1

user1   | success  |  2

user2 | ...        |

Basically what I need to do is this. I need to store the first random number (6) and than the last random number (2) which will be whenever the user succeeds. How would I do that? And i need to do this for each user because I will be doing something with these numbers.

Body:
The quickest way would be to use table to get counts:

table(df$user)

Example code:

> df <- data.frame(user=c(rep("john",4),rep("jane",3)), event=c(rep("failed",3), "success", rep("failed",2), "success"))
> df
  user   event
1 john  failed
2 john  failed
3 john  failed
4 john success
5 jane  failed
6 jane  failed
7 jane success
> table(df$user)

jane john
   3    4

EDIT: To address latest edits you made that substantially modified the question:

> df <- data.frame(user=c(rep("john",4),rep("jane",3)), event=c(rep("failed",3), "success", rep("failed",2), "success"), randNum=c(4,6,1,2,9,3,5))

> library(dplyr)

> df <- df %>% group_by(user) %>% mutate(trial = 1:n())

> df[df$trial==1 | df$event=="success",]
Source: local data frame [4 x 4]
Groups: user [2]

    user   event randNum trial
  <fctr>  <fctr>   <dbl> <int>
1   john  failed       4     1
2   john success       2     4
3   jane  failed       9     1
4   jane success       5     3


问:
How to match concentric ellipses' edges with some vertical line in R plot
Background: My ultimate goal in asking the following question is to turn the following into a function. In short, I have a curve placed above multiple concentric ellipses (ovals). The core issue is how to match the curve above these ellipses so if the curve changes the ellipses change accordingly.

Details:

More specifically, I want to have 11 concentric ellipses (see below image). At the outer edge of these 11 ellipses, I need 13 line segments to go up to attach to the curve line (see image below). The curve shown below is a Cauchy distribution (see last line of R code below the image). But this curve can be any other symmetric curve (e.g., normal distribution, t-distribution).

Question:

How can I determine (match) the coordinates of the ellipses with the line segment that must exactly connect to the outer edge of the ellipses?

Note: Most probably, the problem has to do with the math behind ellipses.

(I've tried something and have provided annotated R codes further below).

Here is my R code:

```<code>if(!require(library(plotrix))){install.packages('plotrix') }
library(plotrix)                ## A package for drawing ellipses ##

# In the "plotrix":

# "x" and "y" are the coordinates of the center.
# "a" and "b" give the radii of the ovals.

plot(1, ty='n', ann = F, xlim = c(-4, 6), ylim = c(-3, 1.5) ) ## A platform for ellipses

draw.ellipse(x = rep(1, 11), y = rep(-1.2, 11),
         a = seq(1, 6, by = .4), b = seq(1/4.5, 6/4.5 , by = .4/4.5 ),
         lty = 2, border = 'gray60' )       ## Draw multiple Concentric ellipses ##

AA <- seq(-4, 6, len = 13)     ## A range of values on the x-xis just like "xlim" ##
BB <- dcauchy( AA, 1, .95)*5   ## The Height for the AA according to a distribution ##

segments(AA, rep(-1.2, length(AA) ), AA, BB, lty = 3, lwd = 2, col= 'green4' )

curve(dcauchy(x, 1, .95)*5, -4, 6, add = T, col ='magenta', lwd = 3)
</code>```

答:
```<code>library(plotrix)

#AVAILABE DATA
el_x = 1 #Centre of ellipse
el_y = -1.2 #Centre of ellipse
n = 13 #The number of ellipses (13 in this example)
el_a = seq(1, 6, length.out = n) #'a' values
#You likely have 'b' too, but I am computing for now
el_b = seq(1/4.5, 6/4.5, length.out = n)

#Retain only every other 'a' value
if (n %%2 !=0){ #Odd 'n'
    el_a_2 = el_a[seq_along(el_a) %% 2 != 0]
} else { #Even 'n'
    el_a_2 = el_a[seq_along(el_a) %% 2 == 0] #Modify if necessary
}

#Store curve in a variable for now
cc = curve(dcauchy(x, 1, .95)*5, min(el_x - el_a), max(el_x + el_a))

#Calculate x-values (subtract and add 'a' to 'el_x') of ellipse extremes
AA <- c(el_x - el_a_2, el_x, el_x + el_a_2) #The x-values you need for segments
AA = sort(AA) #To plot lines and points as you want

#Calculate y-values from AA
BB <- dcauchy(AA, 1, .95)*5  #The y-values you need for segments

#Raise the curve to have 0.2 distance (OPTIONAL)
Raise_curve = max(el_b + el_y) + 0.2 - (min(BB) - max(el_b + el_y))

BB = BB + Raise_curve #Raise BB

plot(1, type = 'n', ann = F,
    xlim = c(min(el_x - el_a), max(el_x + el_a)),
    ylim = c(min(el_y - el_b), max(BB)))

draw.ellipse(x = rep(el_x, n), y = rep(el_y, n),
         a = el_a, b = el_b,
         lty = 2, border = 'gray60')

segments(x0 = AA, x1 = AA, y0 = el_y, y1 = BB, lty = 3, lwd = 2,
    col = c(rep('green3', floor(length(AA)-3)/2),
        rep('navy', 3 ),
        rep('green3', length(AA) - 3 - floor(length(AA)-3)/2)))

lines(cc$x, cc$y+ Raise_curve, lwd = 2, col = "red")

#ADDITIONAL EXAMPLE
points(AA, rep(-1.2, length(AA) ), pch = c(rep(22, 6), 21, rep(22, 6)),
    col = c(rep('blue', 6), 'red', rep('blue', 6)),
    bg = c(rep('blue', 6), 'red', rep('blue', 6)), cex = 3)

xx <- seq(AA[7], AA[9], length.out = 1000)
yy = dcauchy(xx, 1, .95)*5
yy = yy+Raise_curve
polygon(c(AA[7], xx, AA[9]), c(el_y, yy, el_y), border = NA,
                       col= adjustcolor('green', alpha.f = .2) )
</code>```

Body:
Background: My ultimate goal in asking the following question is to turn the following into a function. In short, I have a curve placed above multiple concentric ellipses (ovals). The core issue is how to match the curve above these ellipses so if the curve changes the ellipses change accordingly.

Details:

More specifically, I want to have 11 concentric ellipses (see below image). At the outer edge of these 11 ellipses, I need 13 line segments to go up to attach to the curve line (see image below). The curve shown below is a Cauchy distribution (see last line of R code below the image). But this curve can be any other symmetric curve (e.g., normal distribution, t-distribution).

Question:

How can I determine (match) the coordinates of the ellipses with the line segment that must exactly connect to the outer edge of the ellipses?

Note: Most probably, the problem has to do with the math behind ellipses.

(I've tried something and have provided annotated R codes further below).

Here is my R code:

if(!require(library(plotrix))){install.packages('plotrix') }
library(plotrix)                ## A package for drawing ellipses ##

# In the "plotrix":

# "x" and "y" are the coordinates of the center.
# "a" and "b" give the radii of the ovals.

plot(1, ty='n', ann = F, xlim = c(-4, 6), ylim = c(-3, 1.5) ) ## A platform for ellipses

draw.ellipse(x = rep(1, 11), y = rep(-1.2, 11),
         a = seq(1, 6, by = .4), b = seq(1/4.5, 6/4.5 , by = .4/4.5 ),
         lty = 2, border = 'gray60' )       ## Draw multiple Concentric ellipses ##

AA <- seq(-4, 6, len = 13)     ## A range of values on the x-xis just like "xlim" ##
BB <- dcauchy( AA, 1, .95)*5   ## The Height for the AA according to a distribution ##

segments(AA, rep(-1.2, length(AA) ), AA, BB, lty = 3, lwd = 2, col= 'green4' )

curve(dcauchy(x, 1, .95)*5, -4, 6, add = T, col ='magenta', lwd = 3)


问:
Count percentage in SQL Server query
I have this SQL query where its most important function is to return the total sales made SUM(gop.quantity). I would then like it to show the percentage for this number. If the query returned the following 3 rows then it should show the percentage next to it - like this:

unitsSold : 2 - percentage: 20%

unitsSold : 4 - percentage: 40%

unitsSold : 6 - percentage: 60%

Query:

```<code>SELECT TOP 20
    p.productid,
    SUM(gop.quantity) AS unitsSold,
    SUM(gop.price * gop.quantity) AS grossSales,
    p.productName, gop.picid, gop.picUrl
FROM
    product AS p
LEFT JOIN
    orderdetail AS gop ON gop.productid = p.productId
LEFT JOIN
    Orders AS hedgo ON hedgo.orderid = gop.orderid
WHERE
    EXISTS (SELECT * FROM orderdetail AS op
            WHERE op.orderid = hedgo.orderid)
GROUP BY
    p.productid, p.productName, gop.picid, gop.picUrl
ORDER BY
    unitsSold DESC
</code>```

How can I accomplish this in my SQL query?

答:
You can use sum() with  over() to get the total:

```<code>select top 20 p.productid
 , SUM(gop.quantity) as unitsSold
 , SUM(gop.quantity+.0) / sum(SUM(gop.quantity)) over() as Percentage
 , SUM(gop.price * gop.quantity) as grossSales
 , p.productName
 , gop.picid
 , gop.picUrl
from product as p
  left join orderdetail as gop
    on gop.productid = p.productId
  left join Orders as hedgo
    on hedgo.orderid = gop.orderid
where exists (
  select *
  from orderdetail as op
  where op.orderid = hedgo.orderid
  )
group by p.productid
 , p.productName
 , gop.picid
 , gop.picUrl
order by unitsSold desc
</code>```

I added +.0 to the sum(gop.quantity) so that the division operation would return a decimal instead of an int, if quantity is an int.

Title: Count percentage in SQL Server query

Body:
I have this SQL query where its most important function is to return the total sales made SUM(gop.quantity). I would then like it to show the percentage for this number. If the query returned the following 3 rows then it should show the percentage next to it - like this:

unitsSold : 2 - percentage: 20%

unitsSold : 4 - percentage: 40%

unitsSold : 6 - percentage: 60%

Query:

SELECT TOP 20
    p.productid,
    SUM(gop.quantity) AS unitsSold,
    SUM(gop.price * gop.quantity) AS grossSales,
    p.productName, gop.picid, gop.picUrl
FROM
    product AS p
LEFT JOIN
    orderdetail AS gop ON gop.productid = p.productId
LEFT JOIN
    Orders AS hedgo ON hedgo.orderid = gop.orderid
WHERE
    EXISTS (SELECT * FROM orderdetail AS op
            WHERE op.orderid = hedgo.orderid)
GROUP BY
    p.productid, p.productName, gop.picid, gop.picUrl
ORDER BY
    unitsSold DESC

How can I accomplish this in my SQL query?

Body:
You can use sum() with  over() to get the total:

select top 20 p.productid
 , SUM(gop.quantity) as unitsSold
 , SUM(gop.quantity+.0) / sum(SUM(gop.quantity)) over() as Percentage
 , SUM(gop.price * gop.quantity) as grossSales
 , p.productName
 , gop.picid
 , gop.picUrl
from product as p
  left join orderdetail as gop
    on gop.productid = p.productId
  left join Orders as hedgo
    on hedgo.orderid = gop.orderid
where exists (
  select *
  from orderdetail as op
  where op.orderid = hedgo.orderid
  )
group by p.productid
 , p.productName
 , gop.picid
 , gop.picUrl
order by unitsSold desc

I added +.0 to the sum(gop.quantity) so that the division operation would return a decimal instead of an int, if quantity is an int.


问:
How do you get the current page URL in jQuery Mobile 1.4.5?
Please don't mark this as a duplicate. I have tried all the methods suggested on StackOverflow and none of them work. They all give me the URL of the referring page, not the current page. Or they don't work at all. Even window.location.href returns the referring page URL, not the current page URL. I'm using jQuery Mobile 1.4.5.

For example say I was on page1.php and I clicked a link to page1.php?getvar=42. Page 1 looks like this:

```<code><!doctype html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
</head>
<body><div data-role="page" data-dom-cache="false">
<a href="page1.php?getvar=42">Click Here</a>
<?php if ($_GET['getvar']=='42'): ?>
<script>
console.log(window.location.href);
console.log(document.location.href);
console.log($.mobile.activePage.data('url'));
</script>
<?php endif ?>
</div></body></html>
</code>```

When I click the link in the above page and I look at what it says in the console. I get:

```<code>http://hostname/page1.php
http://hostname/page1.php
/page1.php
</code>```

I've also tried wrapping these calls to console.log() in a jQuery $(document).ready() function with no change in the result.

```<code><script>
$(function() {
    console.log(window.location.href);
    console.log(document.location.href);
    console.log($.mobile.activePage.data('url'));
});
</script>
</code>```

As you can see none of these are the complete URL. The same is true when linking to a different file. So it doesn't just affect pages with GET variables on the URL. I am expecting to see /page1.php?getvar=42

I've found topics on Stack Overflow that ask this same question but none of the answers are working for me. Perhaps they are using a different version of jQuery Mobile. I'm using jQuery 1.4.5 as you can see.

So far the only solution that I have found is to turn off ajax loading of pages in jQuery mobile by putting data-ajax="false" on a parent container. But there must be a better way.

(By the way, the reason I need this is so that I can reload the current page. But currently all attempts to reload the current page just take me back to the referring page. And this is why.)

答:
The answer is to wrap window.location.href in a setTimeout() call like this:

```<code><script>
setTimeout(function() {
    console.log(window.location.href);
}, 0);
</script>
</code>```

Wrapping inside of $(document).ready() call does not work, though.

Body:
Please don't mark this as a duplicate. I have tried all the methods suggested on StackOverflow and none of them work. They all give me the URL of the referring page, not the current page. Or they don't work at all. Even window.location.href returns the referring page URL, not the current page URL. I'm using jQuery Mobile 1.4.5.

For example say I was on page1.php and I clicked a link to page1.php?getvar=42. Page 1 looks like this:

<!doctype html>

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">

Click Here
<?php if ($_GET['getvar']=='42'): ?>

<?php endif ?>

When I click the link in the above page and I look at what it says in the console. I get:

http://hostname/page1.php
http://hostname/page1.php
/page1.php

I've also tried wrapping these calls to console.log() in a jQuery $(document).ready() function with no change in the result.

As you can see none of these are the complete URL. The same is true when linking to a different file. So it doesn't just affect pages with GET variables on the URL. I am expecting to see /page1.php?getvar=42

I've found topics on Stack Overflow that ask this same question but none of the answers are working for me. Perhaps they are using a different version of jQuery Mobile. I'm using jQuery 1.4.5 as you can see.

So far the only solution that I have found is to turn off ajax loading of pages in jQuery mobile by putting data-ajax="false" on a parent container. But there must be a better way.

(By the way, the reason I need this is so that I can reload the current page. But currently all attempts to reload the current page just take me back to the referring page. And this is why.)

Body:
The answer is to wrap window.location.href in a setTimeout() call like this:

<script>
setTimeout(function() {
    console.log(window.location.href);
}, 0);
</script>

Wrapping inside of $(document).ready() call does not work, though.


问:
How to print a string and integer variable together?
I have written the following script:

```<code>string="My name"
age=19
print(string +str(age))
</code>```

But this gives an error stating:

```<code>"str object is not callable".
</code>```

Help me to typecast and print.

答:
Try formatting strings:

print( f'{string} {age}' )

Body:
I have written the following script:

string="My name"
age=19
print(string +str(age))

But this gives an error stating:

"str object is not callable".

Help me to typecast and print.


问:
Convert date and time into Correct format to compare to current date
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.

Following is how  I have

```<code>string date = "2017-03-29";
string time  = "09:30"
</code>```

I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq

答:
I would say the same as @Sam, but I don't have enough reputation to comment.

```<code>string date = "2017-03-29";
string time = "09:30";

string dateTimeString = string.Format("{0} {1}", date, time);

DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
</code>```

Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.

Body:
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.

Following is how  I have

string date = "2017-03-29";
string time  = "09:30"

I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq

Body:
I would say the same as @Sam, but I don't have enough reputation to comment.

string date = "2017-03-29";
string time = "09:30";

string dateTimeString = string.Format("{0} {1}", date, time);

DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.


问:
Array.push performs deep copy instead of shallow copy
Context

I'm using Typescript/Angular2 RC1 for my webapp and I have two classes. In class1 (Angular2 service), I have a variable myVar = [obj1, obj2, obj3] and in class2 (Angular2 component), I get myLocalVar = class1.myVar in the constructor using viewInjector to inject the service.

Problem

In class2, I copy myVar with a push (shallow copy because it copies objects) so myLocalVar is equal to [obj1, obj2, obj3] (such that objX={number:X}). When I change one item such as: myVar[0]={number:5} in class1 the change won't appear in my class2 myLocalVar and myLocalVar[0].number will be equal to 1. However, myVar of class2 changes... It seems that the this.myLocalVar.push(this.myVar[int]); created a deep copy instead of a shallow copy.

Is Typescript changing the behavior of a push in Javascript? If yes, what should I do to keep the reference and do a shallow copy?

Code Sample

```<code>@Injectable()

export class Class1{

    public myVar:any[];

    constructor(){
        this.myVar = [{number: 1}, {number: 2}, {number: 3}];
    }

    changeVar(newVar):void{
        this.myVar[0] = newVar; // newVar = {number: 5}
    }
}
</code>```

```<code>@Component({
    selector: 'class2',
    viewInjector: [Class1],
    templateUrl: 'someURL'
})
export class Class2{

    private myLocalVar:any[] = [];

    constructor(class1: Class1){
        this.myVar = class1.myVar;
    }

    showVars():void{
        console.log(this.myLocalVar[0]);
        console.log(this.myVar[0]);
    }

    ngOnInit(){
        for(let int = 0; int < this.myVar.length; int++){
            this.myLocalVar.push(this.myVar[int]);
        }
    }
}
</code>```

The console.log will print two different values: console.log(this.myLocalVar[0]) prints 1 and console.log(this.myVar[0]); prints 5 after changeVar() has been called by a third party!

Edit

Here is a plunker that demonstrates the problem:

Click on show, check your console and you will see the same values

Click on change

Click on show again and you will see two different values for myVar and myLocalVar

What I need is each time I change myVar[x]=newObj I want myLocalVar to reflect that change. Please include a solution to that problem if you want your answer to be validated.

答:
Your have this problem because myLocalVar and myVar are two different references. Meaning, they are two different array containers.

And when you push element from myVar to myLocalVar, you push the references of the elements in myVar into myLocalVar. So
if

myVar = [{name: 1}, {name: 2}] you have two object in it and both references to the objects are pushed into myLocalVar.

When you call changeVar method, you basically replace the element reference in myVar with new object reference. However, the old reference to the element being replaced is still there and referenced by myLocalVar, thus the result you see.

So the solution?

You need to change how your changeVar method set the value. Instead of doing this.myVar[0] = {number:newVar};, you should do this.myVar[0]['number'] = newVar; This maintains the reference.

Body:
Context

I'm using Typescript/Angular2 RC1 for my webapp and I have two classes. In class1 (Angular2 service), I have a variable myVar = [obj1, obj2, obj3] and in class2 (Angular2 component), I get myLocalVar = class1.myVar in the constructor using viewInjector to inject the service.

Problem

In class2, I copy myVar with a push (shallow copy because it copies objects) so myLocalVar is equal to [obj1, obj2, obj3] (such that objX={number:X}). When I change one item such as: myVar[0]={number:5} in class1 the change won't appear in my class2 myLocalVar and myLocalVar[0].number will be equal to 1. However, myVar of class2 changes... It seems that the this.myLocalVar.push(this.myVar[int]); created a deep copy instead of a shallow copy.

Is Typescript changing the behavior of a push in Javascript? If yes, what should I do to keep the reference and do a shallow copy?

Code Sample

@Injectable()

export class Class1{

    public myVar:any[];

    constructor(){
        this.myVar = [{number: 1}, {number: 2}, {number: 3}];
    }

    changeVar(newVar):void{
        this.myVar[0] = newVar; // newVar = {number: 5}
    }
}

@Component({
    selector: 'class2',
    viewInjector: [Class1],
    templateUrl: 'someURL'
})
export class Class2{

    private myLocalVar:any[] = [];

    constructor(class1: Class1){
        this.myVar = class1.myVar;
    }

    showVars():void{
        console.log(this.myLocalVar[0]);
        console.log(this.myVar[0]);
    }

    ngOnInit(){
        for(let int = 0; int < this.myVar.length; int++){
            this.myLocalVar.push(this.myVar[int]);
        }
    }
}

The console.log will print two different values: console.log(this.myLocalVar[0]) prints 1 and console.log(this.myVar[0]); prints 5 after changeVar() has been called by a third party!

Edit

Here is a plunker that demonstrates the problem:

Click on show, check your console and you will see the same values

Click on change

Click on show again and you will see two different values for myVar and myLocalVar

What I need is each time I change myVar[x]=newObj I want myLocalVar to reflect that change. Please include a solution to that problem if you want your answer to be validated.


问:
Shorten Dynamic SQL Query For Loop
I have a function that builds an sql query and then inserts it into the client-side light sql.

I think im using to many for loops, how would i make this shorter?

```<code>function insert(dataBase,table,row){
    var j = 0;

    var sqlQueryArray = [];

    sqlQueryArray[j++] = 'INSERT INTO ';
    sqlQueryArray[j++] = table
    sqlQueryArray[j++] = ' ('

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = row[i].id + ',';
    };

    sqlQueryArray[j++] = row[(row.length - 1)].id + '';
    sqlQueryArray[j++] = ')'
    var sqlQueryString = ' VALUES ';

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = '?, ';
    };

    sqlQueryArray[j++] = '?';
    sqlQueryArray[j++] = ');'

    for (var i = 0; i < sqlQueryArray.length; i++){
        sqlQueryString += sqlQueryArray[i];
    }
    var rowArray = []
    for (var i = row.length - 1; i >= 0; i--){
        rowArray[i] = row[i].val;
    };

    dataBase.openDatabase.transaction(
        function (transaction) {
            transaction.executeSql(sqlQueryString,
                rowArray,
                dataBase.nullSQLHandler, dataBase.QueryError);
        }
    );
}
</code>```

答:
First of all, I think you'd be better not tracking the index manually (j++). Use sqlQueryArray.push() to insert the elements at the end of sqlQueryArray.

Then, to simplify your code, you can create a function that returns you a custom SQL passing your row variable as a parameter, with that you can generate the INSERT INTO clause with all the ? markers.

ContentLicense: CC BY-SA 2.5

Title: Shorten Dynamic SQL Query For Loop

Body:
I have a function that builds an sql query and then inserts it into the client-side light sql.

I think im using to many for loops, how would i make this shorter?

function insert(dataBase,table,row){
    var j = 0;

    var sqlQueryArray = [];

    sqlQueryArray[j++] = 'INSERT INTO ';
    sqlQueryArray[j++] = table
    sqlQueryArray[j++] = ' ('

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = row[i].id + ',';
    };

    sqlQueryArray[j++] = row[(row.length - 1)].id + '';
    sqlQueryArray[j++] = ')'
    var sqlQueryString = ' VALUES ';

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = '?, ';
    };

    sqlQueryArray[j++] = '?';
    sqlQueryArray[j++] = ');'

    for (var i = 0; i < sqlQueryArray.length; i++){
        sqlQueryString += sqlQueryArray[i];
    }
    var rowArray = []
    for (var i = row.length - 1; i >= 0; i--){
        rowArray[i] = row[i].val;
    };

    dataBase.openDatabase.transaction(
        function (transaction) {
            transaction.executeSql(sqlQueryString,
                rowArray,
                dataBase.nullSQLHandler, dataBase.QueryError);
        }
    );
}


问:
How can I create a sequence generator in DataFlow?
Using PTransforms, I'm generating say 1 million objects. However, I need to label these objects with individual unique numbers from 1 to 1 million. There is NO specified order that these objets need to be generated, but the sequence number should range continuously from 1 to 1 million.

So, I need what in a db world would be an "autonum" function or also known as a "sequence generator". Is there a way to accomplish thin in google cloud dataflow?

The only ideas I came up with is to:

a) store all of the objects as a signle PCollectionView object and then traverse this list in order and assign a new hashmap which has the sequenceKey and the object value. This is not super efficient, and has problems when trying to store all million objects in memory, but it is a workaround that should work.

or

b) maybe use some sort of memcache service that is accessible from all notes and do an atomic read-increment from it? (Not sure how to do this, but it might be possible.) But, this feels like a lot of coding for a simple sequence generator (also, I'm not sure if performance may be poor since everything may get bottlenecks by the seq generator call)

c) remove requirement that the sequence numbers are contiguous, and then do something similar to "b" above.

答:
This sort of behavior can be simply supported with stateful processing in Beam's Java SDK. This is because state information can be kept accross bundles, so you can number the elements of your whole PCollection.

You can read more about it in this blog post.

A DoFn that can do this is the following:

```<code>new DoFn<KV<MyKey, MyValue>, KV<Integer, KV<MyKey, MyValue>>>() {

  // A state cell holding a single Integer per key+window
  @StateId("index")
  private final StateSpec<Object, ValueState<Integer>> indexSpec =
      StateSpecs.value(VarIntCoder.of());

  @ProcessElement
  public void processElement(
      ProcessContext context,
      @StateId("index") ValueState<Integer> index) {
    int current = firstNonNull(index.read(), 0);
    context.output(KV.of(current, context.element()));
    index.write(current+1);
  }
}
</code>```

Body:
This sort of behavior can be simply supported with stateful processing in Beam's Java SDK. This is because state information can be kept accross bundles, so you can number the elements of your whole PCollection.

You can read more about it in this blog post.

A DoFn that can do this is the following:

new DoFn<KV<MyKey, MyValue>, KV<Integer, KV<MyKey, MyValue>>>() {

  // A state cell holding a single Integer per key+window
  @StateId("index")
  private final StateSpec<Object, ValueState<Integer>> indexSpec =
      StateSpecs.value(VarIntCoder.of());

  @ProcessElement
  public void processElement(
      ProcessContext context,
      @StateId("index") ValueState<Integer> index) {
    int current = firstNonNull(index.read(), 0);
    context.output(KV.of(current, context.element()));
    index.write(current+1);
  }
}


问:
Can Enum.ToString support precision specifiers like "X2"?
Enum.ToString(string) does not support direct usage of precision specifiers like X2 or D5 to apply a padding to numeric values.  Formattings like ToString("X") or ToString("D") are implemented and well documented. Of course I can explicitely cast it to int before and so make use of the format specifiers implemented for ints to convert it to a padded string.

I was wondering if there is some direct support for this functionallity for enum without the need to cast them. On first sight it seems strange that this is not directly implemented as it was done for ints or other numeric types. But maybe I am missing something more important which could explicitely explain that it wasn't done like that for enums?

```<code>public enum Number
{
    Ten = 10
}

Console.WriteLine(Number.Ten);                      //OK: Ten
Console.WriteLine(Number.Ten.ToString());           //OK: Ten
Console.WriteLine(Number.Ten.ToString("D"));        //OK: 10
Console.WriteLine(Number.Ten.ToString("D5"));       //Expected 00010 - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or
Console.WriteLine(Number.Ten.ToString("X"));        //OK: 0000000A
Console.WriteLine(Number.Ten.ToString("X2"));       //Expected 0A - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or "d"
Console.WriteLine(10.ToString("X2"));               //OK: 0A
Console.WriteLine(10.ToString("D5"));               //OK: 00010
Console.WriteLine(((int)Number.Ten).ToString("X2"));//OK: 0A
</code>```

A short summary from the accepted answer:
It is not explicitely there because it is already implicitely done depending on the size of the underlying type. So if you like X2 instead of X8 just use byte as underlying type and ToString("X") will behave like ToString("X2").

答:
The implementation of Enum.ToString() shows that it was designed so that only certain format specifiers can be used:

```<code>    public String ToString(String format) {
        if (format == null || format.Length == 0)
            format = "G";

        if (String.Compare(format, "G", StringComparison.OrdinalIgnoreCase) == 0)
            return ToString();

        if (String.Compare(format, "D", StringComparison.OrdinalIgnoreCase) == 0)
            return GetValue().ToString();

        if (String.Compare(format, "X", StringComparison.OrdinalIgnoreCase) == 0)
            return InternalFormattedHexString(GetValue());

        if (String.Compare(format, "F", StringComparison.OrdinalIgnoreCase) == 0)
            return InternalFlagsFormat((RuntimeType)GetType(), GetValue());

        throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
    }
</code>```

I think it covers the most common scenarios: being able to show its numeric, hexadecimal, or string representation. The workaround of an explicit cast seems cheap enough to not need to bake it into the framework.

If you want to use the underlying type's ToString() without knowing what the specific type is (without having to cast!), you could maybe do something like:

```<code>var formattedValue = string.Format("{0:X2}",
    Convert.ChangeType(Number.Ten, Number.Ten.GetTypeCode()));
</code>```

Which would ouput "0A". This could be wrapped up easily in an extension method.

Body:
Enum.ToString(string) does not support direct usage of precision specifiers like X2 or D5 to apply a padding to numeric values.  Formattings like ToString("X") or ToString("D") are implemented and well documented. Of course I can explicitely cast it to int before and so make use of the format specifiers implemented for ints to convert it to a padded string.

I was wondering if there is some direct support for this functionallity for enum without the need to cast them. On first sight it seems strange that this is not directly implemented as it was done for ints or other numeric types. But maybe I am missing something more important which could explicitely explain that it wasn't done like that for enums?

public enum Number
{
    Ten = 10
}

Console.WriteLine(Number.Ten);                      //OK: Ten
Console.WriteLine(Number.Ten.ToString());           //OK: Ten
Console.WriteLine(Number.Ten.ToString("D"));        //OK: 10
Console.WriteLine(Number.Ten.ToString("D5"));       //Expected 00010 - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or
Console.WriteLine(Number.Ten.ToString("X"));        //OK: 0000000A
Console.WriteLine(Number.Ten.ToString("X2"));       //Expected 0A - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or "d"
Console.WriteLine(10.ToString("X2"));               //OK: 0A
Console.WriteLine(10.ToString("D5"));               //OK: 00010
Console.WriteLine(((int)Number.Ten).ToString("X2"));//OK: 0A

A short summary from the accepted answer:
It is not explicitely there because it is already implicitely done depending on the size of the underlying type. So if you like X2 instead of X8 just use byte as underlying type and ToString("X") will behave like ToString("X2").

Body:
The implementation of Enum.ToString() shows that it was designed so that only certain format specifiers can be used:

    public String ToString(String format) {
        if (format == null || format.Length == 0)
            format = "G";

        if (String.Compare(format, "G", StringComparison.OrdinalIgnoreCase) == 0)
            return ToString();

        if (String.Compare(format, "D", StringComparison.OrdinalIgnoreCase) == 0)
            return GetValue().ToString();

        if (String.Compare(format, "X", StringComparison.OrdinalIgnoreCase) == 0)
            return InternalFormattedHexString(GetValue());

        if (String.Compare(format, "F", StringComparison.OrdinalIgnoreCase) == 0)
            return InternalFlagsFormat((RuntimeType)GetType(), GetValue());

        throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
    }

I think it covers the most common scenarios: being able to show its numeric, hexadecimal, or string representation. The workaround of an explicit cast seems cheap enough to not need to bake it into the framework.

If you want to use the underlying type's ToString() without knowing what the specific type is (without having to cast!), you could maybe do something like:

var formattedValue = string.Format("{0:X2}",
    Convert.ChangeType(Number.Ten, Number.Ten.GetTypeCode()));

Which would ouput "0A". This could be wrapped up easily in an extension method.


问:
Scaling a CSS frame-by-frame animation (Save me!)
I was wondering if one of you could assist me with a CSS/HTML issue I am having.

I have a CSS based animation using the background and the steps() method. Unfortunately, this has meant scaling has been an issue.

Is there a way of simply scaling the div containing this to fit the screen? I don't mind the aspect ratio, that's not an issue. Here is my CSS for the animation:

```<code>    .pageOpen {
  width: 710.956522px;
  height: 400px;
  background: url('/Images/SiteVitalImages/preloader-open.png') left center;
  background-repeat: no-repeat;
  background-size: cover;
  animation: play 1s steps(22) infinite;
}

@keyframes play {
    100% { background-position: right ; }
}
</code>```

I would really appreciate the assistance, this has been quite irritating.

Here is a gif of the issue:
https://gyazo.com/91deb470a88b6066de9015beec5c0eed

I'd like for it to scale horizontally without showing upcoming frames of the animation.

答:
Originally I misunderstood what you were trying to do. playing with this I found that you must scale it so the height is the largest dimension so it doesn't repeat horizontally. to add to the illusion I made the background black and centered it, also I reversed the order so it looked more explosiony to me.

you can also see it on jsfiddle https://jsfiddle.net/j7L4amov/11/

html, body{
  height: 100%;
  background-color: black;
 }

.wrapper{
  position: relative;
  margin: auto;
  min-height: 400px;
  height: 100%;
  min-width: 710px;
  width:  calc( 100vh * 16.0 / 9.0 );
}

.pageOpen {
  min-height: 400px;
  min-width: 710px;
  height: 100%;
  width: 100%;
 background: url('https://www.contingentgame.com/storage/themes/godlike/assets/images/preloader-bg.png') no-repeat right center;
 background-size: cover;
 animation: play 1.5s steps(22) infinite;
 overflow: hidden;
}

@keyframes play {
    100% {
      background-position: left center;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=wrapper>
<div class=pageOpen>
</div>
</div></code>```

Body:
I was wondering if one of you could assist me with a CSS/HTML issue I am having.

I have a CSS based animation using the background and the steps() method. Unfortunately, this has meant scaling has been an issue.

Is there a way of simply scaling the div containing this to fit the screen? I don't mind the aspect ratio, that's not an issue. Here is my CSS for the animation:

    .pageOpen {
  width: 710.956522px;
  height: 400px;
  background: url('/Images/SiteVitalImages/preloader-open.png') left center;
  background-repeat: no-repeat;
  background-size: cover;
  animation: play 1s steps(22) infinite;
}

@keyframes play {
    100% { background-position: right ; }
}

I would really appreciate the assistance, this has been quite irritating.

Here is a gif of the issue:
https://gyazo.com/91deb470a88b6066de9015beec5c0eed

I'd like for it to scale horizontally without showing upcoming frames of the animation.

Body:
Originally I misunderstood what you were trying to do. playing with this I found that you must scale it so the height is the largest dimension so it doesn't repeat horizontally. to add to the illusion I made the background black and centered it, also I reversed the order so it looked more explosiony to me.

you can also see it on jsfiddle https://jsfiddle.net/j7L4amov/11/

html, body{
  height: 100%;
  background-color: black;
 }

.wrapper{
  position: relative;
  margin: auto;
  min-height: 400px;
  height: 100%;
  min-width: 710px;
  width:  calc( 100vh * 16.0 / 9.0 );
}

.pageOpen {
  min-height: 400px;
  min-width: 710px;
  height: 100%;
  width: 100%;
 background: url('https://www.contingentgame.com/storage/themes/godlike/assets/images/preloader-bg.png') no-repeat right center;
 background-size: cover;
 animation: play 1.5s steps(22) infinite;
 overflow: hidden;
}

@keyframes play {
    100% {
      background-position: left center;
    }
}

<div class=wrapper>
<div class=pageOpen>
</div>
</div>


问:
Is it possible to have multiple AuthenticationProcessingFilter on the same path in spring security?
Is it possible to hock multiple AuthenticationProcessingFilter(s) on the login path in spring security? lets I want to have the following filtrates run in order every time user login:

requestIntegrityFilter: validate the url/hostname/IP/.. according to some rules
 secretTokenAuthenticationFilter: validate token generated in the browser from 3rd party.
 UsernamePasswordAuthenticationFilter : validate username/password

I could have one AuthenticationFilter where I can encapsulate all this logic in one method.but I'm wondering if there are any alternative solutions.

答:
You can have multiple Filters, just specify the order and you are fine

```<code>filterChain.doFilter(request, response);
</code>```

This command will make sure of execution of the subsequent filters in the filter chain

Body:
You can have multiple Filters, just specify the order and you are fine

filterChain.doFilter(request, response);

This command will make sure of execution of the subsequent filters in the filter chain


问:
Postgres 9.6: Parallel query does not take max_parallel_workers_per_gather setting
Postgres 9.6;  Centos 6.7 ; 24 cores

BigTable1 contains 1,500,000,000 rows;    weight 180GB.

```<code>max_worker_processes = 20
max_parallel_workers_per_gather = 12
</code>```

1)
When running

```<code>EXPLAIN
SELECT
    date_id, id1, id2, id3, id4, topdomain, ftype, SUM(imps), SUM(cls)
FROM BigTable1
WHERE
    date_id BETWEEN 2017021200 AND 2017022400
    AND date_id BETWEEN 2017020000 AND 2017029999
GROUP BY
date_id, id1, id2, id3, id4, topdomain, ftype;
</code>```

No “Workers Planned:” used at all. Why?

2)
When running the same query when in the session defined

```<code>set max_parallel_workers_per_gather = 5;
</code>```

“Workers Planned: 5” appear. The execution time was improved only by 25%.

2.1)    Why “Workers Planned:” appears only after this setting?
2.2)    Why we could not see a much better improvement when running with max_parallel_workers_per_gather = 5 ?

Thank you!.

答:
If you are just looking to test the parallel query bits then you can have a look at force_parallel_mode and setting it to on.

force_parallel_mode (enum)

Allows the use of parallel queries for testing purposes even in
  cases where no performance benefit is expected. The allowed values of
  force_parallel_mode are off (use parallel mode only when it is
  expected to improve performance), on (force parallel query for all
  queries for which it is thought to be safe), and regress (like on, but
  with additional behavior changes as explained below).

And, just as robert-haas   mentioned below, Without force_parallel_modethe optimizer will potentially decide parallel query isn't the quickest... see the params below:

```<code>select
  name,
  setting,
  unit,
  short_desc
from pg_settings
where name in (
  'force_parallel_mode',
  'min_parallel_relation_size',
  'parallel_setup_cost',
  'parallel_tuble_cost',
  'max_parallel_workers_per_gather' )
  limit 10 ;
</code>```

```<code>postgres=>
---------------------------------+---------+------+---------------------------------------------------------------------------------------------
 force_parallel_mode             | off     |      | Forces use of parallel query facilities.
 max_parallel_workers_per_gather | 0       |      | Sets the maximum number of parallel processes per executor node.
 min_parallel_relation_size      | 1024    | 8kB  | Sets the minimum size of relations to be considered for parallel scan.
 parallel_setup_cost             | 1000    |      | Sets the planner's estimate of the cost of starting up worker processes for parallel query.
(4 rows)
</code>```

Body:
Postgres 9.6;  Centos 6.7 ; 24 cores

BigTable1 contains 1,500,000,000 rows;    weight 180GB.

max_worker_processes = 20
max_parallel_workers_per_gather = 12

1)
When running

EXPLAIN
SELECT
    date_id, id1, id2, id3, id4, topdomain, ftype, SUM(imps), SUM(cls)
FROM BigTable1
WHERE
    date_id BETWEEN 2017021200 AND 2017022400
    AND date_id BETWEEN 2017020000 AND 2017029999
GROUP BY
date_id, id1, id2, id3, id4, topdomain, ftype;

No “Workers Planned:” used at all. Why?

2)
When running the same query when in the session defined

set max_parallel_workers_per_gather = 5;

“Workers Planned: 5” appear. The execution time was improved only by 25%.

2.1)    Why “Workers Planned:” appears only after this setting?
2.2)    Why we could not see a much better improvement when running with max_parallel_workers_per_gather = 5 ?

Thank you!.

Body:
If you are just looking to test the parallel query bits then you can have a look at force_parallel_mode and setting it to on.

force_parallel_mode (enum)

Allows the use of parallel queries for testing purposes even in
  cases where no performance benefit is expected. The allowed values of
  force_parallel_mode are off (use parallel mode only when it is
  expected to improve performance), on (force parallel query for all
  queries for which it is thought to be safe), and regress (like on, but
  with additional behavior changes as explained below).

And, just as robert-haas   mentioned below, Without force_parallel_modethe optimizer will potentially decide parallel query isn't the quickest... see the params below:

select
  name,
  setting,
  unit,
  short_desc
from pg_settings
where name in (
  'force_parallel_mode',
  'min_parallel_relation_size',
  'parallel_setup_cost',
  'parallel_tuble_cost',
  'max_parallel_workers_per_gather' )
  limit 10 ;

postgres=>
---------------------------------+---------+------+---------------------------------------------------------------------------------------------
 force_parallel_mode             | off     |      | Forces use of parallel query facilities.
 max_parallel_workers_per_gather | 0       |      | Sets the maximum number of parallel processes per executor node.
 min_parallel_relation_size      | 1024    | 8kB  | Sets the minimum size of relations to be considered for parallel scan.
 parallel_setup_cost             | 1000    |      | Sets the planner's estimate of the cost of starting up worker processes for parallel query.
(4 rows)


问:
How do I get the current user's username in Bash?
How do I get the current user's username in Bash? Do I use whoami?

答:
In Solaris OS I used this command:

```<code>$ who am i     # Remember to use it with space.
</code>```

On Linux- Someone already answered this in comments.

```<code>$ whoami       # Without space
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Solaris OS I used this command:

$ who am i     # Remember to use it with space.

On Linux- Someone already answered this in comments.

$ whoami       # Without space


问:
Variadic template argument deduction/substitution failed, metaprogramming
Im attempting to create a recursive template function, however I keep getting the error:

no matching function for call to meuPrint(int&, Separator&, string&)

while also receiving:

candidate:
  template string meuPrint(U ..., Separator&,string&).

```<code>struct Separator {};

template<class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text )
{//end
    char buffer[200];
    sprintf( buffer , text.c_str() , b... );
    return buffer;
}
template<class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , string value , T ...a )
{//string
    return meuPrint( b... , to_lower( value ) , placeholder , text , a... );
}

template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )
{//middle
    return meuPrint( b... , value , placeholder , text , a... );
}

template<class ...T>
string meuPrint( std::string _text , T ...a )
{//start
    Separator placeholder;
    return meuPrint( placeholder , _text , a... );
}

int main( int n , char** args )
{
    string o = meuPrint(  string( "hello %i world" )  ,  8 );
    std::cout << o << std::endl;
    return 0;
}
</code>```

The goal here isnt necessarily to lowercase the parameters, but to test a concept. I dont understand why the compiler keeps failing to deduce while telling me some valid candidates afterwards.

答:
Something like this cannot work

```<code>template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )
</code>```

Rule of thumb: you can have only a pack of argument that must be at the end of the list of argument.

So you can reasonably write (and the compiler can deduce) something like

```<code>template <typename V, typename ... T>
string meuPrint(V value, T ... a)
</code>```

but the following will fail

```<code>template <typename V, typename ... T>
string meuPrint(T ... a, V value)
</code>```

Two pack of arguments, as follows,

```<code>template <typename ... U, typename ... T>
string meuPrint(U ... u, T ... t)
</code>```

can't be deduced (where is the border between the pack u and the pack t ?).

If you have two packs of arguments, you have to collect they with something like a std::tuple; something like

```<code>template <typename ... U, typename ... T>
string meuPrint(std::tuple<U ...> u, std::tuple<T ...> t)
</code>```

but the use of variadic tuples can be a little difficult.

Off Topic suggestion: you're using C++11; not the old C. Throw away sprintf() and use the C++ streams facilities.

Is a lot simpler use variadic arguments with streams (you can ignore the format string)

Body:
Im attempting to create a recursive template function, however I keep getting the error:

no matching function for call to meuPrint(int&, Separator&, string&)

while also receiving:

candidate:
  template string meuPrint(U ..., Separator&,string&).

struct Separator {};

template<class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text )
{//end
    char buffer[200];
    sprintf( buffer , text.c_str() , b... );
    return buffer;
}
template<class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , string value , T ...a )
{//string
    return meuPrint( b... , to_lower( value ) , placeholder , text , a... );
}

template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )
{//middle
    return meuPrint( b... , value , placeholder , text , a... );
}

template<class ...T>
string meuPrint( std::string _text , T ...a )
{//start
    Separator placeholder;
    return meuPrint( placeholder , _text , a... );
}

int main( int n , char** args )
{
    string o = meuPrint(  string( "hello %i world" )  ,  8 );
    std::cout << o << std::endl;
    return 0;
}

The goal here isnt necessarily to lowercase the parameters, but to test a concept. I dont understand why the compiler keeps failing to deduce while telling me some valid candidates afterwards.

Body:
Something like this cannot work

template<class V, class ...T, class ...U>
string meuPrint( U ...b , Separator &placeholder , string& text , V value , T ...a )

Rule of thumb: you can have only a pack of argument that must be at the end of the list of argument.

So you can reasonably write (and the compiler can deduce) something like

template <typename V, typename ... T>
string meuPrint(V value, T ... a)

but the following will fail

template <typename V, typename ... T>
string meuPrint(T ... a, V value)

Two pack of arguments, as follows,

template <typename ... U, typename ... T>
string meuPrint(U ... u, T ... t)

can't be deduced (where is the border between the pack u and the pack t ?).

If you have two packs of arguments, you have to collect they with something like a std::tuple; something like

template <typename ... U, typename ... T>
string meuPrint(std::tuple<U ...> u, std::tuple<T ...> t)

but the use of variadic tuples can be a little difficult.

Off Topic suggestion: you're using C++11; not the old C. Throw away sprintf() and use the C++ streams facilities.

Is a lot simpler use variadic arguments with streams (you can ignore the format string)


问:
C++ pointers and references data type
In his book "The C++ Programming Language" (4th edition), the author (Bjarne Stroustrup) says in page 138:

From these types, we can construct other types using declarator operators:

  §7.2 Pointer types (such as int∗)

  §7.3 Array types (such as char[])

  §7.7 Reference types (such as double& and vector<int>&&)

Which confuses me a bit.

I have a basic understanding of pointer, array and reference operators and I know that they are related to memory addresses.

But if I have a code like this:

```<code>#include <iostream>
#include <typeinfo>
#include <conio.h>

using namespace std;

int main()
{
    float Var;

    float& Var_Ref = Var;

    float* Var_ptr;
    Var_ptr = &Var;

    cout << "\n\n Type of Var is " << typeid(Var).name();
    cout << "\n\n Type of Var_ptr is " << typeid(Var).name();
    cout << "\n\n Type of Var_Ref is " << typeid(Var).name();

    getch();

    cout << "\n\n\n";
}
</code>```

And the output is:

I can see that typeid.name() returns the type they are related to not the type of the variables themselves.

I suppose that:

Var_Ref is of type float& (an alias for the float variable Var)

Var_ptr is of type float* (pointer to the variable Var that has a float type)

Especially for the pointer which when printed show an integral hex value of a memory location.

Q: Are these real data types? Am I missing something?

答:
No, these are still real datatypes.

Pointers point to an address space in the memory. For example,

```<code>int test = 5;
int *foo = &test;
</code>```

& will get the address that test is located at. *foo just states that foo will be storing the address.

With this in mind, foo will not = 5. But rather some hex address such as 0xA000125BFFFFFF or something weird like that.

If this helps, some people like to write:

```<code>int* foo
</code>```

So you can think of this as a int pointer called foo.

But, one thing to point out is that all of these are type int. This will apply to another datatype such as float or double or some other custom one.

However, one thing to note is that you cannot do this:

```<code>double test = 5.02;
int *foo = &test;
</code>```

Title: C++ pointers and references data type

Body:
In his book "The C++ Programming Language" (4th edition), the author (Bjarne Stroustrup) says in page 138:

From these types, we can construct other types using declarator operators:

  §7.2 Pointer types (such as int∗)

  §7.3 Array types (such as char[])

  §7.7 Reference types (such as double& and vector<int>&&)

Which confuses me a bit.

I have a basic understanding of pointer, array and reference operators and I know that they are related to memory addresses.

But if I have a code like this:

#include <iostream>
#include <typeinfo>
#include <conio.h>

using namespace std;

int main()
{
    float Var;

    float& Var_Ref = Var;

    float* Var_ptr;
    Var_ptr = &Var;

    cout << "\n\n Type of Var is " << typeid(Var).name();
    cout << "\n\n Type of Var_ptr is " << typeid(Var).name();
    cout << "\n\n Type of Var_Ref is " << typeid(Var).name();

    getch();

    cout << "\n\n\n";
}

And the output is:

I can see that typeid.name() returns the type they are related to not the type of the variables themselves.

I suppose that:

Var_Ref is of type float& (an alias for the float variable Var)

Var_ptr is of type float* (pointer to the variable Var that has a float type)

Especially for the pointer which when printed show an integral hex value of a memory location.

Q: Are these real data types? Am I missing something?

Body:
No, these are still real datatypes.

Pointers point to an address space in the memory. For example,

int test = 5;
int *foo = &test;

& will get the address that test is located at. *foo just states that foo will be storing the address.

With this in mind, foo will not = 5. But rather some hex address such as 0xA000125BFFFFFF or something weird like that.

If this helps, some people like to write:

int* foo

So you can think of this as a int pointer called foo.

But, one thing to point out is that all of these are type int. This will apply to another datatype such as float or double or some other custom one.

However, one thing to note is that you cannot do this:

double test = 5.02;
int *foo = &test;


问:
SystemNullReference while connecting to WebService
I have created a service reference by Visual Studio 2015. Communication works fine but I have to get application free of app.config file. I tried to create own binding and endpoint but in effect I receive SystemNullReference.

Sample of my code:

```<code>    var binding = CreateBinding();
    var endpoint = new EndpointAddress("http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx");
    var Client = new Testowy.Emailver.EmailVerNoTestEmailSoapClient(binding, endpoint );

private static BasicHttpBinding CreateBinding()
        {
            var binding = new BasicHttpBinding();
            binding.Name = "EmailVerNoTestEmailSoap";
            binding.CloseTimeout = TimeSpan.FromMinutes(1);
            binding.OpenTimeout = TimeSpan.FromMinutes(1);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            binding.SendTimeout = TimeSpan.FromMinutes(1);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.MaxBufferSize = 65536;
            binding.MaxBufferPoolSize = 524288;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = System.Text.Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;

            binding.ReaderQuotas.MaxDepth = 32;
            binding.ReaderQuotas.MaxStringContentLength = 8192;
            binding.ReaderQuotas.MaxArrayLength = 16384;
            binding.ReaderQuotas.MaxBytesPerRead = 4096;
            binding.ReaderQuotas.MaxNameTableCharCount = 16384;

            binding.Security.Mode = BasicHttpSecurityMode.None;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            binding.Security.Transport.Realm = "";
            binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
            return binding;
        }
</code>```

System.NullReferenceException: Object reference not set to an instance
  of an object.

Server stack trace:    w
  System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.SecurityChannelFactory1.ClientSecurityChannel1.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation
  operation, EndpointAddress target, Uri via, SecurityToken
  currentToken, TimeSpan timeout)    w
  System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan
  timeout)    w
  System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SecuritySessionClientSettings1.ClientSecuritySessionChannel.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)

  w System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel
  channel, TimeSpan timeout)    w
  System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan
  timeout, CallOnceManager cascade)    w
  System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan
  timeout)    w System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)    w
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)    w
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

Exception rethrown at [0]:    w
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    w
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    w
  WebServices.Testowy.Emailver.EmailVerNoTestEmailSoap.AdvancedVerifyEmail(String
  email, Int32 timeout, String LicenseKey)    w
  WebServices.Test.GetWebService() w
  C:\Users\michal.warchulinski\Source\Repos\Aplixcom_CommonComponents\Aplixcom_CommonComponents\WebServices\ClientClasses.cs:wiersz
  65    w App.Main() w C:\Users\michal.warchulinski\Documents\Visual
  Studio 2015\Projects\Soap\Soap\Program.cs:wiersz 22

Excuse me a lot of text. Any clues what can provide this exeption?

答:
Try calling the Open method on the client before invoking the webservice method. Sometimes it helps solving some object initialization issues.

We can see based on your stack trace, that it actually tried opening the client when you invoked the webservice method. But apparently it tried opening the channel in a different way compared to the Open method.

Unfortunately, I don't have the knowledge to explain why the Open call is sometimes needed and sometimes not.

I'ld be glad if someone could explain that as well.

Body:
I have created a service reference by Visual Studio 2015. Communication works fine but I have to get application free of app.config file. I tried to create own binding and endpoint but in effect I receive SystemNullReference.

Sample of my code:

    var binding = CreateBinding();
    var endpoint = new EndpointAddress("http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx");
    var Client = new Testowy.Emailver.EmailVerNoTestEmailSoapClient(binding, endpoint );

private static BasicHttpBinding CreateBinding()
        {
            var binding = new BasicHttpBinding();
            binding.Name = "EmailVerNoTestEmailSoap";
            binding.CloseTimeout = TimeSpan.FromMinutes(1);
            binding.OpenTimeout = TimeSpan.FromMinutes(1);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            binding.SendTimeout = TimeSpan.FromMinutes(1);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.MaxBufferSize = 65536;
            binding.MaxBufferPoolSize = 524288;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = System.Text.Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;

            binding.ReaderQuotas.MaxDepth = 32;
            binding.ReaderQuotas.MaxStringContentLength = 8192;
            binding.ReaderQuotas.MaxArrayLength = 16384;
            binding.ReaderQuotas.MaxBytesPerRead = 4096;
            binding.ReaderQuotas.MaxNameTableCharCount = 16384;

            binding.Security.Mode = BasicHttpSecurityMode.None;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            binding.Security.Transport.Realm = "";
            binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            binding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
            return binding;
        }

System.NullReferenceException: Object reference not set to an instance
  of an object.

Server stack trace:    w
  System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.SecurityChannelFactory1.ClientSecurityChannel1.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation
  operation, EndpointAddress target, Uri via, SecurityToken
  currentToken, TimeSpan timeout)    w
  System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan
  timeout)    w
  System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan
  timeout)    w
  System.ServiceModel.Security.SecuritySessionClientSettings1.ClientSecuritySessionChannel.OnOpen(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)

  w System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
  timeout)    w
  System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel
  channel, TimeSpan timeout)    w
  System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan
  timeout, CallOnceManager cascade)    w
  System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan
  timeout)    w System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)    w
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)    w
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

Exception rethrown at [0]:    w
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    w
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    w
  WebServices.Testowy.Emailver.EmailVerNoTestEmailSoap.AdvancedVerifyEmail(String
  email, Int32 timeout, String LicenseKey)    w
  WebServices.Test.GetWebService() w
  C:\Users\michal.warchulinski\Source\Repos\Aplixcom_CommonComponents\Aplixcom_CommonComponents\WebServices\ClientClasses.cs:wiersz
  65    w App.Main() w C:\Users\michal.warchulinski\Documents\Visual
  Studio 2015\Projects\Soap\Soap\Program.cs:wiersz 22

Excuse me a lot of text. Any clues what can provide this exeption?


答:
Like mentioned in the comments, it looks like you have re-assigned the built in function str to something else. Find and remove that, and your code should work.

It's also worth noting that in python3 the print() function will attempt to cast your arguments to strings if you separate them with a ,. As seen here:

```<code>print(string, age)
</code>```

Will cast age to a string for you.

Title: How to print a string and integer variable together?

Body:
I have written the following script:

string="My name"
age=19
print(string +str(age))

But this gives an error stating:

"str object is not callable".

Help me to typecast and print.

Body:
Like mentioned in the comments, it looks like you have re-assigned the built in function str to something else. Find and remove that, and your code should work.

It's also worth noting that in python3 the print() function will attempt to cast your arguments to strings if you separate them with a ,. As seen here:

print(string, age)

Will cast age to a string for you.


问:
c struct relationships
```<code>//CHILD
typedef struct Child{
    int id;
}Child;
Child* newChild(){
    Child *aChild = malloc(sizeof(Child));
    aChild->id = 0;
    return aChild;
}

//PARENT
typedef struct Parent{
    int id;
    Child **children;
}Parent;

Parent* newParent(){
    Parent *aParent = malloc(sizeof(Parent));
    aParent->id = 0;
    aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN?
    for(i=0; i<5; i++){
        aParent->children[i] = newChild();
    }
    return aParent;
}
</code>```

Is the newParent() function a correct way to create a struct with an array children? My main concern is the line:

```<code>aParent->children = malloc(sizeof(Child*) * 5);
</code>```

答:
As Let_Me_Be says, there is nothing wrong in principle with the code. However, I'd like to point out if I can that you are probably wanting to do this:

```<code>Parent *p = newParent();
</code>```

But what isn't apparent is that a lot of memory has just been allocated. If you don't keep track of it, or forget to free it, you have a problem. Also, you don't know how many children a Parent has should you wish to resize it. I might suggest:

```<code>typedef struct Parent{
    int id;
    int numchildren;
    Child **children;
}Parent;
</code>```

and I might propose functions like:

```<code>int parent_array_Initialise(Parent *p, int num_children)
{
    p = malloc(sizeof(Parent));
    ...
}

int parent_array_children_resize(Parent *p, int new_children_size);

int parent_array_Free(Parent *p);
</code>```

You then call the functions. The idea would be to return the result of the malloc (size of
array if success, 0 if failure) in each case so you can test the malloc result.

Just my personal taste. Whatever you do, pass the results through valgrind or similar just to make sure you're not leaking memory.

Title: c struct relationships

Body:
//CHILD
typedef struct Child{
    int id;
}Child;
Child* newChild(){
    Child *aChild = malloc(sizeof(Child));
    aChild->id = 0;
    return aChild;
}

//PARENT
typedef struct Parent{
    int id;
    Child **children;
}Parent;

Parent* newParent(){
    Parent *aParent = malloc(sizeof(Parent));
    aParent->id = 0;
    aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN?
    for(i=0; i<5; i++){
        aParent->children[i] = newChild();
    }
    return aParent;
}

Is the newParent() function a correct way to create a struct with an array children? My main concern is the line:

aParent->children = malloc(sizeof(Child*) * 5);

Body:
As Let_Me_Be says, there is nothing wrong in principle with the code. However, I'd like to point out if I can that you are probably wanting to do this:

Parent *p = newParent();

But what isn't apparent is that a lot of memory has just been allocated. If you don't keep track of it, or forget to free it, you have a problem. Also, you don't know how many children a Parent has should you wish to resize it. I might suggest:

typedef struct Parent{
    int id;
    int numchildren;
    Child **children;
}Parent;

and I might propose functions like:

int parent_array_Initialise(Parent *p, int num_children)
{
    p = malloc(sizeof(Parent));
    ...
}

int parent_array_children_resize(Parent *p, int new_children_size);

int parent_array_Free(Parent *p);

You then call the functions. The idea would be to return the result of the malloc (size of
array if success, 0 if failure) in each case so you can test the malloc result.

Just my personal taste. Whatever you do, pass the results through valgrind or similar just to make sure you're not leaking memory.