问:
Any library like STL (vector, map...) in C?

Possible Duplicates:

  Container Class / Library for C

  Is there a good collection library for C-language?

In C++, you have a very useful Standard Template Library (STL) which has structures like vector, map, set...

If I am using plain C, is there any library provide similar structures/functions?

Thanks!

答:
glib is an excellent library with many data structures and useful functions. It is used heavily in the GTK+ widget toolkit.

GLib provides advanced data structures, such as memory chunks, doubly- and singly-linked lists, hash tables, dynamic strings and string utilities, such as a lexical scanner, string chunks (groups of strings), dynamic arrays, balanced binary trees, N-ary trees, quarks (a two-way association of a string and a unique integer identifier), keyed data lists, relations and tuples. Caches provide memory management.

GLib implements functions that provide threads, thread programming and related facilities such as primitive variable access, mutexes, asynchronous queues, secure memory pools, message passing and logging, hook functions (callback registering) and timers. Also message passing facilities such as byte order conversion and I/O channels.

Some other features of GLib include:

standard macros

warnings and assertions

dynamic loading of modules

a type system, GType

an object system, GObject

http://library.gnome.org/devel/glib/


来源: stackexchange

问:
c# code double_it is not working when doubling an integer's value
I am following a tutorial on udemy, and my question is if the c# code double_it is no longer used by unity3d, or if there's some type of library I have to include in my code for it to work. The couse had me write the following code, in order to double an integer's value. The other problem is that I cannot get a variable named temp to work either in my code. It's all part of the same code. </p>

```<code>    void Start ()
    {
            int anumber;
        anumber = double_it (5);
        Debug.Log ("The doubled value is: " + anumber);
    }

    void Update ()
    {
            if double_it(int input_number) {
            var temp = input_number * 2;
            return temp;
        }
    }
}
</code>```

答:
So I found the answer by just following the error codes in MonoDevelop and this is what I got. Well, at least there are no compiler errors this way. I also found that MonoDevelop does not refresh each line of code, until you physically go up or/and down with the arrow.</p>

```<code>    void Start()
    {
        int anumber;
        anumber = double_it (5);
        Debug.Log ("The doubled value is: " + anumber);
        anumber = double_it (12);
        Debug.Log ("The doubled value is: " + anumber);
    }

    void Update()
            {

        if (Input.GetKey ("Right")) {
            transform.Translate (.2f, 0f, 0f);
        }
        if (Input.GetKey ("Left")) {
            transform.Translate (-.2f, 0f, 0f);
        }
        if (Input.GetKey ("Up")) {
            transform.Translate (0f, .2f, 0f);
        }
        if (Input.GetKey ("Down")) {
            transform.Translate (0f, -.2f, 0f);
        }
        }
        int double_it(int input_number)
        {
            var temp = input_number * 2;
            return temp;
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am following a tutorial on udemy, and my question is if the c# code double_it is no longer used by unity3d, or if there's some type of library I have to include in my code for it to work. The couse had me write the following code, in order to double an integer's value. The other problem is that I cannot get a variable named temp to work either in my code. It's all part of the same code.

    void Start ()
    {
            int anumber;
        anumber = double_it (5);
        Debug.Log ("The doubled value is: " + anumber);
    }

    void Update ()
    {
            if double_it(int input_number) {
            var temp = input_number * 2;
            return temp;
        }
    }
}

Body:
So I found the answer by just following the error codes in MonoDevelop and this is what I got. Well, at least there are no compiler errors this way. I also found that MonoDevelop does not refresh each line of code, until you physically go up or/and down with the arrow.

    void Start()
    {
        int anumber;
        anumber = double_it (5);
        Debug.Log ("The doubled value is: " + anumber);
        anumber = double_it (12);
        Debug.Log ("The doubled value is: " + anumber);
    }

    void Update()
            {

        if (Input.GetKey ("Right")) {
            transform.Translate (.2f, 0f, 0f);
        }
        if (Input.GetKey ("Left")) {
            transform.Translate (-.2f, 0f, 0f);
        }
        if (Input.GetKey ("Up")) {
            transform.Translate (0f, .2f, 0f);
        }
        if (Input.GetKey ("Down")) {
            transform.Translate (0f, -.2f, 0f);
        }
        }
        int double_it(int input_number)
        {
            var temp = input_number * 2;
            return temp;
        }
    }


问:
Java repeat part of a program with if and boolean operators
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

```<code>else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;
</code>```

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

答:
hey bro and welcometo the amazing java world ;)

Your could try something like this.

```<code>    boolean ingame= true;
    while ( ingame) {

    System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
    System.out.println("Spieler Eins");
    double playerOne = scan.nextDouble();
    System.out.println("Spieler Zwei");
    double playerTwo = scan.nextDouble();

    double randomValue = Math.random() * 100.0;

    // Math.abs
    double spacingOne = Math.abs(playerOne - randomValue);
    double spacingTwo = Math.abs(playerTwo - randomValue);
    System.out.println("Die Random Zahl war " + randomValue);

    if (spacingOne < spacingTwo) {
        System.out.println("Spieler Eins hat gewonnen!");
    }

    if (spacingOne > spacingTwo) {
        System.out.println("Spieler Zwei hat gewonnen!");
    }

    if (spacingOne == spacingTwo) {
        System.out.println("Unentschieden!");
    }
    System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
    String PlayAgain = scan.nextLine();
    if  (PlayAgain.equals("nein"));
    ingame= false;
}
</code>```

PS: Immer weiter üben, Deutschland braucht mehr JAVA-Entwickler ;)

Body:
Hello I'm fairly new to java and I had troubles in a little test game.
So this is just a part of the code, I want that the user can repeat the part as often as he like with an while operater.

The code is here:

else if (a == 6){
        boolean InGame = true;
        while ( InGame );

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = scan.nextLine();
        if  (PlayAgain == "nein");
        boolean inGame = false;

Well I have never worked alot with booleans due to me being new in java.
Would nice if you could help me out.

Body:
hey bro and welcometo the amazing java world ;)

Your could try something like this.

    boolean ingame= true;
    while ( ingame) {

    System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
    System.out.println("Spieler Eins");
    double playerOne = scan.nextDouble();
    System.out.println("Spieler Zwei");
    double playerTwo = scan.nextDouble();

    double randomValue = Math.random() * 100.0;

    // Math.abs
    double spacingOne = Math.abs(playerOne - randomValue);
    double spacingTwo = Math.abs(playerTwo - randomValue);
    System.out.println("Die Random Zahl war " + randomValue);

    if (spacingOne < spacingTwo) {
        System.out.println("Spieler Eins hat gewonnen!");
    }

    if (spacingOne > spacingTwo) {
        System.out.println("Spieler Zwei hat gewonnen!");
    }

    if (spacingOne == spacingTwo) {
        System.out.println("Unentschieden!");
    }
    System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
    String PlayAgain = scan.nextLine();
    if  (PlayAgain.equals("nein"));
    ingame= false;
}

PS: Immer weiter üben, Deutschland braucht mehr JAVA-Entwickler ;)


问:
Add-in manifest uploaded in organization App catalog does not come up
We have a office-365 online tenant  for our organization. I have created an App catalog for the tenant based on the instructions provided in this link https://dev.office.com/docs/add-ins/publish/set-up-an-add-in-catalog-on-office-365.

I uploaded some new Add-in manifest files in the catalog. However the new Add-ins do not come up immediately in the organization catlog for the desktop clients. The manifest are valid and when I test then using the Sideloading of Add-ins it works fine.

Can someone shed some light on why the new Add-ins do not come up in the catalog ?

I am the admin of the tenant and have full contribute permissions. So i don't think this is a permission issue.

答:
I actually experienced a similar issue.  When you side load the add-in it doesn't do a full validation.

I know of two ways to do the full validation.  One is to grab the latest XSD and do a validation in your preferred xml schema validator tool.  In addition to that you could try to submit it to the app store (you don't have to complete the submission as it validates the schema when you drop the manifest in the first step).

Some gotchas that aren't obvious right off the bat.  Element order matters in the manifest.  Also Resource Ids have a short character limit of 30-35.  In most example manifests "Contoso" will get in under the limit but if you trade that for something much longer you'll be over it.

Addins with schema validation errors won't show in add-in catalogs but will side load successfully.


问:
OKTA SSO SAML Response
Trying to setup a SSO for a Java web application built with Spring MVC.
I've registered my application to an OKTA server, got a Metadata URL and a SignOn URL. I'm using the SignOn URL from my application, authenticating with success, then a POST request is made with some form data that include a SAML Response object.

What should be the next step from here?
I've decoded the SAML response, and now from my understanding I need to get a token or a session ID that I'll need to use to my further requests to the OKTA server.

Edit 1:
Ran the spring-boot-saml-example, the authentication works as expected.
But, when trying to get the current session using OKTA Session API from the Spring application, an HTTP 404 code is returned. Fetching the current session using the browser work fine.

答: Take a look at this blog post, this example uses Spring Security and an Okta SAML app .  Take a look at that, and if that doesn't help let us know.</p>

Title: OKTA SSO SAML Response


问:
How to check user and pass then redirect
This is a template that I use for my project:

http://bootsnipp.com/snippets/featured/custom-login-registration-amp-forgot-password

I want to use that login template with my phpMyAdmin to check username and password.

User input their account then click submit button

After clicking submit button, the icon will change from arrow to animated circle (At this point I want it to check user and password with database phpMyAdmin)

If their account and password match with the database, it will show "Login success" message, and if they don't match, a "Wrong username or password" message will show.

If username and password match, wait for 3 seconds and then redirect to another page.

I don't know how to combine my phpMyAdmin with this login form. So if you know how to do so, please tell or suggest how I can finish this project.

Here is my code:

html,
body {
  background: #efefef;
  padding: 10px;
  font-family: 'Varela Round';
}
/*=== 2. Anchor Link ===*/
a {
  color: #aaaaaa;
  transition: all ease-in-out 200ms;
}
a:hover {
  color: #333333;
  text-decoration: none;
}
/*=== 3. Text Outside the Box ===*/
.etc-login-form {
  color: #919191;
  padding: 10px 20px;
}
.etc-login-form p {
  margin-bottom: 5px;
}
/*=== 4. Main Form ===*/
.login-form-1 {
  max-width: 300px;
  border-radius: 5px;
  display: inline-block;
}
.main-login-form {
  position: relative;
}
.login-form-1 .form-control {
  border: 0;
  box-shadow: 0 0 0;
  border-radius: 0;
  background: transparent;
  color: #555555;
  padding: 7px 0;
  font-weight: bold;
  height:auto;
}
.login-form-1 .form-control::-webkit-input-placeholder {
  color: #999999;
}
.login-form-1 .form-control:-moz-placeholder,
.login-form-1 .form-control::-moz-placeholder,
.login-form-1 .form-control:-ms-input-placeholder {
  color: #999999;
}
.login-form-1 .form-group {
  margin-bottom: 0;
  border-bottom: 2px solid #efefef;
  padding-right: 20px;
  position: relative;
}
.login-form-1 .form-group:last-child {
  border-bottom: 0;
}
.login-group {
  background: #ffffff;
  color: #999999;
  border-radius: 8px;
  padding: 10px 20px;
}
.login-group-checkbox {
  padding: 5px 0;
}
/*=== 5. Login Button ===*/
.login-form-1 .login-button {
  position: absolute;
  right: -25px;
  top: 50%;
  background: #ffffff;
  color: #999999;
  padding: 11px 0;
  width: 50px;
  height: 50px;
  margin-top: -25px;
  border: 5px solid #efefef;
  border-radius: 50%;
  transition: all ease-in-out 500ms;
}
.login-form-1 .login-button:hover {
  color: #555555;
  transform: rotate(450deg);
}
.login-form-1 .login-button.clicked {
  color: #555555;
}
.login-form-1 .login-button.clicked:hover {
  transform: none;
}
.login-form-1 .login-button.clicked.success {
  color: #2ecc71;
}
.login-form-1 .login-button.clicked.error {
  color: #e74c3c;
}
/*=== 6. Form Invalid ===*/
label.form-invalid {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 5;
  display: block;
  margin-top: -25px;
  padding: 7px 9px;
  background: #777777;
  color: #ffffff;
  border-radius: 5px;
  font-weight: bold;
  font-size: 11px;
}
label.form-invalid:after {
  top: 100%;
  right: 10px;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-color: transparent;
  border-top-color: #777777;
  border-width: 6px;
}
/*=== 7. Form - Main Message ===*/
.login-form-main-message {
  background: #ffffff;
  color: #999999;
  border-left: 3px solid transparent;
  border-radius: 3px;
  margin-bottom: 8px;
  font-weight: bold;
  height: 0;
  padding: 0 20px 0 17px;
  opacity: 0;
  transition: all ease-in-out 200ms;
}
.login-form-main-message.show {
  height: auto;
  opacity: 1;
  padding: 10px 20px 10px 17px;
}
.login-form-main-message.success {
  border-left-color: #2ecc71;
}
.login-form-main-message.error {
  border-left-color: #e74c3c;
}
/*=== 8. Custom Checkbox & Radio ===*/
/* Base for label styling */
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked,
[type="radio"]:not(:checked),
[type="radio"]:checked {
  position: absolute;
  left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label,
[type="radio"]:not(:checked) + label,
[type="radio"]:checked + label {
  position: relative;
  padding-left: 25px;
  padding-top: 1px;
  cursor: pointer;
}
/* checkbox aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before,
[type="radio"]:not(:checked) + label:before,
[type="radio"]:checked + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 2px;
  width: 17px;
  height: 17px;
  border: 0px solid #aaa;
  background: #f0f0f0;
  border-radius: 3px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.3);
}
/* checked mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after,
[type="radio"]:not(:checked) + label:after,
[type="radio"]:checked + label:after {
  position: absolute;
  color: #555555;
  transition: all .2s;
}
/* checked mark aspect changes */
[type="checkbox"]:not(:checked) + label:after,
[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  transform: scale(0);
}
[type="checkbox"]:checked + label:after,
[type="radio"]:checked + label:after {
  opacity: 1;
  transform: scale(1);
}
/* disabled checkbox */
[type="checkbox"]:disabled:not(:checked) + label:before,
[type="checkbox"]:disabled:checked + label:before,
[type="radio"]:disabled:not(:checked) + label:before,
[type="radio"]:disabled:checked + label:before {
  box-shadow: none;
  border-color: #8c8c8c;
  background-color: #878787;
}
[type="checkbox"]:disabled:checked + label:after,
[type="radio"]:disabled:checked + label:after {
  color: #555555;
}
[type="checkbox"]:disabled + label,
[type="radio"]:disabled + label {
  color: #8c8c8c;
}
/* accessibility */
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before,
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
  border: 1px dotted #f6f6f6;
}
/* hover style just for information */
label:hover:before {
  border: 1px solid #f6f6f6 !important;
}
/*=== Customization ===*/
/* radio aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
  border-radius: 3px;
}
[type="radio"]:not(:checked) + label:before,
[type="radio"]:checked + label:before {
  border-radius: 35px;
}
/* selected mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
  content: '✔';
  top: 0;
  left: 2px;
  font-size: 14px;
}
[type="radio"]:not(:checked) + label:after,
[type="radio"]:checked + label:after {
  content: '\2022';
  top: 0;
  left: 3px;
  font-size: 30px;
  line-height: 25px;
}
/*=== 9. Misc ===*/
.logo {
  padding: 15px 0;
  font-size: 25px;
  color: #aaaaaa;
  font-weight: bold;
}

/* hebrew */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrkByb1TKJa77egybnpn19yM.woff2) format('woff2');
  unicode-range: U+0590-05FF, U+20AA, U+25CC, U+FB1D-FB4F;
}
/* vietnamese */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrv8zf_FOSsgRmwsS7Aa9k2w.woff2) format('woff2');
  unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrj0LW-43aMEzIO6XUTLjad8.woff2) format('woff2');
  unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrugdm0LZdjqr5-oayXSOefg.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}

button:focus {
    outline:none !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<!-- All the files that are required -->

<!-- Where all the magic happens -->
<!-- LOGIN FORM -->

  <div class="text-center" style="padding:50px 0">
   <div class="logo">Login to Smartmeter system</div>
   <!-- Main Form -->
   <div class="login-form-1">
    <form id="login-form" class="text-left">
     <div class="login-form-main-message"></div>
     <div class="main-login-form">
      <div class="login-group">
       <div class="form-group">
        <label for="lg_username" class="sr-only">Username</label>
        <input type="text" class="form-control" id="lg_username" name="lg_username" placeholder="Username">
       </div>
       <div class="form-group">
        <label for="lg_password" class="sr-only">Password</label>
        <input type="password" class="form-control" id="lg_password" name="lg_password" placeholder="Password">
       </div>
      </div>
      <button type="submit" class="login-button"><i class="fa fa-chevron-right"></i></button>
     </div>
     <div class="etc-login-form">
        <center><p>Additional Text can input here</a></p></center>
     </div>
    </form>
   </div>
   <!-- end:Main Form -->
  </div>

<!-- Ajax Script -->

<script type="text/javascript">
(function($) {
    "use strict";

 // Options for Message
 //----------------------------------------------
  var options = {
   'btn-loading': '<i class="fa fa-spinner fa-pulse"></i>',
   'btn-success': '<i class="fa fa-check"></i>',
   'btn-error': '<i class="fa fa-remove"></i>',
   'msg-success': 'Login Success! Redirecting...',
   'msg-error': 'Wrong login credentials!',
   'useAJAX': true,
  };

 // Login Form
 //----------------------------------------------
 // Validation
  $("#login-form").validate({
   rules: {
      lg_username: "required",
     lg_password: "required",
    },
   errorClass: "form-invalid"
  });

 // Form Submission
  $("#login-form").submit(function() {
   remove_loading($(this));

  if(options['useAJAX'] == true)
  {
   // Dummy AJAX request (Replace this with your AJAX code)
    // If you don't want to use AJAX, remove this
     dummy_submit_form($(this));

    // Cancel the normal submission.
    // If you don't want to use AJAX, remove this
     return false;
  }
  });

 // Register Form
 //----------------------------------------------
 // Validation
  $("#register-form").validate({
   rules: {
      reg_username: "required",
     reg_password: {
     required: true,
     minlength: 5
    },
     reg_password_confirm: {
     required: true,
     minlength: 5,
     equalTo: "#register-form [name=reg_password]"
    },
    reg_email: {
       required: true,
     email: true
    },
    reg_agree: "required",
    },
   errorClass: "form-invalid",
   errorPlacement: function( label, element ) {
     if( element.attr( "type" ) === "checkbox" || element.attr( "type" ) === "radio" ) {
      element.parent().append( label ); // this would append the label after all your checkboxes/labels (so the error-label will be the last element in <div class="controls"> )
     }
   else {
      label.insertAfter( element ); // standard behaviour
     }
    }
  });

  // Form Submission
  $("#register-form").submit(function() {
   remove_loading($(this));

  if(options['useAJAX'] == true)
  {
   // Dummy AJAX request (Replace this with your AJAX code)
    // If you don't want to use AJAX, remove this
     dummy_submit_form($(this));

    // Cancel the normal submission.
    // If you don't want to use AJAX, remove this
     return false;
  }
  });

 // Forgot Password Form
 //----------------------------------------------
 // Validation
  $("#forgot-password-form").validate({
   rules: {
      fp_email: "required",
    },
   errorClass: "form-invalid"
  });

 // Form Submission
  $("#forgot-password-form").submit(function() {
   remove_loading($(this));

  if(options['useAJAX'] == true)
  {
   // Dummy AJAX request (Replace this with your AJAX code)
    // If you don't want to use AJAX, remove this
     dummy_submit_form($(this));

    // Cancel the normal submission.
    // If you don't want to use AJAX, remove this
     return false;
  }
  });

 // Loading
 //----------------------------------------------
  function remove_loading($form)
  {
   $form.find('[type=submit]').removeClass('error success');
   $form.find('.login-form-main-message').removeClass('show error success').html('');
  }

  function form_loading($form)
  {
    $form.find('[type=submit]').addClass('clicked').html(options['btn-loading']);
  }

  function form_success($form)
  {
   $form.find('[type=submit]').addClass('success').html(options['btn-success']);
   $form.find('.login-form-main-message').addClass('show success').html(options['msg-success']);
  }

  function form_failed($form)
  {
   $form.find('[type=submit]').addClass('error').html(options['btn-error']);
   $form.find('.login-form-main-message').addClass('show error').html(options['msg-error']);
  }

 // Dummy Submit Form (Remove this)
 //----------------------------------------------
 // This is just a dummy form submission. You should use your AJAX function or remove this function if you are not using AJAX.
  function dummy_submit_form($form)
  {
   if($form.valid())
   {
    form_loading($form);

    setTimeout(function() {
     form_success($form);
    }, 2000);
   }
  }

})(jQuery);
</script>
</body>
</html></code>```

connect.php

```<code><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "consumption";
$tbname = "user";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn -> connect_error){
    die ("connection failed: " . $conn -> connect_error);
}
</code>```

答:
Edit your html to this

<!DOCTYPE html>

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

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

Login to Smartmeter system

    <form id="login-form" class="text-left">

        Username
        <input type="text" class="form-control" id="lg_username" name="lg_username" placeholder="Username">

        Password
        <input type="password" class="form-control" id="lg_password" name="lg_password" placeholder="Password">

      <button type="submit" class="login-button"></button>

Additional Text can input here

    </form>

```

Body:
This is a template that I use for my project:

http://bootsnipp.com/snippets/featured/custom-login-registration-amp-forgot-password

I want to use that login template with my phpMyAdmin to check username and password.

User input their account then click submit button

After clicking submit button, the icon will change from arrow to animated circle (At this point I want it to check user and password with database phpMyAdmin)

If their account and password match with the database, it will show "Login success" message, and if they don't match, a "Wrong username or password" message will show.

If username and password match, wait for 3 seconds and then redirect to another page.

I don't know how to combine my phpMyAdmin with this login form. So if you know how to do so, please tell or suggest how I can finish this project.

Here is my code:

html,
body {
  background: #efefef;
  padding: 10px;
  font-family: 'Varela Round';
}
/*=== 2. Anchor Link ===*/
a {
  color: #aaaaaa;
  transition: all ease-in-out 200ms;
}
a:hover {
  color: #333333;
  text-decoration: none;
}
/*=== 3. Text Outside the Box ===*/
.etc-login-form {
  color: #919191;
  padding: 10px 20px;
}
.etc-login-form p {
  margin-bottom: 5px;
}
/*=== 4. Main Form ===*/
.login-form-1 {
  max-width: 300px;
  border-radius: 5px;
  display: inline-block;
}
.main-login-form {
  position: relative;
}
.login-form-1 .form-control {
  border: 0;
  box-shadow: 0 0 0;
  border-radius: 0;
  background: transparent;
  color: #555555;
  padding: 7px 0;
  font-weight: bold;
  height:auto;
}
.login-form-1 .form-control::-webkit-input-placeholder {
  color: #999999;
}
.login-form-1 .form-control:-moz-placeholder,
.login-form-1 .form-control::-moz-placeholder,
.login-form-1 .form-control:-ms-input-placeholder {
  color: #999999;
}
.login-form-1 .form-group {
  margin-bottom: 0;
  border-bottom: 2px solid #efefef;
  padding-right: 20px;
  position: relative;
}
.login-form-1 .form-group:last-child {
  border-bottom: 0;
}
.login-group {
  background: #ffffff;
  color: #999999;
  border-radius: 8px;
  padding: 10px 20px;
}
.login-group-checkbox {
  padding: 5px 0;
}
/*=== 5. Login Button ===*/
.login-form-1 .login-button {
  position: absolute;
  right: -25px;
  top: 50%;
  background: #ffffff;
  color: #999999;
  padding: 11px 0;
  width: 50px;
  height: 50px;
  margin-top: -25px;
  border: 5px solid #efefef;
  border-radius: 50%;
  transition: all ease-in-out 500ms;
}
.login-form-1 .login-button:hover {
  color: #555555;
  transform: rotate(450deg);
}
.login-form-1 .login-button.clicked {
  color: #555555;
}
.login-form-1 .login-button.clicked:hover {
  transform: none;
}
.login-form-1 .login-button.clicked.success {
  color: #2ecc71;
}
.login-form-1 .login-button.clicked.error {
  color: #e74c3c;
}
/*=== 6. Form Invalid ===*/
label.form-invalid {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 5;
  display: block;
  margin-top: -25px;
  padding: 7px 9px;
  background: #777777;
  color: #ffffff;
  border-radius: 5px;
  font-weight: bold;
  font-size: 11px;
}
label.form-invalid:after {
  top: 100%;
  right: 10px;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-color: transparent;
  border-top-color: #777777;
  border-width: 6px;
}
/*=== 7. Form - Main Message ===*/
.login-form-main-message {
  background: #ffffff;
  color: #999999;
  border-left: 3px solid transparent;
  border-radius: 3px;
  margin-bottom: 8px;
  font-weight: bold;
  height: 0;
  padding: 0 20px 0 17px;
  opacity: 0;
  transition: all ease-in-out 200ms;
}
.login-form-main-message.show {
  height: auto;
  opacity: 1;
  padding: 10px 20px 10px 17px;
}
.login-form-main-message.success {
  border-left-color: #2ecc71;
}
.login-form-main-message.error {
  border-left-color: #e74c3c;
}
/*=== 8. Custom Checkbox & Radio ===*/
/* Base for label styling */
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked,
[type="radio"]:not(:checked),
[type="radio"]:checked {
  position: absolute;
  left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label,
[type="radio"]:not(:checked) + label,
[type="radio"]:checked + label {
  position: relative;
  padding-left: 25px;
  padding-top: 1px;
  cursor: pointer;
}
/* checkbox aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before,
[type="radio"]:not(:checked) + label:before,
[type="radio"]:checked + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 2px;
  width: 17px;
  height: 17px;
  border: 0px solid #aaa;
  background: #f0f0f0;
  border-radius: 3px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.3);
}
/* checked mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after,
[type="radio"]:not(:checked) + label:after,
[type="radio"]:checked + label:after {
  position: absolute;
  color: #555555;
  transition: all .2s;
}
/* checked mark aspect changes */
[type="checkbox"]:not(:checked) + label:after,
[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  transform: scale(0);
}
[type="checkbox"]:checked + label:after,
[type="radio"]:checked + label:after {
  opacity: 1;
  transform: scale(1);
}
/* disabled checkbox */
[type="checkbox"]:disabled:not(:checked) + label:before,
[type="checkbox"]:disabled:checked + label:before,
[type="radio"]:disabled:not(:checked) + label:before,
[type="radio"]:disabled:checked + label:before {
  box-shadow: none;
  border-color: #8c8c8c;
  background-color: #878787;
}
[type="checkbox"]:disabled:checked + label:after,
[type="radio"]:disabled:checked + label:after {
  color: #555555;
}
[type="checkbox"]:disabled + label,
[type="radio"]:disabled + label {
  color: #8c8c8c;
}
/* accessibility */
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before,
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
  border: 1px dotted #f6f6f6;
}
/* hover style just for information */
label:hover:before {
  border: 1px solid #f6f6f6 !important;
}
/*=== Customization ===*/
/* radio aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
  border-radius: 3px;
}
[type="radio"]:not(:checked) + label:before,
[type="radio"]:checked + label:before {
  border-radius: 35px;
}
/* selected mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
  content: '✔';
  top: 0;
  left: 2px;
  font-size: 14px;
}
[type="radio"]:not(:checked) + label:after,
[type="radio"]:checked + label:after {
  content: '\2022';
  top: 0;
  left: 3px;
  font-size: 30px;
  line-height: 25px;
}
/*=== 9. Misc ===*/
.logo {
  padding: 15px 0;
  font-size: 25px;
  color: #aaaaaa;
  font-weight: bold;
}

/* hebrew */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrkByb1TKJa77egybnpn19yM.woff2) format('woff2');
  unicode-range: U+0590-05FF, U+20AA, U+25CC, U+FB1D-FB4F;
}
/* vietnamese */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrv8zf_FOSsgRmwsS7Aa9k2w.woff2) format('woff2');
  unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrj0LW-43aMEzIO6XUTLjad8.woff2) format('woff2');
  unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
  font-family: 'Varela Round';
  font-style: normal;
  font-weight: 400;
  src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrugdm0LZdjqr5-oayXSOefg.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}

button:focus {
    outline:none !important;
}

<!DOCTYPE html>

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

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

Login to Smartmeter system

    <form id="login-form" class="text-left">

        Username
        <input type="text" class="form-control" id="lg_username" name="lg_username" placeholder="Username">

        Password
        <input type="password" class="form-control" id="lg_password" name="lg_password" placeholder="Password">

      <button type="submit" class="login-button"></button>

Additional Text can input here

    </form>

connect.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "consumption";
$tbname = "user";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn -> connect_error){
    die ("connection failed: " . $conn -> connect_error);
}

Body:
Edit your html to this

<!DOCTYPE html>
<html lang="en">
<head>
  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<!-- All the files that are required -->

<!-- Where all the magic happens -->
<!-- LOGIN FORM -->

  <div class="text-center" style="padding:50px 0">
   <div class="logo">Login to Smartmeter system</div>
   <!-- Main Form -->
   <div class="login-form-1">
    <form id="login-form" class="text-left">
     <div class="login-form-main-message"></div>
     <div class="main-login-form">
      <div class="login-group">
       <div class="form-group">
        <label for="lg_username" class="sr-only">Username</label>
        <input type="text" class="form-control" id="lg_username" name="lg_username" placeholder="Username">
       </div>
       <div class="form-group">
        <label for="lg_password" class="sr-only">Password</label>
        <input type="password" class="form-control" id="lg_password" name="lg_password" placeholder="Password">
       </div>
      </div>
      <button type="submit" class="login-button"><i class="fa fa-chevron-right"></i></button>
     </div>
     <div class="etc-login-form">
        <center><p>Additional Text can input here</a></p></center>
     </div>
    </form>
   </div>
   <!-- end:Main Form -->
  </div>

<!-- Ajax Script -->

<script type="text/javascript">
(function($) {
    "use strict";

 // Options for Message
 //----------------------------------------------
  var options = {
   'btn-loading': '<i class="fa fa-spinner fa-pulse"></i>',
   'btn-success': '<i class="fa fa-check"></i>',
   'btn-error': '<i class="fa fa-remove"></i>',
   'msg-success': 'Login Success! Redirecting...',
   'msg-error': 'Wrong login credentials!',
   'useAJAX': true,
  };

 // Login Form
 //----------------------------------------------
 // Validation
  $("#login-form").validate({
   rules: {
      lg_username: "required",
     lg_password: "required",
    },
   errorClass: "form-invalid"
  });

 // Form Submission
  $("#login-form").submit(function() {
   remove_loading($(this));

  if(options['useAJAX'] == true)
  {
   // Dummy AJAX request (Replace this with your AJAX code)
    // If you don't want to use AJAX, remove this
     dummy_submit_form($(this));
  window.location.href = "mypage.php";
    // Cancel the normal submission.
    // If you don't want to use AJAX, remove this
     return false;
  }
  });

 // Register Form
 //----------------------------------------------
 // Validation
  $("#register-form").validate({
   rules: {
      reg_username: "required",
     reg_password: {
     required: true,
     minlength: 5
    },
     reg_password_confirm: {
     required: true,
     minlength: 5,
     equalTo: "#register-form [name=reg_password]"
    },
    reg_email: {
       required: true,
     email: true
    },
    reg_agree: "required",
    },
   errorClass: "form-invalid",
   errorPlacement: function( label, element ) {
     if( element.attr( "type" ) === "checkbox" || element.attr( "type" ) === "radio" ) {
      element.parent().append( label ); // this would append the label after all your checkboxes/labels (so the error-label will be the last element in <div class="controls"> )
     }
   else {
      label.insertAfter( element ); // standard behaviour
     }
    }
  });

  // Form Submission
  $("#register-form").submit(function() {
   remove_loading($(this));

  if(options['useAJAX'] == true)
  {
   // Dummy AJAX request (Replace this with your AJAX code)
    // If you don't want to use AJAX, remove this
     dummy_submit_form($(this));

    // Cancel the normal submission.
    // If you don't want to use AJAX, remove this
     return false;
  }
  });

 // Forgot Password Form
 //----------------------------------------------
 // Validation
  $("#forgot-password-form").validate({
   rules: {
      fp_email: "required",
    },
   errorClass: "form-invalid"
  });

 // Form Submission
  $("#forgot-password-form").submit(function() {
   remove_loading($(this));

  if(options['useAJAX'] == true)
  {
   // Dummy AJAX request (Replace this with your AJAX code)
    // If you don't want to use AJAX, remove this
     dummy_submit_form($(this));

    // Cancel the normal submission.
    // If you don't want to use AJAX, remove this
     return false;
  }
  });

 // Loading
 //----------------------------------------------
  function remove_loading($form)
  {
   $form.find('[type=submit]').removeClass('error success');
   $form.find('.login-form-main-message').removeClass('show error success').html('');
  }

  function form_loading($form)
  {
    $form.find('[type=submit]').addClass('clicked').html(options['btn-loading']);
  }

  function form_success($form)
  {
   $form.find('[type=submit]').addClass('success').html(options['btn-success']);
   $form.find('.login-form-main-message').addClass('show success').html(options['msg-success']);
  }

  function form_failed($form)
  {
   $form.find('[type=submit]').addClass('error').html(options['btn-error']);
   $form.find('.login-form-main-message').addClass('show error').html(options['msg-error']);
  }

 // Dummy Submit Form (Remove this)
 //----------------------------------------------
 // This is just a dummy form submission. You should use your AJAX function or remove this function if you are not using AJAX.
  function dummy_submit_form($form)
  {
   if($form.valid())
   {
    form_loading($form);

    setTimeout(function() {
     form_success($form);
    }, 2000);
   }
  }

})(jQuery);
</script>
</body>
</html>


问:
Calling a variable from one function to the other (Python)
I'll start by saying that I did look up answers to this question and unfortunately, I just couldn't understand them or they didn't seem to work for me. This is of course down to me rather than the people who answered the question, so I do apologise in advance.

So pretty much I'm trying to call a variable that is assigned by the user from one function to the other, I'll give an example:

```<code>def function_one():
    a = input("What is your name?")
    return a
def function_two():
    print("Nice to meet you, "a)

function_one()
function_two()
</code>```

This of course does not work and I'm sure that is down to my own stupidity, I wasn't sure why at first because I saw other people saying to simply return the variable, which I did!

I also tried calling the variable from the other function, for example:

```<code>def function_two()
    a = function_one()
</code>```

but I realised that was pretty stupid since I'm just assigning that function  as a, so it's not going to work.

I'd appreciate some insight, I know these are not the kind of questions you'd expect but yeah... I'm clueless.

答:
you do have it. this should work.

```<code>def function_two():
    a = function_one()
    print('hi {}'.format(a))
</code>```

then

```<code>>>>function_two()
</code>```

Body:
I'll start by saying that I did look up answers to this question and unfortunately, I just couldn't understand them or they didn't seem to work for me. This is of course down to me rather than the people who answered the question, so I do apologise in advance.

So pretty much I'm trying to call a variable that is assigned by the user from one function to the other, I'll give an example:

def function_one():
    a = input("What is your name?")
    return a
def function_two():
    print("Nice to meet you, "a)

function_one()
function_two()

This of course does not work and I'm sure that is down to my own stupidity, I wasn't sure why at first because I saw other people saying to simply return the variable, which I did!

I also tried calling the variable from the other function, for example:

def function_two()
    a = function_one()

but I realised that was pretty stupid since I'm just assigning that function  as a, so it's not going to work.

I'd appreciate some insight, I know these are not the kind of questions you'd expect but yeah... I'm clueless.

Body:
you do have it. this should work.

def function_two():
    a = function_one()
    print('hi {}'.format(a))

then

>>>function_two()


问:
WCF error "Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding"
I'm trying to run a webservice on a Windows Server 2012 R2, but I get the following error

Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding. Registered base address schemes are [http].

The solutions I have tried so far :

Could not find a base address that matches scheme net.tcp (the first two answers)

My web.config file

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="Binding1" >
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    <services>
      <service name="ServerName" behaviorConfiguration="ServerInternet" >
        <endpoint address=""
            binding="netTcpBinding"
            bindingConfiguration="Binding1"
            contract="Namespace.Interface"
            bindingNamespace="http://www.mycompany.com/webservices"
        />

        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8080/WebService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServerInternet">
          <!-- certificate infos here -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
</code>```

The advanced settings :

The functionalities I have installed on the server :

Pool settings :

Classic pipeline

CLR .NET 4.0

LocalService Identity

The site bindings

What could be the reasons of this error?

答: The problem would be that you don't have TCP Activation and TCP Port Sharing enabled in server manager, which doesn't add up, as this is required for net.tcp in IIS.</p>

Body:
I'm trying to run a webservice on a Windows Server 2012 R2, but I get the following error

Could not find a base address that matches scheme net.tcp for the endpoint with binding NetTcpBinding. Registered base address schemes are [http].

The solutions I have tried so far :

Could not find a base address that matches scheme net.tcp (the first two answers)

My web.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="Binding1" >
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
    <services>
      <service name="ServerName" behaviorConfiguration="ServerInternet" >
        <endpoint address=""
            binding="netTcpBinding"
            bindingConfiguration="Binding1"
            contract="Namespace.Interface"
            bindingNamespace="http://www.mycompany.com/webservices"
        />

        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8080/WebService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServerInternet">

          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

The advanced settings :

The functionalities I have installed on the server :

Pool settings :

Classic pipeline

CLR .NET 4.0

LocalService Identity

The site bindings

What could be the reasons of this error?


问:
stop button activity if function returns false
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

```<code>register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...
</code>```

答:
Try this</p>

```<code>if (!valid_email)
    return;
</code>```

Body:
I have a onclick button and a function to check if email is valid.
If it is not valid it will return false.

What I want is a way to stop the button action if it is false.

Is there a way, like die(); in php to stop button action if boolean is false?

register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                Boolean valid_email = isValidEmail(email);

//how can I stop the onclick if boolean is false?

                Response.Listener<String> responseListener = new Response.Listener<String>(){

                    @Override
                    public void onResponse(String response){
                        try {
...

Body:
Try this

if (!valid_email)
    return;


问:
How do I run a sql query using shell script for mysql server. I am new to shell scripting.
Server : MySQL
Query : SQL
Requirement : Shell Script

How do I run a sql query using shell script for mysql server.
This will help me in automating the task.

答:
```<code>mysql -u USER -p PASSWORD -h MYSQLSERVERNAME -e 'select * from foo...' database-name
</code>```


问:
Check if a number is prime or not in mysql
I am wondering what's the best way to check whether a number is prime or not using sql. I was able to generate the sequence of numbers from 1 to 1000 but I would like to identify which number is a prime. Can somebody share your thoughts on this.Thanks.</p>

```<code>SELECT i
  FROM
(
select
     i0.i
    +i1.i*2
    +i2.i*4
    +i3.i*8
    +i4.i*16
    +i5.i*32
    +i6.i*64
    +i7.i*128
    +i8.i*256
    +i9.i*512
    as i
from
               (select 0 as i union select 1) as i0
    cross join (select 0 as i union select 1) as i1
    cross join (select 0 as i union select 1) as i2
    cross join (select 0 as i union select 1) as i3
    cross join (select 0 as i union select 1) as i4
    cross join (select 0 as i union select 1) as i5
    cross join (select 0 as i union select 1) as i6
    cross join (select 0 as i union select 1) as i7
    cross join (select 0 as i union select 1) as i8
    cross join (select 0 as i union select 1) as i9
) Z
WHERE i>=1 AND i<=1000;
</code>```

答:
This is not a good fit for SQL.  But you can do it as:

```<code>select n.*
from n
where not exists (select 1
                  from n n2
                  where n2.n <= sqrt(n.n) and n2.n > 1 and
                        n.n mod n2.n = 0
                 ) and
      n > 1;  -- 1 is deemed to not be prime
</code>```

You may need to wait a little while to start seeing numbers.

I should note that in MySQL, a shorter way to generate the numbers is:

```<code>select (@rn := @rn + 1) as i
from (select 0 as i union select 1) as i0 cross join
     (select 0 as i union select 1) as i1 cross join
     (select 0 as i union select 1) as i2 cross join
     (select 0 as i union select 1) as i3 cross join
     (select 0 as i union select 1) as i4 cross join
     (select 0 as i union select 1) as i5 cross join
     (select 0 as i union select 1) as i6 cross join
     (select 0 as i union select 1) as i7 cross join
     (select 0 as i union select 1) as i8 cross join
     (select 0 as i union select 1) as i9 cross join
     (select @rn := 0) params
having i >= 1 and i <= 1000;
</code>```

This should be faster because no intermediate table is materialized.  In addition, adding 1 is probably slightly faster than the arithmetic, although the difference is calculation may be rather small.

Body:
I am wondering what's the best way to check whether a number is prime or not using sql. I was able to generate the sequence of numbers from 1 to 1000 but I would like to identify which number is a prime. Can somebody share your thoughts on this.Thanks.

SELECT i
  FROM
(
select
     i0.i
    +i1.i*2
    +i2.i*4
    +i3.i*8
    +i4.i*16
    +i5.i*32
    +i6.i*64
    +i7.i*128
    +i8.i*256
    +i9.i*512
    as i
from
               (select 0 as i union select 1) as i0
    cross join (select 0 as i union select 1) as i1
    cross join (select 0 as i union select 1) as i2
    cross join (select 0 as i union select 1) as i3
    cross join (select 0 as i union select 1) as i4
    cross join (select 0 as i union select 1) as i5
    cross join (select 0 as i union select 1) as i6
    cross join (select 0 as i union select 1) as i7
    cross join (select 0 as i union select 1) as i8
    cross join (select 0 as i union select 1) as i9
) Z
WHERE i>=1 AND i<=1000;

Body:
This is not a good fit for SQL.  But you can do it as:

select n.*
from n
where not exists (select 1
                  from n n2
                  where n2.n <= sqrt(n.n) and n2.n > 1 and
                        n.n mod n2.n = 0
                 ) and
      n > 1;  -- 1 is deemed to not be prime

You may need to wait a little while to start seeing numbers.

I should note that in MySQL, a shorter way to generate the numbers is:

select (@rn := @rn + 1) as i
from (select 0 as i union select 1) as i0 cross join
     (select 0 as i union select 1) as i1 cross join
     (select 0 as i union select 1) as i2 cross join
     (select 0 as i union select 1) as i3 cross join
     (select 0 as i union select 1) as i4 cross join
     (select 0 as i union select 1) as i5 cross join
     (select 0 as i union select 1) as i6 cross join
     (select 0 as i union select 1) as i7 cross join
     (select 0 as i union select 1) as i8 cross join
     (select 0 as i union select 1) as i9 cross join
     (select @rn := 0) params
having i >= 1 and i <= 1000;

This should be faster because no intermediate table is materialized.  In addition, adding 1 is probably slightly faster than the arithmetic, although the difference is calculation may be rather small.


问:
Old App Icon showing in Open In ... menu on iOS
I am updating an iOS application.  I have created new App Icons and everything works except the Open In menu.  The Home App Icon is correct, the App Icon in Settings is correct, but the App Icon in the Open In menu is the old App Icon.

My UTI document type shows the new small icon on the attachment.

Anybody know where the old App Icon is hiding?

Thanks, Allen

答:
Have you tried:

In iPhone, delete the app

In Xcode, clean derived data

Reinstall the app

It looks like the icon is somehow cached.


问:
Context of class with listener - spring-rabbitmq, internals and injecting beans based on contain of message
I am using spring-boot and spring-rabbitmq package. I have some config class and class representing client. This client class has one listener annotated with @RabbitListener.  Everything is fine with my config and client - it does work.

However, I need to know some details about internals of this client class. Is something special set in a context ?   I would like to be able to inject one of three available datasources (three beans). I mean that I would like to be able based on the first symbol of message (thanks to custom converter I can assume that this symbol happens) that actual datasource bean will be injected/used.

Any ideas? Maybe spring-rabbitmq modifies in some way context ?

答:
The class with @RabbitListener must be declared as a bean in application context (either way - out of scope of the question). And it must be singleton - created only once object. Therefore all the injections must be done during its instantiation/initialization.

So, during that @RabbitListener method invocation you should just choose a proper DataSource, for example from the:

```<code>@Autowired
Map<String, DataSource> dataSources;
</code>```

What you describe in your question isn't a behavior of Spring Dependency Injection Container.

Body:
The class with @RabbitListener must be declared as a bean in application context (either way - out of scope of the question). And it must be singleton - created only once object. Therefore all the injections must be done during its instantiation/initialization.

So, during that @RabbitListener method invocation you should just choose a proper DataSource, for example from the:

@Autowired
Map<String, DataSource> dataSources;

What you describe in your question isn't a behavior of Spring Dependency Injection Container.


问:
All nodejs functions asyncronously running?
I was trying to learn about async/promises/callbacks/js modules/etc... However, when I was trying to run a simple module which only required a file, and ran a function that only returned the parameter back, node was not outputting the result correctly. By this I mean that it would only sometimes return the value, and sometimes not.

I am pretty new so I could be wrong, but from what I understand this is async in node(?). But while researching I was only finding functions which do things like load, wait, timeout, etc. in lists for things that use async. But it seems that everything I run in node, no matter how simple runs with async and will not consistently output values? Here is an example of what I ran and recieved in the node console:

```<code>> function test(input){
... return input;
... }
> test('a')

> test('a')
'a'
>
> test(5)

> test(5)
5
>
</code>```

Like I said, I was working on learning about a few things, but it started by looking into modules, so I was also wondering what a common 'pattern'(?) for handling this is, when exporting modules. Thanks.

Edit:

I'm not sure if I made it very clear, but for the most part I was really just wondering why a function as simple as this wouldn't be working, when the only functions I have seen people talk about async with are functions that are obviously waiting, in a sense. Not simple functions like this. I havent tried putting a callback with this yet, but I assume that works. I just didn't think you needed them for functions as simple as this?

答:
Use something like this   </p>

```<code>function test(input,callback){
 return callback(input);
}

test('a',function(s){console.log(s)})
</code>```

Body:
I was trying to learn about async/promises/callbacks/js modules/etc... However, when I was trying to run a simple module which only required a file, and ran a function that only returned the parameter back, node was not outputting the result correctly. By this I mean that it would only sometimes return the value, and sometimes not.

I am pretty new so I could be wrong, but from what I understand this is async in node(?). But while researching I was only finding functions which do things like load, wait, timeout, etc. in lists for things that use async. But it seems that everything I run in node, no matter how simple runs with async and will not consistently output values? Here is an example of what I ran and recieved in the node console:

> function test(input){
... return input;
... }
> test('a')

> test('a')
'a'
>
> test(5)

> test(5)
5
>

Like I said, I was working on learning about a few things, but it started by looking into modules, so I was also wondering what a common 'pattern'(?) for handling this is, when exporting modules. Thanks.

Edit:

I'm not sure if I made it very clear, but for the most part I was really just wondering why a function as simple as this wouldn't be working, when the only functions I have seen people talk about async with are functions that are obviously waiting, in a sense. Not simple functions like this. I havent tried putting a callback with this yet, but I assume that works. I just didn't think you needed them for functions as simple as this?

Body:
Use something like this

function test(input,callback){
 return callback(input);
}

test('a',function(s){console.log(s)})


问:
Selenium explicit wait upper limit
I'm using Selenium to do some automated testing in a C# app.  I have a component that's not disappearing after the 90 seconds explicit wait.  Is there an upper limit to the timeout:

```<code>Driver.WaitUntil(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector("section > h1 > img")), 90);
</code>```

I haven't found anything indicating there's an upper limit.

答: Cannot say about explicit wait upper limit, but if you want to make it more you can put the wait in loop. So the loop will make it 90*number of loops.</p>

Title: Selenium explicit wait upper limit

Body:
I'm using Selenium to do some automated testing in a C# app.  I have a component that's not disappearing after the 90 seconds explicit wait.  Is there an upper limit to the timeout:

Driver.WaitUntil(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector("section > h1 > img")), 90);

I haven't found anything indicating there's an upper limit.


答:
Another way is to use this:

```<code> def ask_for_users_name():
      name = input("What is your name?")
      greet_user(name)

 def greet_user(user_name):
     print("Nice to meet you,"+user_name)

 ask_for_users_name()
</code>```

You merely call ask_for_users_name() at the end.

Edit:

greet_user_() is a void function, which means it does not return anything. In this case, all it does is receive input passed to it and prints it. If you want to perform other operations, you can pass it additional parameters, or keep it the way it is.

Version 1:

```<code> def ask_for_users_name():
     name = input("What is your name?")
     age = int(input("What is your age? "))
     print("Your age is ", age)
     greet_user(name)

 def greet_user(user_name):
     print("Nice to meet you,"+user_name)

 ask_for_users_name()
</code>```

In version 1, we are still utilizing greet_user() to just print one thing, and performing another print operation in ask_for_users_name().

Version 2:

```<code>def ask_for_users_name():
     name = input("What is your name?")
     age = int(input("What is your age? "))
     greet_user(name, age)

def greet_user(user_name, user_age):
     print("Nice to meet you,"+user_name)
     print("Your age is", user_age)

ask_for_users_name()
</code>```

In version 2, we are passing both age and name to greet_user(), which in turn prints out the passed variables. I hope this helps.

Title: Calling a variable from one function to the other (Python)

Body:
Another way is to use this:

 def ask_for_users_name():
      name = input("What is your name?")
      greet_user(name)

 def greet_user(user_name):
     print("Nice to meet you,"+user_name)

 ask_for_users_name()

You merely call ask_for_users_name() at the end.

Edit:

greet_user_() is a void function, which means it does not return anything. In this case, all it does is receive input passed to it and prints it. If you want to perform other operations, you can pass it additional parameters, or keep it the way it is.

Version 1:

 def ask_for_users_name():
     name = input("What is your name?")
     age = int(input("What is your age? "))
     print("Your age is ", age)
     greet_user(name)

 def greet_user(user_name):
     print("Nice to meet you,"+user_name)

 ask_for_users_name()

In version 1, we are still utilizing greet_user() to just print one thing, and performing another print operation in ask_for_users_name().

Version 2:

def ask_for_users_name():
     name = input("What is your name?")
     age = int(input("What is your age? "))
     greet_user(name, age)

def greet_user(user_name, user_age):
     print("Nice to meet you,"+user_name)
     print("Your age is", user_age)

ask_for_users_name()

In version 2, we are passing both age and name to greet_user(), which in turn prints out the passed variables. I hope this helps.


问:
Symfony2 SonataMediaBundle Audio Config
I need to use SonataMediaBundle to store audio files - mp3 and maybe also somehow conwert them also to ogg.

So basically I need config.

Currently I have this:

```<code>sonata_media:
default_context: default
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr
contexts:
    default:  # the default context is mandatory
        providers:
            - sonata.media.provider.dailymotion
            - sonata.media.provider.youtube
            - sonata.media.provider.image
            - sonata.media.provider.file

        formats:
            small: { width: 100 , quality: 70}
            big:   { width: 500 , quality: 70}
    user:
        providers:
            - sonata.media.provider.file
        formats:
            mp3: { quality: 100}
            ogg: { quality: 100}

cdn:
    server:
        path: /uploads/media # http://media.sonata-project.org/

filesystem:
    local:
        directory:  %kernel.root_dir%/uploads/media
        create:     true
class:
    media:  Application\Sonata\MediaBundle\Entity\Media
</code>```

But when I Im using command:

php.exe C:\xampp\htdocs\Radiooo\app\console sonata:media:add sonata.media.provider.file user C:/test.mp3

Im getting file stored like 45914671541816acb68412cc66ba1a71da3ac7a1.mpga

Can you help me what Im doing wrong?

答:
First of all: I'm totally aware of the creation date of this question, but I recently stumbled upon the same problem, where I wanted to upload a mp3 file and just keep the file extension to mp3 instead of switching it to mpga. And as far as I can see, there was no easy solution added to the source code in the last three years ...

I'm pretty sure that my solution is not the best one, but it does the job with a small amount of code to add :)

In my project, I had to upload a file by setting the BinaryContent of a Media object to the Symfony Request class, which leads the Problem to exactly this line:

```<code>// FileProvider.php#L483
$guesser = ExtensionGuesser::getInstance();
$extension = $guesser->guess($media->getContentType());
</code>```

The FileProvider class fetches the instance of the ExtensionGuesser from Symfony and lets him do the work of guessing what the extension for the given ContentType should be:

```<code>// MimeTypeExtensionGuesser.php#L623
'audio/mpeg' => 'mpga',
</code>```

In my opinion it would be great, if we could either add own MimeType->Extension mappings or simply replace the class of the ExtensionGuesser with a small change in the configuration files. But no one knew that three people like us do not want to upload a mp3 file and switch the extension to mpga ... so there was no solution like these.

But we can actually change the className of the FileProvider and just overwrite the method that we want to do something different:

```<code>// app/config/services.yml
parameters:
    sonata.media.provider.file.class: Application\Sonata\MediaBundle\Provider\FileProvider

// Application\Sonata\MediaBundle\Provider\FileProvider:
<?php

namespace Application\Sonata\MediaBundle\Provider;

use Sonata\MediaBundle\Extra\ApiMediaFile;
use Sonata\MediaBundle\Model\MediaInterface;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class FileProvider
 *
 * @package Application\Sonata\MediaBundle\Provider
 */
class FileProvider extends \Sonata\MediaBundle\Provider\FileProvider
{
    /**
     * @var array
     */
    protected $contentTypeMapping = [
        'audio/mpeg' => 'mp3'
    ];

    /**
     * Set media binary content according to request content.
     *
     * @param MediaInterface $media
     */
    protected function generateBinaryFromRequest(MediaInterface $media)
    {
        if (php_sapi_name() === 'cli') {
            throw new \RuntimeException('The current process cannot be executed in cli environment');
        }

        if (!$media->getContentType()) {
            throw new \RuntimeException(
                'You must provide the content type value for your media before setting the binary content'
            );
        }

        $request = $media->getBinaryContent();

        if (!$request instanceof Request) {
            throw new \RuntimeException('Expected Request in binary content');
        }

        $content   = $request->getContent();
        $extension = $this->getExtension($media->getContentType());

        $handle = tmpfile();
        fwrite($handle, $content);
        $file = new ApiMediaFile($handle);
        $file->setExtension($extension);
        $file->setMimetype($media->getContentType());

        $media->setBinaryContent($file);
    }

    /**
     * Returns the fileExtension for a given contentType
     *
     * First of all, we have to look at our own mapping and if we have no mapping defined, just use the ExtensionGuesser
     *
     * @param string $contentType
     *
     * @return string
     */
    private function getExtension($contentType)
    {
        if (array_key_exists($contentType, $this->contentTypeMapping)) {
            return $this->contentTypeMapping[$contentType];
        }

        // create unique id for media reference
        $guesser   = ExtensionGuesser::getInstance();
        $extension = $guesser->guess($contentType);

        if (!$extension) {
            throw new \RuntimeException(
                sprintf('Unable to guess extension for content type %s', $contentType)
            );
        }

        return $extension;
    }
}
</code>```

Until now it works pretty well and I had no problem with it :)

Title: Symfony2 SonataMediaBundle Audio Config

Body:
I need to use SonataMediaBundle to store audio files - mp3 and maybe also somehow conwert them also to ogg.

So basically I need config.

Currently I have this:

sonata_media:
default_context: default
db_driver: doctrine_orm # or doctrine_mongodb, doctrine_phpcr
contexts:
    default:  # the default context is mandatory
        providers:
            - sonata.media.provider.dailymotion
            - sonata.media.provider.youtube
            - sonata.media.provider.image
            - sonata.media.provider.file

        formats:
            small: { width: 100 , quality: 70}
            big:   { width: 500 , quality: 70}
    user:
        providers:
            - sonata.media.provider.file
        formats:
            mp3: { quality: 100}
            ogg: { quality: 100}

cdn:
    server:
        path: /uploads/media # http://media.sonata-project.org/

filesystem:
    local:
        directory:  %kernel.root_dir%/uploads/media
        create:     true
class:
    media:  Application\Sonata\MediaBundle\Entity\Media

But when I Im using command:

php.exe C:\xampp\htdocs\Radiooo\app\console sonata:media:add sonata.media.provider.file user C:/test.mp3

Im getting file stored like 45914671541816acb68412cc66ba1a71da3ac7a1.mpga

Can you help me what Im doing wrong?

Body:
First of all: I'm totally aware of the creation date of this question, but I recently stumbled upon the same problem, where I wanted to upload a mp3 file and just keep the file extension to mp3 instead of switching it to mpga. And as far as I can see, there was no easy solution added to the source code in the last three years ...

I'm pretty sure that my solution is not the best one, but it does the job with a small amount of code to add :)

In my project, I had to upload a file by setting the BinaryContent of a Media object to the Symfony Request class, which leads the Problem to exactly this line:

// FileProvider.php#L483
$guesser = ExtensionGuesser::getInstance();
$extension = $guesser->guess($media->getContentType());

The FileProvider class fetches the instance of the ExtensionGuesser from Symfony and lets him do the work of guessing what the extension for the given ContentType should be:

// MimeTypeExtensionGuesser.php#L623
'audio/mpeg' => 'mpga',

In my opinion it would be great, if we could either add own MimeType->Extension mappings or simply replace the class of the ExtensionGuesser with a small change in the configuration files. But no one knew that three people like us do not want to upload a mp3 file and switch the extension to mpga ... so there was no solution like these.

But we can actually change the className of the FileProvider and just overwrite the method that we want to do something different:

// app/config/services.yml
parameters:
    sonata.media.provider.file.class: Application\Sonata\MediaBundle\Provider\FileProvider

// Application\Sonata\MediaBundle\Provider\FileProvider:
<?php

namespace Application\Sonata\MediaBundle\Provider;

use Sonata\MediaBundle\Extra\ApiMediaFile;
use Sonata\MediaBundle\Model\MediaInterface;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class FileProvider
 *
 * @package Application\Sonata\MediaBundle\Provider
 */
class FileProvider extends \Sonata\MediaBundle\Provider\FileProvider
{
    /**
     * @var array
     */
    protected $contentTypeMapping = [
        'audio/mpeg' => 'mp3'
    ];

    /**
     * Set media binary content according to request content.
     *
     * @param MediaInterface $media
     */
    protected function generateBinaryFromRequest(MediaInterface $media)
    {
        if (php_sapi_name() === 'cli') {
            throw new \RuntimeException('The current process cannot be executed in cli environment');
        }

        if (!$media->getContentType()) {
            throw new \RuntimeException(
                'You must provide the content type value for your media before setting the binary content'
            );
        }

        $request = $media->getBinaryContent();

        if (!$request instanceof Request) {
            throw new \RuntimeException('Expected Request in binary content');
        }

        $content   = $request->getContent();
        $extension = $this->getExtension($media->getContentType());

        $handle = tmpfile();
        fwrite($handle, $content);
        $file = new ApiMediaFile($handle);
        $file->setExtension($extension);
        $file->setMimetype($media->getContentType());

        $media->setBinaryContent($file);
    }

    /**
     * Returns the fileExtension for a given contentType
     *
     * First of all, we have to look at our own mapping and if we have no mapping defined, just use the ExtensionGuesser
     *
     * @param string $contentType
     *
     * @return string
     */
    private function getExtension($contentType)
    {
        if (array_key_exists($contentType, $this->contentTypeMapping)) {
            return $this->contentTypeMapping[$contentType];
        }

        // create unique id for media reference
        $guesser   = ExtensionGuesser::getInstance();
        $extension = $guesser->guess($contentType);

        if (!$extension) {
            throw new \RuntimeException(
                sprintf('Unable to guess extension for content type %s', $contentType)
            );
        }

        return $extension;
    }
}

Until now it works pretty well and I had no problem with it :)


问:
Ubuntu OpenCV not compiling
I'm trying to compile OpenCV 3.2 with contributions with the following commands:

```<code>1.
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local/ -DOPENCV_EXTRA_MODULES_PATH=/home/matteo/Desktop/Xilinx/OpenCV/source/opencv_contrib/modules/ /home/matteo/Desktop/Xilinx/OpenCV/source/opencv-3.2.0/
2.
make -j7 # runs 7 jobs in parallel
3.
sudo make install
</code>```

Can you explain why I get

```<code>...
........
...........
........................
-- VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
-- Caffe:   NO
-- Protobuf:   NO
-- Glog:   NO
-- Downloading ...
CMake Error at cmake/OpenCVUtils.cmake:1043 (file):
  file DOWNLOAD cannot open file for write.
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

CMake Error at cmake/OpenCVUtils.cmake:1047 (message):
  Failed to download .  Status=
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

-- Configuring incomplete, errors occurred!
</code>```

I'm working with Ubuntu 16.04 . I already had OpenCV on the system: maybe I unistall it in the wrong way? I remember to compile OpenCV 3.2 with the same command used above.

答:
I get the same error, that exact error, around the protobuf. There's another error on the xfeatures2d module, too, if your delete the dnn modules (so they don't get configured/built). My problem is, I need the "non-free" xfeatures2d module. :(

The problem appears to be in the opencv_contrib, in the DNN and xfeatures2d modules, but I'm not sure how to fix it. the call to ocv_download seems to be having empty inputs, even though the dnn and xfeatures2d cmake files are passing in arguments. I am not even a novice with cmake, so I'm not sure how to troubleshoot further.

I get this error on both Mac configuring for XCode and on Windows configuring for Visual Studio, using the latest version of cmake-gui, 3.8.0-rc3.

EDIT: I think I've found the issue, though. I opened an issue in the opencv_contrib github. There is a call to ocv_download in the dnn and xfeatures2d cmake files that uses FILENAME as the first parameter, but should be using PACKAGE instead. When I changed the parameters to PACKAGE, CMake successfully configured opencv with the opencv_contrib modules.

Hope this helps! :)

Title: Ubuntu OpenCV not compiling

Body:
I'm trying to compile OpenCV 3.2 with contributions with the following commands:

1.
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local/ -DOPENCV_EXTRA_MODULES_PATH=/home/matteo/Desktop/Xilinx/OpenCV/source/opencv_contrib/modules/ /home/matteo/Desktop/Xilinx/OpenCV/source/opencv-3.2.0/
2.
make -j7 # runs 7 jobs in parallel
3.
sudo make install

Can you explain why I get

...
........
...........
........................
-- VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
-- Caffe:   NO
-- Protobuf:   NO
-- Glog:   NO
-- Downloading ...
CMake Error at cmake/OpenCVUtils.cmake:1043 (file):
  file DOWNLOAD cannot open file for write.
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

CMake Error at cmake/OpenCVUtils.cmake:1047 (message):
  Failed to download .  Status=
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

-- Configuring incomplete, errors occurred!

I'm working with Ubuntu 16.04 . I already had OpenCV on the system: maybe I unistall it in the wrong way? I remember to compile OpenCV 3.2 with the same command used above.


问:
"many to many to many" relation
I have a simple database of cosmetics. Each product may consist of multiple ingredients. Therefore it is a simple many to many relation and currently I have a database like this:

```<code>CREATE TABLE `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredients` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredient_to_product` (
  `ingredient_id` INT UNSIGNED NOT NULL,
  `product_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ingredient_id`, `product_id`),
  INDEX (`product_id`)
);
</code>```

However, some ingredients can have many different names. For example: "LINALOOL ESSENTIAL OIL", "LINALYL ALCOHOL" and "3,7-DIMETHYL-1,6-OCTADIEN-3-OL" refers to the same ingredient.

When I am presenting one product, I would like to keep ingredient name as on product label. So in case of one product it will be "LINALYL ALCOHOL" and in case of another product it may be something other, but referring to identical ingredient.

Now I would like to query database for all names of the product by specifying one of its names or by its ID, however how one ID could refer to many names? Do I have to keep two tables: one for specific ingredient in general and another table just for names (relation many names to one ingredient)? Is there any better way?

答:
I suppose the good news is that one name cannot be used for multiple different ingredients, right?

So yes, you probably need an "ingredient name" table, something like

```<code>`name` TEXT NOT NULL,
`ingredient_id` INT UNSIGNED NOT NULL
</code>```

(I'd probably just use name as the PK here, but if your design calls for always using surrogates then also add ingredient_name_id I guess...)

And then the details of the ingredient (except name) would still go in ingredient table.  (You could keep a default name in the ingredient table as well, but I wouldn't.  If you need that concept, I'd consider adding a "default flag" to the ingredient name table or something like that.)

Since you want to know the name used for each ingredient by a given product, you would replace your current "ingredient to product xref" with an "ingredient-name to product xref".

Title: "many to many to many" relation

Body:
I have a simple database of cosmetics. Each product may consist of multiple ingredients. Therefore it is a simple many to many relation and currently I have a database like this:

CREATE TABLE `products` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredients` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` TEXT NOT NULL,
  PRIMARY KEY (`id`),
);

CREATE TABLE `ingredient_to_product` (
  `ingredient_id` INT UNSIGNED NOT NULL,
  `product_id` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ingredient_id`, `product_id`),
  INDEX (`product_id`)
);

However, some ingredients can have many different names. For example: "LINALOOL ESSENTIAL OIL", "LINALYL ALCOHOL" and "3,7-DIMETHYL-1,6-OCTADIEN-3-OL" refers to the same ingredient.

When I am presenting one product, I would like to keep ingredient name as on product label. So in case of one product it will be "LINALYL ALCOHOL" and in case of another product it may be something other, but referring to identical ingredient.

Now I would like to query database for all names of the product by specifying one of its names or by its ID, however how one ID could refer to many names? Do I have to keep two tables: one for specific ingredient in general and another table just for names (relation many names to one ingredient)? Is there any better way?

Body:
I suppose the good news is that one name cannot be used for multiple different ingredients, right?

So yes, you probably need an "ingredient name" table, something like

`name` TEXT NOT NULL,
`ingredient_id` INT UNSIGNED NOT NULL

(I'd probably just use name as the PK here, but if your design calls for always using surrogates then also add ingredient_name_id I guess...)

And then the details of the ingredient (except name) would still go in ingredient table.  (You could keep a default name in the ingredient table as well, but I wouldn't.  If you need that concept, I'd consider adding a "default flag" to the ingredient name table or something like that.)

Since you want to know the name used for each ingredient by a given product, you would replace your current "ingredient to product xref" with an "ingredient-name to product xref".


问:
Performance benchmark: PHP Generated content VS. javascript and DOM over AJAX
For the following pretty straightforward task: query a list of products from a DB and present it on a webpage,
consider 2 setups:

Setup1: PHP script queries. All content is built on the server and the entire page is served back to the client.

Setup2: Static HTML "page skeleton" requesting content using AJAX. Received content is parsed on the client side using Javascript and rendered using innerHTML or similar.

Of course the second setup only makes sense when you have pages, categories and tags for the client user to choose from.

I need to compare these two, at least by means of:

time it will take content to be served

user experience (setup1 is delivered as a whole, setup2 is delivered in "two parts")

scalability - how do the setups compare when I have 100,000 queries daily

Any thoughts on the issue will be much appreciated.

答:
You may find the following question helpful: Smarty Vs. Javascript/AJAX

I brought up a few points in my answer to that question:

You should use server-side scripts to show any data that is known at the moment the page is loaded. In this case, you know the list of products should be displayed. The fact that a question's answers should be shown is known at page load.

You should only use AJAX calls to load dynamic data that is not known at the moment the page is loaded. For example, when you click the "comments" link under a question or answer on Stack Overflow. The fact that you want to view a particular question's comments is not known at page load.

Javascript should not be required to access core functionality of your site.

You should gracefully degrade functionality when Javascript is disabled. For example, Stack Overflow works just fine with Javascript disabled. You don't have access to real-time Markdown previews or dynamic badge notices, but the core functionality is still intact.

A single HTTP request to a server-generated page will load significantly faster than a request to load a page that makes five or six additional AJAX calls, especially on high latency connections (like cellular networks). See Yahoo's Best Practices for Speeding Up Your Website.

You should think of Javascript as a bonus feature that might not be enabled, not as something that should be used to construct critical pieces of your website. There are exceptions to this rule. If you want to do some sort of pagination in which you click a "next page" button and only the product list changes, AJAX might be the right choice. You should, however, make sure users without Javascript are not excluded from viewing the entire list.

There's nothing more frustrating than when a page can't be accessed because the web developer didn't obey the KISS principle. As an example, take Friendly's Restaurants. I wanted to check out their menu while I was at the mall, so I loaded their website on my iPhone, only to find out that you literally can't get any meaningful information about the restaurant without Flash. It's nice to have fancy menus with swooshing desserts flying everywhere, but in the end, I just wanted to see the items on their menu. I couldn't do that because they required Flash. Graceful degradation in service would have been helpful in that case.

Some things on the web can't be done effectively without Javascript. Displaying a list of products is not one of them. If you are still unsure, look at how other popular websites do things. I think you'll find most of the successful, well-engineered websites follow the guidelines listed above.

OwnerDisplayName: gnosis

OwnerDisplayName: William Brendel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: William Brendel


问:
How to search (using regex) for a regex literal in text?
I just stumbled on a case where I had to remove quotes surrounding a specific regex pattern in a file, and the immediate conclusion I came to was to use vim's search and replace util and just escape each special character in the original and replacement patterns.

This worked (after a little tinkering), but it left me wondering if there is a better way to do these sorts of things.

The original regex (quoted): '/^\//' to be replaced with /^\//

And the search/replace pattern I used:

s/'\/\^\\\/\/'/\/\^\\\/\//g

Thanks!

答:
You can use almost any character as the regex delimiter.  This will save you from having to escape forward slashes.  You can also use groups to extract the regex and avoid re-typing it.  For example, try this:

```<code>:s#'\(\\^\\//\)'#\1#
</code>```

I do not know if this will work for your case, because the example you listed and the regex you gave do not match up.  (The regex you listed will match '/^\//', not '\^\//'. Mine will match the latter. Adjust as necessary.)

Body:
You can use almost any character as the regex delimiter.  This will save you from having to escape forward slashes.  You can also use groups to extract the regex and avoid re-typing it.  For example, try this:

:s#'\(\\^\\//\)'#\1#

I do not know if this will work for your case, because the example you listed and the regex you gave do not match up.  (The regex you listed will match '/^\//', not '\^\//'. Mine will match the latter. Adjust as necessary.)


问:
jQuery reset star-rating.js
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

```<code> $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }
</code>```

Please help on how to reset these stars to zero or null.

Here is the full code.

```<code> $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});
</code>```

答:
You could try something like this; an attempt to set default blank stars on initial page load, or Click.

```<code>$(document).ready(function() {
    $('i').addClass('fa-star-o');
});
</code>```

Then refresh page to rest:

```<code>$( ".reset" ).click(function() {
    location.reload();
});
</code>```

If you don't want to refresh page, you could try:

```<code>$( ".reset" ).click(function() {
   $('i').addClass('fa-star-o');
});
</code>```

You may have to re-initiate your click feature on the star with similar jQuery to re add the appropriate Class when needed.

If this doesn't help or work; could you create a https://jsfiddle.net/ to fully replicate your issue; and then we could solve it. If it were me; I'd find a better plugin to use or just write it from scratch at that point.

Title: jQuery reset star-rating.js

Body:
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

 $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }

Please help on how to reset these stars to zero or null.

Here is the full code.

 $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});

Body:
You could try something like this; an attempt to set default blank stars on initial page load, or Click.

$(document).ready(function() {
    $('i').addClass('fa-star-o');
});

Then refresh page to rest:

$( ".reset" ).click(function() {
    location.reload();
});

If you don't want to refresh page, you could try:

$( ".reset" ).click(function() {
   $('i').addClass('fa-star-o');
});

You may have to re-initiate your click feature on the star with similar jQuery to re add the appropriate Class when needed.

If this doesn't help or work; could you create a https://jsfiddle.net/ to fully replicate your issue; and then we could solve it. If it were me; I'd find a better plugin to use or just write it from scratch at that point.


答:
Something like:</p>

```<code>if(!isValidEmail(email))
    return;

//the rest of your code goes here...
</code>```

Title: stop button activity if function returns false

Body:
Something like:

if(!isValidEmail(email))
    return;

//the rest of your code goes here...


问:
Error: spawn sh ENOENT Node.js
I am trying to trigger PIFM on my raspberry Pi by tweets from a specific twitter account using node.js. However when I run twitpifm.js on the command line:

```<code>node twitpifm.js
</code>```

I get the following error:

```<code>events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: spawn sh ENOENT
    at exports._errnoException (util.js:874:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at doNTCallback2 (node.js:439:9)
    at process._tickCallback (node.js:353:17)
    at Function.Module.runMain (module.js:469:11)
    at startup (node.js:134:18)
    at node.js:961:3
</code>```

I am using this version of PIFM on my PI2

https://github.com/asmello/fm_transmitter

I have written a script (test.sh) that will start PIFm from command line without parameters

```<code> #!/bin/bash
    /home/pi/PIFm/fm_transmitter/bin/Release/fm_transmitter music.wav 103.50
</code>```

I am aware that I need to need to use a child_process within my node.js to activate this shell script but am having trouble with it;

First I invoke child process with:

```<code>var spawn = require('child_process').spawn // child process.spawn
</code>```

I then try to trigger the shell with the following:

```<code>function thisTweet(){

    spawn('sh', ['test.sh'], {  // shell script I want to run.
    cwd:' /home/pi/Desktop/Twitter', // current working directory where my twitpifm.js file is
    env: Object.assign({}, process.env, { PATH: process.env.PATH + '/home/pi/PIFm/fm_transmitter' }) //this sets a path to where test.sh is
    })
</code>```

Any suggestions would be great!

答:
Ok..I got a solution that seems to be working using . execfile from here:

https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback

This code worked:

```<code>const execFile = require('child_process').execFile;
const child = execFile('sh', ['/home/pi/Desktop/twitter/test'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});
}
</code>```

This lets me execute a shell script from node.js

Title: Error: spawn sh ENOENT Node.js

Body:
I am trying to trigger PIFM on my raspberry Pi by tweets from a specific twitter account using node.js. However when I run twitpifm.js on the command line:

node twitpifm.js

I get the following error:

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: spawn sh ENOENT
    at exports._errnoException (util.js:874:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at doNTCallback2 (node.js:439:9)
    at process._tickCallback (node.js:353:17)
    at Function.Module.runMain (module.js:469:11)
    at startup (node.js:134:18)
    at node.js:961:3

I am using this version of PIFM on my PI2

https://github.com/asmello/fm_transmitter

I have written a script (test.sh) that will start PIFm from command line without parameters

 #!/bin/bash
    /home/pi/PIFm/fm_transmitter/bin/Release/fm_transmitter music.wav 103.50

I am aware that I need to need to use a child_process within my node.js to activate this shell script but am having trouble with it;

First I invoke child process with:

var spawn = require('child_process').spawn // child process.spawn

I then try to trigger the shell with the following:

function thisTweet(){

    spawn('sh', ['test.sh'], {  // shell script I want to run.
    cwd:' /home/pi/Desktop/Twitter', // current working directory where my twitpifm.js file is
    env: Object.assign({}, process.env, { PATH: process.env.PATH + '/home/pi/PIFm/fm_transmitter' }) //this sets a path to where test.sh is
    })

Any suggestions would be great!

Body:
Ok..I got a solution that seems to be working using . execfile from here:

https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback

This code worked:

const execFile = require('child_process').execFile;
const child = execFile('sh', ['/home/pi/Desktop/twitter/test'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});
}

This lets me execute a shell script from node.js