问:
openstack API python - no module named version
I'm trying to instanciate VM on openstack using the NovaClient API in python. More precisely with mq-rabbit celery tasks.

Unfortunatly I got this error :

```<code>from novaclient import client
File "/usr/local/lib/python2.7/dist-packages/novaclient/__init__.py", line 15, in <module>
import pbr.version
ImportError: No module named version
</code>```

I already tested with a simple python file and it works, my VM was created but when I try to do this throught a celery tash I got the error above...

My version is the latest python-novaclient-6.0.2, but as our servers are in version 2 I use the version 2 API.
Here is my code in my celery task, who works when I test in python shell :

```<code>loader = loading.get_plugin_loader('password')
    auth = loader.load_from_options(auth_url=auth_url, username=username, password=password, project_name=tenant_name)
    sess = session.Session(auth=auth)
    nova = client.Client('2', session=sess) #API version and session
</code>```

答:
Seems it's the same error and this one

Basically what you need is to make sure you have pbr installed.

If you had it already, reinstalling might help

pip uninstall pbr

pip install pbr

Body:
I'm trying to instanciate VM on openstack using the NovaClient API in python. More precisely with mq-rabbit celery tasks.

Unfortunatly I got this error :

from novaclient import client
File "/usr/local/lib/python2.7/dist-packages/novaclient/__init__.py", line 15, in <module>
import pbr.version
ImportError: No module named version

I already tested with a simple python file and it works, my VM was created but when I try to do this throught a celery tash I got the error above...

My version is the latest python-novaclient-6.0.2, but as our servers are in version 2 I use the version 2 API.
Here is my code in my celery task, who works when I test in python shell :

loader = loading.get_plugin_loader('password')
    auth = loader.load_from_options(auth_url=auth_url, username=username, password=password, project_name=tenant_name)
    sess = session.Session(auth=auth)
    nova = client.Client('2', session=sess) #API version and session


来源: stackexchange

问:
How to make a responsive menu with simple jquery and css
I am trying a simple responsive menu with Css and jQuery. I want the jQuery script to work only on a certain window width. When I resize the browser. Here is my code.

$(document).ready(function(){
   $(".resmenu").click(function(){
    $(".menu").slideToggle();
   });

   $(".submenu").click(function(){
    $(this).toggleClass("active_submenu");
    $(this).parent().find(".dropdown").slideToggle();
   });

  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
 width:980px;
 margin:100px auto 0 auto;
 font-family:arial;
}

ul, li {
 margin:0;
 padding:0;
}

.resmenu {
 display:none;
}

.menu li {
 display: inline-block;
 position: relative;
}
.menu li a {
 font-size: 14px;
 text-transform: uppercase;
 color: #3b2612;
 padding: 6px 17px;
 letter-spacing: 1px;
 display: block;
 text-decoration: none;
}
.menu li:hover a {
 background: #444;
 color: #fff !important;
}

.menu li ul {
 position: absolute;
 width: 250px;
 z-index: 5;
 left: 0px;
 top:28px;
 display:none;

}
.menu li:hover ul {
 display:block;
}
.menu li ul li {
 display: block;
}

.menu li ul li a {
 padding: 6px 17px;
 transition: all 0.2s;
 text-transform: capitalize;
}
.menu li ul li a:hover {
 background: #000;
}

/*--- responsive ----*/
@media screen and (max-width:768px) {

.resmenu {
 color: #fff !important;
 display: block;
 text-decoration: none !important;
 background: #6ca2bd;
 padding: 5px 10px;
}
.menu {
 display: none;
 background: #444444;
}
.menu li {
 position: relative;
 display: block;
}
.menu li a {
 color: #fff;
 font-size:14px;
 padding: 6px 17px;
}
.menu li a:hover {
 background-color: #000;
 color: #000;
 transition: all 0.3s;
}
.active_submenu {
 background-color: #ceb689 !important;
 color: #fff !important;
}

.menu li ul {
 display: none;
 width: 100%;
 position: relative;
 top: 0px;
 display:none;

}
.menu li:hover ul {
 display: none;
 top: 0px;
}

.menu li a.active {
 color: #fff;
 font-family: 'opensanssemibold';
}

.menu li ul li a {
 background:#333;
}

}</code>```

       Menu

Menu

Dropdown One

Dropdown

Dropdown

Dropdown

Dropdown

Dropdown Two

Dropdown

Dropdown

Dropdown

Dropdown

Menu

Menu

```

It is working on 768px screen size, but when I click on the drop-down link instead of hover on more than 768 screen size, the drop down link is slide toggle. I need this script work on certain width only.

答:
Use $(window).width() to get the width of the screen and use it in your condition:

```<code>if ($(window).width() < 768) {
         // run your code here
}
</code>```

See code snippet:

$(document).ready(function() {
  $(".resmenu").click(function() {
    $(".menu").slideToggle();
  });

  $(".submenu").click(function() {
    if ($(window).width() < 768) {
      $(this).toggleClass("active_submenu");
      $(this).parent().find(".dropdown").slideToggle();
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 980px;
  margin: 100px auto 0 auto;
  font-family: arial;
}

ul,
li {
  margin: 0;
  padding: 0;
}

.resmenu {
  display: none;
}

.menu li {
  display: inline-block;
  position: relative;
}

.menu li a {
  font-size: 14px;
  text-transform: uppercase;
  color: #3b2612;
  padding: 6px 17px;
  letter-spacing: 1px;
  display: block;
  text-decoration: none;
}

.menu li:hover a {
  background: #444;
  color: #fff !important;
}

.menu li ul {
  position: absolute;
  width: 250px;
  z-index: 5;
  left: 0px;
  top: 28px;
  display: none;
}

.menu li:hover ul {
  display: block;
}

.menu li ul li {
  display: block;
}

.menu li ul li a {
  padding: 6px 17px;
  transition: all 0.2s;
  text-transform: capitalize;
}

.menu li ul li a:hover {
  background: #000;
}

/*--- responsive ----*/

@media screen and (min-width:769px) {
  .menu {
    display: block!important;
  }
}

@media screen and (max-width:768px) {
  .resmenu {
    color: #fff !important;
    display: block;
    text-decoration: none !important;
    background: #6ca2bd;
    padding: 5px 10px;
  }
  .menu {
    display: none;
    background: #444444;
  }
  .menu li {
    position: relative;
    display: block;
  }
  .menu li a {
    color: #fff;
    font-size: 14px;
    padding: 6px 17px;
  }
  .menu li a:hover {
    background-color: #000;
    color: #000;
    transition: all 0.3s;
  }
  .active_submenu {
    background-color: #ceb689 !important;
    color: #fff !important;
  }
  .menu li ul {
    display: none;
    width: 100%;
    position: relative;
    top: 0px;
    display: none;
  }
  .menu li:hover ul {
    display: none;
    top: 0px;
  }
  .menu li a.active {
    color: #fff;
    font-family: 'opensanssemibold';
  }
  .menu li ul li a {
    background: #333;
  }
}</code>```

    Menu

Menu

Dropdown One

Dropdown

Dropdown

Dropdown

Dropdown

Dropdown Two

Dropdown

Dropdown

Dropdown

Dropdown

Menu

Menu

```

ContentLicense: CC BY-SA 3.0

Body:
I am trying a simple responsive menu with Css and jQuery. I want the jQuery script to work only on a certain window width. When I resize the browser. Here is my code.

$(document).ready(function(){
   $(".resmenu").click(function(){
    $(".menu").slideToggle();
   });

   $(".submenu").click(function(){
    $(this).toggleClass("active_submenu");
    $(this).parent().find(".dropdown").slideToggle();
   });

  });

.container {
 width:980px;
 margin:100px auto 0 auto;
 font-family:arial;
}

ul, li {
 margin:0;
 padding:0;
}

.resmenu {
 display:none;
}

.menu li {
 display: inline-block;
 position: relative;
}
.menu li a {
 font-size: 14px;
 text-transform: uppercase;
 color: #3b2612;
 padding: 6px 17px;
 letter-spacing: 1px;
 display: block;
 text-decoration: none;
}
.menu li:hover a {
 background: #444;
 color: #fff !important;
}

.menu li ul {
 position: absolute;
 width: 250px;
 z-index: 5;
 left: 0px;
 top:28px;
 display:none;

}
.menu li:hover ul {
 display:block;
}
.menu li ul li {
 display: block;
}

.menu li ul li a {
 padding: 6px 17px;
 transition: all 0.2s;
 text-transform: capitalize;
}
.menu li ul li a:hover {
 background: #000;
}

/*--- responsive ----*/
@media screen and (max-width:768px) {

.resmenu {
 color: #fff !important;
 display: block;
 text-decoration: none !important;
 background: #6ca2bd;
 padding: 5px 10px;
}
.menu {
 display: none;
 background: #444444;
}
.menu li {
 position: relative;
 display: block;
}
.menu li a {
 color: #fff;
 font-size:14px;
 padding: 6px 17px;
}
.menu li a:hover {
 background-color: #000;
 color: #000;
 transition: all 0.3s;
}
.active_submenu {
 background-color: #ceb689 !important;
 color: #fff !important;
}

.menu li ul {
 display: none;
 width: 100%;
 position: relative;
 top: 0px;
 display:none;

}
.menu li:hover ul {
 display: none;
 top: 0px;
}

.menu li a.active {
 color: #fff;
 font-family: 'opensanssemibold';
}

.menu li ul li a {
 background:#333;
}

}

       Menu

Menu

Dropdown One

Dropdown

Dropdown

Dropdown

Dropdown

Dropdown Two

Dropdown

Dropdown

Dropdown

Dropdown

Menu

Menu

It is working on 768px screen size, but when I click on the drop-down link instead of hover on more than 768 screen size, the drop down link is slide toggle. I need this script work on certain width only.

Body:
Use $(window).width() to get the width of the screen and use it in your condition:

if ($(window).width() < 768) {
         // run your code here
}

See code snippet:

$(document).ready(function() {
  $(".resmenu").click(function() {
    $(".menu").slideToggle();
  });

  $(".submenu").click(function() {
    if ($(window).width() < 768) {
      $(this).toggleClass("active_submenu");
      $(this).parent().find(".dropdown").slideToggle();
    }
  });

});

.container {
  width: 980px;
  margin: 100px auto 0 auto;
  font-family: arial;
}

ul,
li {
  margin: 0;
  padding: 0;
}

.resmenu {
  display: none;
}

.menu li {
  display: inline-block;
  position: relative;
}

.menu li a {
  font-size: 14px;
  text-transform: uppercase;
  color: #3b2612;
  padding: 6px 17px;
  letter-spacing: 1px;
  display: block;
  text-decoration: none;
}

.menu li:hover a {
  background: #444;
  color: #fff !important;
}

.menu li ul {
  position: absolute;
  width: 250px;
  z-index: 5;
  left: 0px;
  top: 28px;
  display: none;
}

.menu li:hover ul {
  display: block;
}

.menu li ul li {
  display: block;
}

.menu li ul li a {
  padding: 6px 17px;
  transition: all 0.2s;
  text-transform: capitalize;
}

.menu li ul li a:hover {
  background: #000;
}

/*--- responsive ----*/

@media screen and (min-width:769px) {
  .menu {
    display: block!important;
  }
}

@media screen and (max-width:768px) {
  .resmenu {
    color: #fff !important;
    display: block;
    text-decoration: none !important;
    background: #6ca2bd;
    padding: 5px 10px;
  }
  .menu {
    display: none;
    background: #444444;
  }
  .menu li {
    position: relative;
    display: block;
  }
  .menu li a {
    color: #fff;
    font-size: 14px;
    padding: 6px 17px;
  }
  .menu li a:hover {
    background-color: #000;
    color: #000;
    transition: all 0.3s;
  }
  .active_submenu {
    background-color: #ceb689 !important;
    color: #fff !important;
  }
  .menu li ul {
    display: none;
    width: 100%;
    position: relative;
    top: 0px;
    display: none;
  }
  .menu li:hover ul {
    display: none;
    top: 0px;
  }
  .menu li a.active {
    color: #fff;
    font-family: 'opensanssemibold';
  }
  .menu li ul li a {
    background: #333;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="btm_header">
    <a href="#" class="resmenu">Menu</a>

    <ul class="menu">
      <li><a href="#">Menu</a></li>
      <li><a href="javascript:void(0);" class="submenu">Dropdown One  <span></span></a>
        <ul class="dropdown">
          <li><a href="#">Dropdown</a></li>
          <li><a href="#">Dropdown</a></li>
          <li><a href="#">Dropdown</a></li>
          <li><a href="#">Dropdown</a></li>
        </ul>
      </li>
      <li><a href="javascript:void(0);" class="submenu">Dropdown Two <span></span></a>
        <ul class="dropdown">
          <li><a href="#">Dropdown</a></li>
          <li><a href="#">Dropdown</a></li>
          <li><a href="#">Dropdown</a></li>
          <li><a href="#">Dropdown</a></li>
        </ul>
      </li>
      <li><a href="#">Menu</a></li>
      <li><a href="#">Menu</a></li>
    </ul>
  </div>
</div>


问:
Find (only) the first row satisfying a given condition in pandas DataFrame
I have a dataframe df with a very long column of random positive integers:

```<code>df = pd.DataFrame({'n': np.random.randint(1, 10, size = 10000)})
</code>```

I want to determine the index of the first even number in the column. One way to do this is:

```<code>df[df.n % 2 == 0].iloc[0]
</code>```

but this involves a lot of operations (generate the indices f.n % 2 == 0, evaluate df on those indices and finally take the first item) and is very slow. A loop like this is much quicker:

```<code>for j in range(len(df)):
    if df.n.iloc[j] % 2 == 0:
        break
</code>```

also because the first result will be probably in the first few lines.  Is there any pandas method for doing this with similar performance? Thank you.

NOTE: This condition (to be an even number) is just an example.  I'm looking for a solution that works for any kind of condition on the values, i.e., for a fast one-line alternative to:

```<code>df[ conditions on df.n ].iloc[0]
</code>```

答:
I decided for fun to play with a few possibilities. I take a dataframe:

```<code>MAX = 10**7
df = pd.DataFrame({'n': range(MAX)})
</code>```

(not random this time.) I want to find the first row for which n >= N for some value of N. I have timed the following four versions:

```<code>def getfirst_pandas(condition, df):
    return df[condition(df)].iloc[0]

def getfirst_iterrows_loop(condition, df):
    for index, row in df.iterrows():
        if condition(row):
            return index, row
    return None

def getfirst_for_loop(condition, df):
    for j in range(len(df)):
        if condition(df.iloc[j]):
            break
    return j

def getfirst_numpy_argmax(condition, df):
    array = df.as_matrix()
    imax  = np.argmax(condition(array))
    return df.index[imax]
</code>```

with N = powers of ten. Of course the numpy (optimized C) code is expected to be faster than for loops in python, but I wanted to see for which values of N python loops are still okay.

I timed the lines:

```<code>getfirst_pandas(lambda x: x.n >= N, df)
getfirst_iterrows_loop(lambda x: x.n >= N, df)
getfirst_for_loop(lambda x: x.n >= N, df)
getfirst_numpy_argmax(lambda x: x >= N, df.n)
</code>```

for N = 1, 10, 100, 1000, ....  This is the log-log graph of the performance:

PICTURE

The simple for loop is ok as long as the "first True position" is expected to be at the beginning, but then it becomes bad.  The np.argmax is the safest solution.

As you can see from the graph, the time for pandas and argmax remain (almost) constant, because  they always scan the whole array.  It would be perfect to have a np or pandas method which doesn't.

Body:
I have a dataframe df with a very long column of random positive integers:

df = pd.DataFrame({'n': np.random.randint(1, 10, size = 10000)})

I want to determine the index of the first even number in the column. One way to do this is:

df[df.n % 2 == 0].iloc[0]

but this involves a lot of operations (generate the indices f.n % 2 == 0, evaluate df on those indices and finally take the first item) and is very slow. A loop like this is much quicker:

for j in range(len(df)):
    if df.n.iloc[j] % 2 == 0:
        break

also because the first result will be probably in the first few lines.  Is there any pandas method for doing this with similar performance? Thank you.

NOTE: This condition (to be an even number) is just an example.  I'm looking for a solution that works for any kind of condition on the values, i.e., for a fast one-line alternative to:

df[ conditions on df.n ].iloc[0]

Body:
I decided for fun to play with a few possibilities. I take a dataframe:

MAX = 10**7
df = pd.DataFrame({'n': range(MAX)})

(not random this time.) I want to find the first row for which n >= N for some value of N. I have timed the following four versions:

def getfirst_pandas(condition, df):
    return df[condition(df)].iloc[0]

def getfirst_iterrows_loop(condition, df):
    for index, row in df.iterrows():
        if condition(row):
            return index, row
    return None

def getfirst_for_loop(condition, df):
    for j in range(len(df)):
        if condition(df.iloc[j]):
            break
    return j

def getfirst_numpy_argmax(condition, df):
    array = df.as_matrix()
    imax  = np.argmax(condition(array))
    return df.index[imax]

with N = powers of ten. Of course the numpy (optimized C) code is expected to be faster than for loops in python, but I wanted to see for which values of N python loops are still okay.

I timed the lines:

getfirst_pandas(lambda x: x.n >= N, df)
getfirst_iterrows_loop(lambda x: x.n >= N, df)
getfirst_for_loop(lambda x: x.n >= N, df)
getfirst_numpy_argmax(lambda x: x >= N, df.n)

for N = 1, 10, 100, 1000, ....  This is the log-log graph of the performance:

PICTURE

The simple for loop is ok as long as the "first True position" is expected to be at the beginning, but then it becomes bad.  The np.argmax is the safest solution.

As you can see from the graph, the time for pandas and argmax remain (almost) constant, because  they always scan the whole array.  It would be perfect to have a np or pandas method which doesn't.


问:
Returning undefined in output
I am new to javascript and I am struggling to understand the return statement:

function solution(number){
     var newarray = []
     for ( var i = 0 ; i < number - 1 ; i++ ) {
        if (i % 3 === 0) {
           newarray.push(number[i]);
        } else if (i % 5 === 0) {
           newarray.push(number[i]);
        } else {
           newarray
        }
      }
      return newarray
    }

   console.log(solution(10));```

This solution is returning an array with values in but they are all undefined. Why is this the case? What essential concept am I missing can anyone help me?

答:
```<code>function solution(number){
 var newarray = []
 for ( var i = 0 ; i < number - 1 ; i++ ) {
    if (i % 3 === 0) {
       newarray.push(i);
    } else if (i % 5 === 0) {
       newarray.push(i);
    } else {
       newarray
    }
  }
 return newarray;
}

console.log(solution(10));
</code>```

Title: Returning undefined in output

Body:
I am new to javascript and I am struggling to understand the return statement:

function solution(number){
     var newarray = []
     for ( var i = 0 ; i < number - 1 ; i++ ) {
        if (i % 3 === 0) {
           newarray.push(number[i]);
        } else if (i % 5 === 0) {
           newarray.push(number[i]);
        } else {
           newarray
        }
      }
      return newarray
    }

   console.log(solution(10));

This solution is returning an array with values in but they are all undefined. Why is this the case? What essential concept am I missing can anyone help me?


问:
Using a promise to wait for function called and finish doing what it suppose before continue
I am calling a function to load some file, this function is getting called from other places too..

for this section of code to run successfully searchconfig.js must load before

What I want to achieve is, for this call to finish loading searchconfig.js and just then continue with the other code and if error occurred, to log it:

```<code>loadRemoteFile("Search/" + Search.Configuration.PathToConfigurable + "/Configurable/searchconfig.js");
</code>```

Full code:

```<code>$(document).ready(function () {
    if (Search.Configuration && Search.Configuration.PathToConfigurable) {
        // the file that is necessary for the code to run successfully
        loadRemoteFile("Search/" + Search.Configuration.PathToConfigurable + "/Configurable/searchconfig.js");
    }

    setTimeout(function () {

        // anchor for injecting the  results
        $('body').prepend("<div id='search-results' class='container'></div>")

        for (var configItem in tempConfig) {
            Search.Configuration[configItem] = tempConfig[configItem];
        }

        var configsToCheckForSlash = ["FullPathToConfigurableFolder", "pathToSearch", "PathToConfigurable", "SearchServiceURL", "ThumbnailsURL", "CMSThumbnailsURL", "PreviewBaseURL"];

        for (var x = 0; x < configsToCheckForSlash.length; x++) {
            Search.Configuration[configsToCheckForSlash[x]] = addForwardSlashToSearchConfigSettings(Search.Configuration[configsToCheckForSlash[x]]);
            _log(Search.Configuration[configsToCheckForSlash[x]])
        }

        for (var x = 0; x < Search.Configuration.pagesToAvoid.length; x++) {
            var pagesToAvoid = Search.Configuration.pagesToAvoid[x].toLowerCase();
            if (location.href.toLowerCase().indexOf(pagesToAvoid) > -1) {
                _log("Search loader abandoned. Please check settings if this is not intended.");
                return;
            }
        }

        $("head").append(Search.Configuration.requiredFiles);

        //pick implementation points
        Search.Configuration.anchorToUseForMainSearch = $("#search-results");

        if (!Search.Configuration.anchorToUseForMainSearch.length) {
            _log("The search implementation could not find a suitable place to place the search, aborting.");
            return;
        }

        searchIsExpanded = false;
        writeSearchHTML();
    }, 400);
});
</code>```

loadRemoteFile function

```<code>function loadRemoteFile(filename, loadIntoHeader){
        filetype = filename.match(".css") ? "css" : "js";

        if (filetype=="js"){
            if(!loadIntoHeader){
                var script   = document.createElement("script");
                script.type  = "text/javascript";
                script.src   = filename;
                document.body.appendChild(script);
            }else{
                ...
            }
        }else if (filetype=="css"){
            ...
        }
}
</code>```

答:
What i ended up using is to wait for the file loading.

What I want to achieve is to finish loading searchconfig.js and just then continue with the other code:

```<code> function when_external_loaded(callback) {
        // means searchconfig.js is loaded,
        // we should restrict the number of times we check
        // if the parameter exist or restrict the max time for checking it
        if (typeof x.pagesToAvoid === 'undefined') {
            setTimeout(function () {
                when_external_loaded(callback);
            }, 10); // wait 10 ms
        } else { callback(); }
    }
</code>```

and then in:

```<code>(document).ready(function(){
    when_external_loaded(function () {
     // place all the code that you want to occur after the file has been loaded
    }
});
</code>```

What will happen is Only when x.pagesToAvoid !== 'undefined') means that searchconfig.js was loaded, we it will load the function calls the callback function.

Bear in mind that you should restrict the time of checking the file existing, cause if the file dont exist this will try forever (for me its OK, cause the existence of the file is not depend on nothing and he will be in that place).

I didn't use the promise solution, cause i misunderstood something. the promise only return true if happen and false if not.
So when the file was tried to load (but it didn't load yet to memory) the promise will be true.. and it wasn't enough for me.

Body:
I am calling a function to load some file, this function is getting called from other places too..

for this section of code to run successfully searchconfig.js must load before

What I want to achieve is, for this call to finish loading searchconfig.js and just then continue with the other code and if error occurred, to log it:

loadRemoteFile("Search/" + Search.Configuration.PathToConfigurable + "/Configurable/searchconfig.js");

Full code:

$(document).ready(function () {
    if (Search.Configuration && Search.Configuration.PathToConfigurable) {
        // the file that is necessary for the code to run successfully
        loadRemoteFile("Search/" + Search.Configuration.PathToConfigurable + "/Configurable/searchconfig.js");
    }

    setTimeout(function () {

        // anchor for injecting the  results
        $('body').prepend("

")

        for (var configItem in tempConfig) {
            Search.Configuration[configItem] = tempConfig[configItem];
        }

        var configsToCheckForSlash = ["FullPathToConfigurableFolder", "pathToSearch", "PathToConfigurable", "SearchServiceURL", "ThumbnailsURL", "CMSThumbnailsURL", "PreviewBaseURL"];

        for (var x = 0; x < configsToCheckForSlash.length; x++) {
            Search.Configuration[configsToCheckForSlash[x]] = addForwardSlashToSearchConfigSettings(Search.Configuration[configsToCheckForSlash[x]]);
            _log(Search.Configuration[configsToCheckForSlash[x]])
        }

        for (var x = 0; x < Search.Configuration.pagesToAvoid.length; x++) {
            var pagesToAvoid = Search.Configuration.pagesToAvoid[x].toLowerCase();
            if (location.href.toLowerCase().indexOf(pagesToAvoid) > -1) {
                _log("Search loader abandoned. Please check settings if this is not intended.");
                return;
            }
        }

        $("head").append(Search.Configuration.requiredFiles);

        //pick implementation points
        Search.Configuration.anchorToUseForMainSearch = $("#search-results");

        if (!Search.Configuration.anchorToUseForMainSearch.length) {
            _log("The search implementation could not find a suitable place to place the search, aborting.");
            return;
        }

        searchIsExpanded = false;
        writeSearchHTML();
    }, 400);
});

loadRemoteFile function

function loadRemoteFile(filename, loadIntoHeader){
        filetype = filename.match(".css") ? "css" : "js";

        if (filetype=="js"){
            if(!loadIntoHeader){
                var script   = document.createElement("script");
                script.type  = "text/javascript";
                script.src   = filename;
                document.body.appendChild(script);
            }else{
                ...
            }
        }else if (filetype=="css"){
            ...
        }
}

Body:
What i ended up using is to wait for the file loading.

What I want to achieve is to finish loading searchconfig.js and just then continue with the other code:

 function when_external_loaded(callback) {
        // means searchconfig.js is loaded,
        // we should restrict the number of times we check
        // if the parameter exist or restrict the max time for checking it
        if (typeof x.pagesToAvoid === 'undefined') {
            setTimeout(function () {
                when_external_loaded(callback);
            }, 10); // wait 10 ms
        } else { callback(); }
    }

and then in:

(document).ready(function(){
    when_external_loaded(function () {
     // place all the code that you want to occur after the file has been loaded
    }
});

What will happen is Only when x.pagesToAvoid !== 'undefined') means that searchconfig.js was loaded, we it will load the function calls the callback function.

Bear in mind that you should restrict the time of checking the file existing, cause if the file dont exist this will try forever (for me its OK, cause the existence of the file is not depend on nothing and he will be in that place).

I didn't use the promise solution, cause i misunderstood something. the promise only return true if happen and false if not.
So when the file was tried to load (but it didn't load yet to memory) the promise will be true.. and it wasn't enough for me.


问:
How to cross compile libxml2 with arm-linux-gnueabihf-gcc compiler. How to cross compile using third party libraries?
when I tried to cross compile I am getting an error

/usr/include/libxml2/libxml/encoding.h:31:26: fatal error: unicode/ucnv.h: No such file or directory
compilation terminated.

答: In recent releases of libxml2, the configure script tries to detect ICU using pkg-config. Depending on your setup, this could result in false positives when cross-compiling (see Autotools Mythbuster for details). I'd suggest to disable ICU support by passing --without-icu to configure. ICU is a huge library and libxml2 only uses it to convert between character sets. It also supports libiconv which is much smaller.


问:
javascript/angular 4 property is undefined after interval tries to get value
I am trying to build an timer, but it is not working.
What I do is I have a button which starts the timer. It sets the begin time and after that start an interval to count on screen. But the function which is called by the interval fails because the beginning time is undefined. I debuged to see if the beginning time is being set, and it is. But when it is called through the interval it is undefined.

Here is my code
Some properties

```<code> timeBegan = new Date();
  started = null;
</code>```

the start function

```<code>start() {
this.timeBegan = new Date();
document.getElementById('ticker').innerHTML = '00:00:00.000';

this.started = setInterval(this.clockRunning, 10);
  }
</code>```

the clockrunning function

```<code>public clockRunning() {
const currentTime = new Date();
console.log(this.timeBegan);
console.log(currentTime.getTime());
const timeElapsed = new Date(currentTime.getTime() - this.timeBegan.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

console.log(currentTime.getSeconds());
console.log(this.timeBegan);
document.getElementById('ticker').innerHTML =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 999 ? ms : ms > 9 ? '0' + ms : '000' + ms);

 }
</code>```

What am I doing wrong?

答:
It is not working because you are referencing:

```<code>this.timeBegan
</code>```

However, "this" is not refering to the "this" you want it to refer to. "this" is the function defined in setInterval. This is because ES5 functions have their own "this".

You could try using an ES6 function which will prob use the "this" you want.

Alternatively, force "this" within your function to refer to the "this" you want by doing:

```<code>this.clockRunning = this.clockRunning.bind(this)
</code>```

This means that the "this" within clockRunning will ALWAYS be the "this" passed to bind(). Make sure you pass the right "this" to bind :) viz the "this" that has the timeBegan property.

Body:
I am trying to build an timer, but it is not working.
What I do is I have a button which starts the timer. It sets the begin time and after that start an interval to count on screen. But the function which is called by the interval fails because the beginning time is undefined. I debuged to see if the beginning time is being set, and it is. But when it is called through the interval it is undefined.

Here is my code
Some properties

 timeBegan = new Date();
  started = null;

the start function

start() {
this.timeBegan = new Date();
document.getElementById('ticker').innerHTML = '00:00:00.000';

this.started = setInterval(this.clockRunning, 10);
  }

the clockrunning function

public clockRunning() {
const currentTime = new Date();
console.log(this.timeBegan);
console.log(currentTime.getTime());
const timeElapsed = new Date(currentTime.getTime() - this.timeBegan.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

console.log(currentTime.getSeconds());
console.log(this.timeBegan);
document.getElementById('ticker').innerHTML =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 999 ? ms : ms > 9 ? '0' + ms : '000' + ms);

 }

What am I doing wrong?

Body:
It is not working because you are referencing:

this.timeBegan

However, "this" is not refering to the "this" you want it to refer to. "this" is the function defined in setInterval. This is because ES5 functions have their own "this".

You could try using an ES6 function which will prob use the "this" you want.

Alternatively, force "this" within your function to refer to the "this" you want by doing:

this.clockRunning = this.clockRunning.bind(this)

This means that the "this" within clockRunning will ALWAYS be the "this" passed to bind(). Make sure you pass the right "this" to bind :) viz the "this" that has the timeBegan property.


问:
MySQL Connector not Working: NO module named Connector
OS: Ubuntu 17.10
Python: 2.7

SUBLIME TEXT 3:

I am trying to import mysql.connector,

ImportError: No module named connector

Although, when i try import mysql.connector in python shell, it works.

Earlier it was working fine, I just upgraded Ubuntu and somehow mysql connector is not working.

I have tried reinstalling mysql connector using pip and git both.

Still no luck.

Please help!

答:
I do not see currently connector version for Ubuntu 17.10.

Have you tried alternative connections?

Hope it will help:
    http://mysql-python.sourceforge.net/MySQLdb.html


问:
Importing a css module into Webpack
I'm trying to set up React-Table, which relies on a style sheet that needs to be imported into Webpack with the following statement:

```<code>import ReactTable from 'react-table'
</code>```

Unfortunately, I'm not very familiar with configuring Webpack and am not sure where this line should go. Here's my webpack.config.js file:

```<code>const loaders = require('loaders');

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js',
    sourceMapFilename: "bundle.js.map"
  },
  module: {
      loaders: [
          loaders.css,
          loaders.url,
          {
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
            presets: ['react', 'es2015', 'stage-1']
          }
    }]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};
</code>```

Can anyone point me in the right direction?

答:
Try updating your webpack file with this and install all loaders like css-loader, url-loader, file-loader, style-loader, sass-loader etc.

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js',
    sourceMapFilename: "bundle.js.map"
  },
  module: {
  loaders: [
     {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
           presets: ['es2015', 'react']
        }
     },
     { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
     {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader'},
     {test: /\.css$/, loader: "style-loader!css-loader" },
     {test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader']},

  ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};
</code>```

Also if you want to make your stylesheet work with webpack and see those changes in app, you can put that stylesheet in your styles folder and import it in your entry file i.e src/index.js. Something like this :-

```<code> import './styles/style.css' ;
</code>```

Title: Importing a css module into Webpack

Body:
I'm trying to set up React-Table, which relies on a style sheet that needs to be imported into Webpack with the following statement:

import ReactTable from 'react-table'

Unfortunately, I'm not very familiar with configuring Webpack and am not sure where this line should go. Here's my webpack.config.js file:

const loaders = require('loaders');

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js',
    sourceMapFilename: "bundle.js.map"
  },
  module: {
      loaders: [
          loaders.css,
          loaders.url,
          {
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
            presets: ['react', 'es2015', 'stage-1']
          }
    }]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

Can anyone point me in the right direction?

Body:
Try updating your webpack file with this and install all loaders like css-loader, url-loader, file-loader, style-loader, sass-loader etc.

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js',
    sourceMapFilename: "bundle.js.map"
  },
  module: {
  loaders: [
     {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
           presets: ['es2015', 'react']
        }
     },
     { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
     {test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader'},
     {test: /\.css$/, loader: "style-loader!css-loader" },
     {test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader']},

  ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

Also if you want to make your stylesheet work with webpack and see those changes in app, you can put that stylesheet in your styles folder and import it in your entry file i.e src/index.js. Something like this :-

 import './styles/style.css' ;


问:
How to extract the child of a tag in Beautifulsoup?
I have the following code and I want to extract content inside

```<code><p><strong>1. Start big</strong><br><br>
Make a slam dunk right away. Boom! Just do it! Start strong! If you’re making a list article about poodle outerwear, don’t save the best for last: put that sporty little pool-vest idea right up there at the top. </p>

<p><strong>2. Hook them and hook them good</strong><br><br>
A recent study of lists (included in another article about the top ten research studies, natch), assembled by some guy you’ve never heard of from an obscure European university in his spare time, found that Web readers usually don’t make it past the first few items on a list. Sad, isn’t it? I bet you’re already thinking about stopping. Yes, it sucks to know people have shorter attention spans than an overly-caffeinated Himalayan fruit-fly. Make the first few count, okay?</p>

<p><strong>3. Stay on message</strong><br><br>
Let’s say you’re writing a list article about the top movies starring Naomi Watts that don’t suck. It’s a short list, if you remember anything about King Kong or her early indie films. I see this kind of thing pop up on <a href="http://www.foxnews.com" rel="nofollow">Fox News</a> and <a href="http://www.metacritic.com" rel="nofollow">Metacritic</a> once in awhile, and I usually can’t stop myself from clicking on them. You get into sort of a click-trance. In fact, hang on a second. I think there might be one on the top opening acts when The Bieb performs in space. Oh yes there is! Okay, back. So, in your article list of the top movies that use a Meatloaf song in the soundtrack, adding that one from Black Sabbath is just not proper usage. We want Meatloaf and Meatloaf only, people! Besides, Black Sabbath is for sissies.</p>
</code>```

my code in Python to extract p tags is

```<code>soup = BeautifulSoup(page, "lxml")

for content in soup.find_all('p'):
    print(content)
</code>```

what should I add to it to extract strong?

I already tried soup.find_all('p > strong')

答:
```<code>from bs4 import BeautifulSoup

page = """
<p><strong>1. Start big</strong><br><br>
Make a slam dunk right away. Boom! Just do it! Start strong! If you’re making a list article about poodle outerwear, don’t save the best for last: put that sporty little pool-vest idea right up there at the top. </p>

<p><strong>2. Hook them and hook them good</strong><br><br>
A recent study of lists (included in another article about the top ten research studies, natch), assembled by some guy you’ve never heard of from an obscure European university in his spare time, found that Web readers usually don’t make it past the first few items on a list. Sad, isn’t it? I bet you’re already thinking about stopping. Yes, it sucks to know people have shorter attention spans than an overly-caffeinated Himalayan fruit-fly. Make the first few count, okay?</p>

<p><strong>3. Stay on message</strong><br><br>
Let’s say you’re writing a list article about the top movies starring Naomi Watts that don’t suck. It’s a short list, if you remember anything about King Kong or her early indie films. I see this kind of thing pop up on <a href="http://www.foxnews.com" rel="nofollow">Fox News</a> and <a href="http://www.metacritic.com" rel="nofollow">Metacritic</a> once in awhile, and I usually can’t stop myself from clicking on them. You get into sort of a click-trance. In fact, hang on a second. I think there might be one on the top opening acts when The Bieb performs in space. Oh yes there is! Okay, back. So, in your article list of the top movies that use a Meatloaf song in the soundtrack, adding that one from Black Sabbath is just not proper usage. We want Meatloaf and Meatloaf only, people! Besides, Black Sabbath is for sissies.</p>
"""

soup = BeautifulSoup(page, 'lxml')

for content in soup.select('p > strong'):
    print(content)
</code>```

Output:

```<code><strong>1. Start big</strong>
<strong>2. Hook them and hook them good</strong>
<strong>3. Stay on message</strong>
</code>```

You need to use the .select method for CSS selectors, not the .find

You can find the bs4 docs on .select here, and some CSS selector docs from w3schools here.

Body:
I have the following code and I want to extract content inside

1. Start big

Make a slam dunk right away. Boom! Just do it! Start strong! If you’re making a list article about poodle outerwear, don’t save the best for last: put that sporty little pool-vest idea right up there at the top.

2. Hook them and hook them good

A recent study of lists (included in another article about the top ten research studies, natch), assembled by some guy you’ve never heard of from an obscure European university in his spare time, found that Web readers usually don’t make it past the first few items on a list. Sad, isn’t it? I bet you’re already thinking about stopping. Yes, it sucks to know people have shorter attention spans than an overly-caffeinated Himalayan fruit-fly. Make the first few count, okay?

3. Stay on message

Let’s say you’re writing a list article about the top movies starring Naomi Watts that don’t suck. It’s a short list, if you remember anything about King Kong or her early indie films. I see this kind of thing pop up on Fox News and Metacritic once in awhile, and I usually can’t stop myself from clicking on them. You get into sort of a click-trance. In fact, hang on a second. I think there might be one on the top opening acts when The Bieb performs in space. Oh yes there is! Okay, back. So, in your article list of the top movies that use a Meatloaf song in the soundtrack, adding that one from Black Sabbath is just not proper usage. We want Meatloaf and Meatloaf only, people! Besides, Black Sabbath is for sissies.

my code in Python to extract p tags is

soup = BeautifulSoup(page, "lxml")

for content in soup.find_all('p'):
    print(content)

what should I add to it to extract strong?

I already tried soup.find_all('p > strong')

Body:
from bs4 import BeautifulSoup

page = """
<p><strong>1. Start big</strong><br><br>
Make a slam dunk right away. Boom! Just do it! Start strong! If you’re making a list article about poodle outerwear, don’t save the best for last: put that sporty little pool-vest idea right up there at the top. </p>

<p><strong>2. Hook them and hook them good</strong><br><br>
A recent study of lists (included in another article about the top ten research studies, natch), assembled by some guy you’ve never heard of from an obscure European university in his spare time, found that Web readers usually don’t make it past the first few items on a list. Sad, isn’t it? I bet you’re already thinking about stopping. Yes, it sucks to know people have shorter attention spans than an overly-caffeinated Himalayan fruit-fly. Make the first few count, okay?</p>

<p><strong>3. Stay on message</strong><br><br>
Let’s say you’re writing a list article about the top movies starring Naomi Watts that don’t suck. It’s a short list, if you remember anything about King Kong or her early indie films. I see this kind of thing pop up on <a href="http://www.foxnews.com" rel="nofollow">Fox News</a> and <a href="http://www.metacritic.com" rel="nofollow">Metacritic</a> once in awhile, and I usually can’t stop myself from clicking on them. You get into sort of a click-trance. In fact, hang on a second. I think there might be one on the top opening acts when The Bieb performs in space. Oh yes there is! Okay, back. So, in your article list of the top movies that use a Meatloaf song in the soundtrack, adding that one from Black Sabbath is just not proper usage. We want Meatloaf and Meatloaf only, people! Besides, Black Sabbath is for sissies.</p>
"""

soup = BeautifulSoup(page, 'lxml')

for content in soup.select('p > strong'):
    print(content)

Output:

<strong>1. Start big</strong>
<strong>2. Hook them and hook them good</strong>
<strong>3. Stay on message</strong>

You need to use the .select method for CSS selectors, not the .find

You can find the bs4 docs on .select here, and some CSS selector docs from w3schools here.


问:
get index of dropdown with the same class name
I have a dropdown which is as follows:

```<code><select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>
</code>```

I have numerous dropdowns like above with the same class. What I am trying to do is get the index and the value of the select one. For that my jQuery code is as follows

```<code>$('.sn-item-reveived-ddl').change(function () {
   var value = $(this).val(); //this brings back the correct value of the dropdown
   var index = $('option:selected').index(); //if i use this it keeps returning index 0

    console.log(index);
});
</code>```

Problem I am having is that I can get the correct value by using this keyword, however if I try to get the index it picks up the index of the first dropdown with the class named sn-item-received-ddl. Can someone tell me where I am going wrong please.

答:
Add this to $('option:selected') so it looks like $('option:selected', this) Then it should work.

Then it will get the index of the selected option in the dropdown you just changed.

$('.sn-item-reveived-ddl').change(function() {
  var value = $(this).val(); //this brings back the correct value of the dropdown
  var index = $('option:selected', this).index(); //if i use this it keeps returning index 0

  console.log(index);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>

<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>

<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select></code>```

Body:
I have a dropdown which is as follows:

<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>

I have numerous dropdowns like above with the same class. What I am trying to do is get the index and the value of the select one. For that my jQuery code is as follows

$('.sn-item-reveived-ddl').change(function () {
   var value = $(this).val(); //this brings back the correct value of the dropdown
   var index = $('option:selected').index(); //if i use this it keeps returning index 0

    console.log(index);
});

Problem I am having is that I can get the correct value by using this keyword, however if I try to get the index it picks up the index of the first dropdown with the class named sn-item-received-ddl. Can someone tell me where I am going wrong please.

Body:
Add this to $('option:selected') so it looks like $('option:selected', this) Then it should work.

Then it will get the index of the selected option in the dropdown you just changed.

$('.sn-item-reveived-ddl').change(function() {
  var value = $(this).val(); //this brings back the correct value of the dropdown
  var index = $('option:selected', this).index(); //if i use this it keeps returning index 0

  console.log(index);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>

<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>

<select class="form-control sn-item-reveived-ddl">
<option value>Have you received this item?></option>
<option value="True">Yes</option>
<option value="False">No</option>
</select>


问:
No return statement in sub-functions? [Javascript]
I'm in Chapter 3 - Functions of Eloquent Javascript.

Everything about the following code makes sense to me -- except one thing.

Why don't the sub-functions (for lack of a better term) have return statements?

```<code>var landscape = function() {
var result = "";
var flat = function(size) {
    for (var count = 0; count < size; count++)
      result += "_";
  };
  var mountain = function(size) {
    result += "/";
    for (var count = 0; count < size; count++)
      result += "'";
    result += "\\";
  };

  flat(3);
  mountain(4);
  flat(6);
  mountain(1);
  flat(1);
  return result;
};

console.log(landscape());
// → ___/''''\______/'\_
</code>```

Maybe I'm missing something fundamental about the purpose of the return statement, even after reading different definitions from different sources.

I've tried adding return statements to the sub-functions. I've found that it'll either terminate the sub-function pre-maturely, or produce the same result as if it was never there.

Thanks for reading.

答:
They are accessing the outer scoped variable result and change something there. So they change the actual result variable's value and doesn't need to return anything. If it reaches to the end of the function, function ends. You can do the same by creating local function scoped variables and make strings from them, return them and concatenate in the main landscape function.

See the alternative of your code with the return statements

var landscape = function() {

  var result = "";

  var flat = function(size) {
    var localFlat = ''; // Function scoped variable
    for (var count = 0; count < size; count++) {
      localFlat += "_";
    }
    return localFlat; // Return function scoped variable
  };

  var mountain = function(size) {
    var localMountain = "/"; // Function scoped variable
    for (var count = 0; count < size; count++) {
      localMountain += "'";
    }
    localMountain += "\\";
    return localMountain; // Return function scoped variable
  };

  result = flat(3) + mountain(4) + flat(6) + mountain(1) + flat(1); // Concatenate the results of each function

  return result;
};

console.log(landscape());```

Body:
I'm in Chapter 3 - Functions of Eloquent Javascript.

Everything about the following code makes sense to me -- except one thing.

Why don't the sub-functions (for lack of a better term) have return statements?

var landscape = function() {
var result = "";
var flat = function(size) {
    for (var count = 0; count < size; count++)
      result += "_";
  };
  var mountain = function(size) {
    result += "/";
    for (var count = 0; count < size; count++)
      result += "'";
    result += "\\";
  };

  flat(3);
  mountain(4);
  flat(6);
  mountain(1);
  flat(1);
  return result;
};

console.log(landscape());
// → ___/''''\______/'\_

Maybe I'm missing something fundamental about the purpose of the return statement, even after reading different definitions from different sources.

I've tried adding return statements to the sub-functions. I've found that it'll either terminate the sub-function pre-maturely, or produce the same result as if it was never there.

Thanks for reading.


问:
How can I obtain the case-sensitive path on Windows?
I need to know which is the real path of a given path.

For example:

The real path is: d:\src\File.txt

And the user give me: D:\src\file.txt

I need as a result: d:\src\File.txt

答:
As an old-timer, I always used FindFirstFile for this purpose. The .Net translation is:

```<code>Directory.GetFiles(Path.GetDirectoryName(userSuppliedName), Path.GetFileName(userSuppliedName)).FirstOrDefault();
</code>```

This only gets you the correct casing for the filename portion of the path, not then entire path.

JeffreyLWhitledge's comment provides a link to a recursive version that can work (though not always) to resolve the full path.

ContentLicense: CC BY-SA 2.5

Body:
As an old-timer, I always used FindFirstFile for this purpose. The .Net translation is:

Directory.GetFiles(Path.GetDirectoryName(userSuppliedName), Path.GetFileName(userSuppliedName)).FirstOrDefault();

This only gets you the correct casing for the filename portion of the path, not then entire path.

JeffreyLWhitledge's comment provides a link to a recursive version that can work (though not always) to resolve the full path.


问:
SpannableString is not working in a Dialog
I want to show the spanString in Bold style and rest of the string in normal style in TextView. But the whole TextView showed in normal style only.   Please help me.

```<code>if ((mStoreListValue.get(pos).getStoreStatus().equals("CLOSED"))){

   final Dialog dialog = new Dialog(v.getRootView().getContext(), android.R.style.Theme_Translucent_NoTitleBar);
   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   dialog.getWindow().setContentView(R.layout.resclosed_dialog);
   ImageView btn_close =  dialog.findViewById(R.id.close_btn);
   TextView txt_close =  dialog.findViewById(R.id.tv_closed);

   SpannableString spanString = new SpannableString(sname);
   spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

   txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));

   btn_close.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
              dialog.dismiss();
         }
    });
  dialog.show();
</code>```

答:
Using String templating, you can have a string resource:
 indicates  bold,
%1$d indicates I am expecting a digit/number
so I get (5 min away) in the textview

```<code>//xml
<string name="confirm_eta_text"> <b>%1$d min </b> away</string>

// Java
mEta.setText(
Compat.fromHtml(String.format(getResources().getString(R.string.confirm_eta_text), 5)));
</code>```

Android String Formatting

Body:
I want to show the spanString in Bold style and rest of the string in normal style in TextView. But the whole TextView showed in normal style only.   Please help me.

if ((mStoreListValue.get(pos).getStoreStatus().equals("CLOSED"))){

   final Dialog dialog = new Dialog(v.getRootView().getContext(), android.R.style.Theme_Translucent_NoTitleBar);
   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   dialog.getWindow().setContentView(R.layout.resclosed_dialog);
   ImageView btn_close =  dialog.findViewById(R.id.close_btn);
   TextView txt_close =  dialog.findViewById(R.id.tv_closed);

   SpannableString spanString = new SpannableString(sname);
   spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

   txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));

   btn_close.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
              dialog.dismiss();
         }
    });
  dialog.show();

Body:
Using String templating, you can have a string resource:
&lt;b> indicates  bold,
%1$d indicates I am expecting a digit/number
so I get (5 min away) in the textview

//xml
<string name="confirm_eta_text"> &lt;b>%1$d min &lt;/b> away</string>

// Java
mEta.setText(
Compat.fromHtml(String.format(getResources().getString(R.string.confirm_eta_text), 5)));

Android String Formatting


问:
PostgreSQL docker image build errors
I am creating a docker image for postgresql installation from sources. Here is my Dockerfile which I created according to the postgresql documentation:

```<code>FROM ubuntu

RUN apt-get update && apt-get install gcc zlib1g-dev libreadline6-dev apt-utils make -y

RUN mkdir -p /tmp/downloads

ADD https://ftp.postgresql.org/pub/source/v9.6.6/postgresql-9.6.6.tar.gz /tmp/downloads

RUN cd /tmp/downloads && tar -zxf postgresql-9.6.6.tar.gz

RUN cd /tmp/downloads/postgresql-9.6.6 && make configure
RUN cd /tmp/downloads/postgresql-9.6.6 && ./configure
RUN cd /tmp/downloads/postgresql-9.6.6 && make
RUN cd /tmp/downloads/postgresql-9.6.6 && su
RUN cd /tmp/downloads/postgresql-9.6.6 && make install
RUN cd /tmp/downloads/postgresql-9.6.6 && adduser postgres
RUN cd /tmp/downloads/postgresql-9.6.6 && mkdir /usr/local/pgsql/data
RUN cd /tmp/downloads/postgresql-9.6.6 && chown postgres /usr/local/pgsql/data
RUN cd /tmp/downloads/postgresql-9.6.6 && su postgres
RUN cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
RUN cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/createdb test
RUN cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/psql test
</code>```

So when I run docker build -t roksolanad/psql:latest . I get errors:

```<code>initdb: cannot be run as root
Please log in (using, e.g., "su") as the (unprivileged) user that will
own the server process.
The command '/bin/sh -c cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data' returned a non-zero code: 1
</code>```

So how can I fix my Dockerfile? I would be very grateful for some help!

答:
As said by @Harald Nordgren, you need sum up all the RUN commands in one command, if possible.

Along with that there are couple of things which are causing the failures

1) adding "postgres" user:

"adduser" expects the additional parameters to be configured when you add a user, as you have mentioned in the comments like asking for password and so. So you need to modify the command to disable the arguments as well as the password like below:

```<code>adduser postgres --gecos '' --disabled-login
</code>```

2) executing postgress using root user

When you execute the command "su postgres", it executes with root user. But whereas we have changed the permissions in the above command "chown postgres /usr/local/pgsql/data"

For this you need a execute the command as "postgres" user which can be enabled by adding USER in dockerfile.

Finally your Dockerfile looks something like this:

```<code>FROM ubuntu

RUN apt-get update && apt-get install gcc zlib1g-dev libreadline6-dev apt-utils make -y

RUN mkdir -p /tmp/downloads

ADD https://ftp.postgresql.org/pub/source/v9.6.6/postgresql-9.6.6.tar.gz /tmp/downloads

RUN cd /tmp/downloads && tar -zxf postgresql-9.6.6.tar.gz

RUN cd /tmp/downloads/postgresql-9.6.6 &&\
    make configure &&\
    ./configure &&\
    make &&\
    su &&\
    make install &&\
    adduser postgres --gecos '' --disabled-login &&\
    mkdir /usr/local/pgsql/data &&\
    chown postgres /usr/local/pgsql/data

USER postgres

#use below command only if it is necessary, it is similar to "cd" linux command
WORKDIR /tmp/downloads/postgresql-9.6.6
RUN /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
</code>```

With this I am able to create a Docker image and tested as well. Adding more information which may be useful.

```<code># docker run -it postgres:2.0 /bin/bash
postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ ps -eaf
UID        PID  PPID  C STIME TTY          TIME CMD
postgres     1     0  0 10:58 ?        00:00:00 /bin/bash
postgres     9     1  0 10:59 ?        00:00:00 ps -eaf

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l logfile start
server starting

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ ps -eaf
UID        PID  PPID  C STIME TTY          TIME CMD
postgres     1     0  0 10:58 ?        00:00:00 /bin/bash
postgres    13     1  0 10:59 ?        00:00:00 /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
postgres    15    13  0 10:59 ?        00:00:00 postgres: checkpointer process
postgres    16    13  0 10:59 ?        00:00:00 postgres: writer process
postgres    17    13  0 10:59 ?        00:00:00 postgres: wal writer process
postgres    18    13  0 10:59 ?        00:00:00 postgres: autovacuum launcher process
postgres    19    13  0 10:59 ?        00:00:00 postgres: stats collector process
postgres    20     1  0 10:59 ?        00:00:00 ps -eaf

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ /usr/local/pgsql/bin/createdb test

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ /usr/local/pgsql/bin/psql test
psql (9.6.6)
Type "help" for help.

test=#
test=#
</code>```

There are other ways to build this docker image but this way I am able to.

Title: PostgreSQL docker image build errors

Body:
I am creating a docker image for postgresql installation from sources. Here is my Dockerfile which I created according to the postgresql documentation:

FROM ubuntu

RUN apt-get update && apt-get install gcc zlib1g-dev libreadline6-dev apt-utils make -y

RUN mkdir -p /tmp/downloads

ADD https://ftp.postgresql.org/pub/source/v9.6.6/postgresql-9.6.6.tar.gz /tmp/downloads

RUN cd /tmp/downloads && tar -zxf postgresql-9.6.6.tar.gz

RUN cd /tmp/downloads/postgresql-9.6.6 && make configure
RUN cd /tmp/downloads/postgresql-9.6.6 && ./configure
RUN cd /tmp/downloads/postgresql-9.6.6 && make
RUN cd /tmp/downloads/postgresql-9.6.6 && su
RUN cd /tmp/downloads/postgresql-9.6.6 && make install
RUN cd /tmp/downloads/postgresql-9.6.6 && adduser postgres
RUN cd /tmp/downloads/postgresql-9.6.6 && mkdir /usr/local/pgsql/data
RUN cd /tmp/downloads/postgresql-9.6.6 && chown postgres /usr/local/pgsql/data
RUN cd /tmp/downloads/postgresql-9.6.6 && su postgres
RUN cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
RUN cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/createdb test
RUN cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/psql test

So when I run docker build -t roksolanad/psql:latest . I get errors:

initdb: cannot be run as root
Please log in (using, e.g., "su") as the (unprivileged) user that will
own the server process.
The command '/bin/sh -c cd /tmp/downloads/postgresql-9.6.6 && /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data' returned a non-zero code: 1

So how can I fix my Dockerfile? I would be very grateful for some help!

Body:
As said by @Harald Nordgren, you need sum up all the RUN commands in one command, if possible.

Along with that there are couple of things which are causing the failures

1) adding "postgres" user:

"adduser" expects the additional parameters to be configured when you add a user, as you have mentioned in the comments like asking for password and so. So you need to modify the command to disable the arguments as well as the password like below:

adduser postgres --gecos '' --disabled-login

2) executing postgress using root user

When you execute the command "su postgres", it executes with root user. But whereas we have changed the permissions in the above command "chown postgres /usr/local/pgsql/data"

For this you need a execute the command as "postgres" user which can be enabled by adding USER in dockerfile.

Finally your Dockerfile looks something like this:

FROM ubuntu

RUN apt-get update && apt-get install gcc zlib1g-dev libreadline6-dev apt-utils make -y

RUN mkdir -p /tmp/downloads

ADD https://ftp.postgresql.org/pub/source/v9.6.6/postgresql-9.6.6.tar.gz /tmp/downloads

RUN cd /tmp/downloads && tar -zxf postgresql-9.6.6.tar.gz

RUN cd /tmp/downloads/postgresql-9.6.6 &&\
    make configure &&\
    ./configure &&\
    make &&\
    su &&\
    make install &&\
    adduser postgres --gecos '' --disabled-login &&\
    mkdir /usr/local/pgsql/data &&\
    chown postgres /usr/local/pgsql/data

USER postgres

#use below command only if it is necessary, it is similar to "cd" linux command
WORKDIR /tmp/downloads/postgresql-9.6.6
RUN /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data

With this I am able to create a Docker image and tested as well. Adding more information which may be useful.

# docker run -it postgres:2.0 /bin/bash
postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ ps -eaf
UID        PID  PPID  C STIME TTY          TIME CMD
postgres     1     0  0 10:58 ?        00:00:00 /bin/bash
postgres     9     1  0 10:59 ?        00:00:00 ps -eaf

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l logfile start
server starting

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ ps -eaf
UID        PID  PPID  C STIME TTY          TIME CMD
postgres     1     0  0 10:58 ?        00:00:00 /bin/bash
postgres    13     1  0 10:59 ?        00:00:00 /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
postgres    15    13  0 10:59 ?        00:00:00 postgres: checkpointer process
postgres    16    13  0 10:59 ?        00:00:00 postgres: writer process
postgres    17    13  0 10:59 ?        00:00:00 postgres: wal writer process
postgres    18    13  0 10:59 ?        00:00:00 postgres: autovacuum launcher process
postgres    19    13  0 10:59 ?        00:00:00 postgres: stats collector process
postgres    20     1  0 10:59 ?        00:00:00 ps -eaf

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ /usr/local/pgsql/bin/createdb test

postgres@8354d83023f9:/tmp/downloads/postgresql-9.6.6$ /usr/local/pgsql/bin/psql test
psql (9.6.6)
Type "help" for help.

test=#
test=#

There are other ways to build this docker image but this way I am able to.


问:
Creating a skeleton project directory
I am a rookie in Python who has been working on Learn Python the Hard Way. This whole process goes well as I have a smattering knowledge on Python until I march into ex46 where I get stuck in the 'Creating the skeleton Project Directory' section. I have no idea where I should run those commands guided on this book. Following are the excerpt of this part:

First, create the structure of your skeleton directory with these commands:

```<code>$ mkdir projects
$ cd projects/
$ mkdir skeleton
$ cd skeleton
$ mkdir  bin
$ mkdir NAME
$ mkdir tests
$ mkdir docs
</code>```

I have tried to run these commands in Windows Powershell, only to be warned that these commands can’t be recognized. I also fumbled to execute them in Pycharm, but all in vain. Could someone point out how I could get it done?

In addition, I am somewhat curious about this method because there seems to be handy way to approach this on Pycharm. Could I achieve the same goal on that?

I am using Python 2.7 and all previous exercises operate well until ex46.

答:
You get that error because you're typing a superfluous $ at the beginning of each command. That $ is the (Linux) command prompt. On your Windows machine, it's something like C:\WINDOWS\system32>. Don't type that.

Just type

```<code>mkdir projects
</code>```

and press Enter. That creates a folder (directory) named "projects". Then type

```<code>cd projects
</code>```

and press Enter. That changes the current directory to that new folder you just created. And so on.

Content migrated from comments since this is what actually solved the issue.

Title: Creating a skeleton project directory

Body:
I am a rookie in Python who has been working on Learn Python the Hard Way. This whole process goes well as I have a smattering knowledge on Python until I march into ex46 where I get stuck in the 'Creating the skeleton Project Directory' section. I have no idea where I should run those commands guided on this book. Following are the excerpt of this part:

First, create the structure of your skeleton directory with these commands:

$ mkdir projects
$ cd projects/
$ mkdir skeleton
$ cd skeleton
$ mkdir  bin
$ mkdir NAME
$ mkdir tests
$ mkdir docs

I have tried to run these commands in Windows Powershell, only to be warned that these commands can’t be recognized. I also fumbled to execute them in Pycharm, but all in vain. Could someone point out how I could get it done?

In addition, I am somewhat curious about this method because there seems to be handy way to approach this on Pycharm. Could I achieve the same goal on that?

I am using Python 2.7 and all previous exercises operate well until ex46.

Body:
You get that error because you're typing a superfluous $ at the beginning of each command. That $ is the (Linux) command prompt. On your Windows machine, it's something like C:\WINDOWS\system32>. Don't type that.

Just type

mkdir projects

and press Enter. That creates a folder (directory) named "projects". Then type

cd projects

and press Enter. That changes the current directory to that new folder you just created. And so on.

Content migrated from comments since this is what actually solved the issue.

ContentLicense: CC BY-SA 4.0


问:
What is the best way to achieve following design (attached image)?
All,

I know this is not difficult one, But I just want to know that which is the best way to achieve . You can see two icons exactly between two layouts (blackish and white). I know we can achieve this using margin but is there any other better way ?

P.S To clarify the confusion this is what my entire screen should look like

Thanks in advance.
Answer will be appreciated.

答:
If you like to Use ConstraintLayout try:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!--UpperLayer-->
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:background="@android:color/black"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </LinearLayout>

    <!--LowerLayer-->
    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:background="@android:color/darker_gray"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="@+id/linearLayout"
        app:layout_constraintStart_toStartOf="@+id/linearLayout"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout">

    </LinearLayout>

    <!--MiddleLayer-->
    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="@+id/linearLayout2"
        app:layout_constraintStart_toStartOf="@+id/linearLayout2"
        app:layout_constraintTop_toTopOf="@+id/linearLayout2">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:src="@android:drawable/ic_menu_add" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:src="@android:drawable/ic_menu_add" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

It Outputs:

Note:
Your UpperLayer and LowerLayer can be any Layout View, not fixed to LinearLayout

Body:
If you like to Use ConstraintLayout try:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!--UpperLayer-->
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:background="@android:color/black"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </LinearLayout>

    <!--LowerLayer-->
    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:background="@android:color/darker_gray"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="@+id/linearLayout"
        app:layout_constraintStart_toStartOf="@+id/linearLayout"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout">

    </LinearLayout>

    <!--MiddleLayer-->
    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="@+id/linearLayout2"
        app:layout_constraintStart_toStartOf="@+id/linearLayout2"
        app:layout_constraintTop_toTopOf="@+id/linearLayout2">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:src="@android:drawable/ic_menu_add" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:src="@android:drawable/ic_menu_add" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

It Outputs:

Note:
Your UpperLayer and LowerLayer can be any Layout View, not fixed to LinearLayout


问:
Can I detect if key is pressed in another window using java
I want to create a program that would run in the background and everytime the user presses a key, the program would notify him in which language he is writing.
but I don't know how to detect (if possible) a key pressing in another unrealated program…
As far as I know keylisteners are only for my own java program when it has the focus, so it is not that useful for me…
(Sorry for my poor english)</p>

答:
Try JNativeHook, it does this nicely.

Only caveat is that the key codes returned are different from those that Java uses IIRC.

I could show you a working program but Stack Overflow doesn't let me link to it because that would be "advertising". No time to produce an SSCCE for this space right now, sorry. I think JNativeHook is not hard to get into anyway.


问:
Limiting number of characters for sitecore single line text field while editing in Experiance editor
Requirement:

Limit the number of characters sitecore single line text field

While editing(not while saving) in experience editor should not allow more than the limit mentioned.

Field should be shown with sub line text (title text should show the details about the limitation)

Example: If the sitecore single line text field is limited to 30 characters, While editing in the experience editor should not allow more than 30 characters and will also sub line (this field will not allow more than 30 characters)

Please provide preferred approach to fulfill this

答:
I think you should create Sitecore custom field with javascript to achieve that,there are some blog posts talking about that:

https://www.sitecore.net/company/blog/474/creating-a-custom-sitecore-field-4246

https://www.geekhive.com/buzz/post/2014/05/how-to-create-a-custom-field-in-sitecore/

I have done that before with "Sitecore Tags Field", which is custom field  and i am using javascript to get list of available tags, i am sure you don't need that but you can see how i am using javascript with that code, you can check my blog post here:

https://abarhoum.wordpress.com/2017/07/06/sitecore-tag-field-tags-and-autocomplete/

i have uploded the code on github as well:

https://github.com/abarhoum/TagControl


问:
TypeError: Fetch argument array has invalid type numpy.ndarray, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)

I am trying to reproduce the results in siaseme LSTM to compare the semantic similarity of two sentences from here :- https://github.com/dhwajraj/deep-siamese-text-similarity

I am using tensorflow 1.4 & python 2.7

The train.py is working properly. For evaluating the model, I created a match_valid.tsv file which is a subset of "train_snli.txt" available there. I have modified the getTsvTestData function present in the input_helpers.py file.

```<code>def getTsvTestData(self, filepath):
        print("Loading testing/labelled data from "+filepath+"\n")
        x1=[]
        x2=[]
        y=[]
        # positive samples from file
        for line in open(filepath):
            l=line.strip().split("\t")
            if len(l)<3:
                continue
            x1.append(l[1].lower()) # text
            x2.append(l[0].lower()) # text
            y.append(int(l[2])) # similarity score 0 or 1
        return np.asarray(x1),np.asarray(x2),np.asarray(y)
</code>```

I am getting error from this part of code in eval.py

```<code>for db in batches:
            x1_dev_b,x2_dev_b,y_dev_b = zip(*db)
            #x1_dev_b = tf.convert_to_tensor(x1_dev_b,)
            print("type x1_dev_b {}".format(type(x1_dev_b))) # tuple
            print("type x2_dev_b {}".format(type(x2_dev_b))) # tuple
            print("type y_dev_b {}\n".format(type(y_dev_b))) # tuple

            feed = {input_x1: x1_dev_b,
                    input_x2: x2_dev_b,
                    input_y:y_dev_b,
                    dropout_keep_prob: 1.0}

            batch_predictions, batch_acc, sim = sess.run([predictions,accuracy,sim], feed_dict=feed)

            print("type batch_predictions {}".format(type(batch_predictions))) # numpy.ndarray
            print("type batch_acc {}".format(type(batch_acc))) # numpy.float32
            print("type sim {}".format(type(sim))) # numpy.ndarray

            all_predictions = np.concatenate([all_predictions, batch_predictions])

            print("\n printing batch predictions {} \n".format(batch_predictions))

            all_d = np.concatenate([all_d, sim])

            print("DEV acc {} \n".format(batch_acc))
</code>```

I am getting this error. I tried to use print statement in sess.run() to find the type but it didn`t work.

```<code>Traceback (most recent call last):
  File "eval.py", line 92, in <module>
    batch_predictions, batch_acc, sim = sess.run([predictions,accuracy,sim], feed_dict=feed)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1105, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 414, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 234, in for_fetch
    return _ListFetchMapper(fetch)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 341, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 242, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 275, in __init__
    % (fetch, type(fetch), str(e)))
TypeError: Fetch argument array([ 1.,  1.,  0.,  0.,  0.,  1.,  1.,  0.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,
        0.,  1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,
        0.,  0.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,  1.,
        1.,  0.,  0.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,
        0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,
        0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,
        0.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,
        1.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,
        0.,  1.,  0.,  0.,  1.,  0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,  1.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  1.,  0.,  0.,  1.,
        1.,  0.,  0.,  1.,  0.,  1.,  0.,  0.,  0.], dtype=float32) has invalid type <type 'numpy.ndarray'>, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)
</code>```

Actually, I am trying to do a query similarity, comparing the query vector to all document vectors in my corpus and rank the sentences based on the similarity score. I know that currently the LSTM is just comparing two sentences with each other and output the similarity as 0 or 1. How can I do that?

答:
The problem is that you are replacing the value of sim, which (I suppose) initially contains a reference to a TensorFlow tensor or operation, with the result of evaluating it (which is a NumPy array), so the second iteration fails because sim is not a TensorFlow tensor or operation anymore.

You can try something like this:

```<code>for db in batches:
            x1_dev_b,x2_dev_b,y_dev_b = zip(*db)
            #x1_dev_b = tf.convert_to_tensor(x1_dev_b,)
            print("type x1_dev_b {}".format(type(x1_dev_b))) # tuple
            print("type x2_dev_b {}".format(type(x2_dev_b))) # tuple
            print("type y_dev_b {}\n".format(type(y_dev_b))) # tuple

            feed = {input_x1: x1_dev_b,
                    input_x2: x2_dev_b,
                    input_y:y_dev_b,
                    dropout_keep_prob: 1.0}

            batch_predictions, batch_acc, batch_sim = sess.run([predictions,accuracy,sim], feed_dict=feed)

            print("type batch_predictions {}".format(type(batch_predictions))) # numpy.ndarray
            print("type batch_acc {}".format(type(batch_acc))) # numpy.float32
            print("type batch_sim {}".format(type(batch_sim))) # numpy.ndarray

            all_predictions = np.concatenate([all_predictions, batch_predictions])

            print("\n printing batch predictions {} \n".format(batch_predictions))

            all_d = np.concatenate([all_d, batch_sim])

            print("DEV acc {} \n".format(batch_acc))
</code>```

Body:
I am trying to reproduce the results in siaseme LSTM to compare the semantic similarity of two sentences from here :- https://github.com/dhwajraj/deep-siamese-text-similarity

I am using tensorflow 1.4 & python 2.7

The train.py is working properly. For evaluating the model, I created a match_valid.tsv file which is a subset of "train_snli.txt" available there. I have modified the getTsvTestData function present in the input_helpers.py file.

def getTsvTestData(self, filepath):
        print("Loading testing/labelled data from "+filepath+"\n")
        x1=[]
        x2=[]
        y=[]
        # positive samples from file
        for line in open(filepath):
            l=line.strip().split("\t")
            if len(l)<3:
                continue
            x1.append(l[1].lower()) # text
            x2.append(l[0].lower()) # text
            y.append(int(l[2])) # similarity score 0 or 1
        return np.asarray(x1),np.asarray(x2),np.asarray(y)

I am getting error from this part of code in eval.py

for db in batches:
            x1_dev_b,x2_dev_b,y_dev_b = zip(*db)
            #x1_dev_b = tf.convert_to_tensor(x1_dev_b,)
            print("type x1_dev_b {}".format(type(x1_dev_b))) # tuple
            print("type x2_dev_b {}".format(type(x2_dev_b))) # tuple
            print("type y_dev_b {}\n".format(type(y_dev_b))) # tuple

            feed = {input_x1: x1_dev_b,
                    input_x2: x2_dev_b,
                    input_y:y_dev_b,
                    dropout_keep_prob: 1.0}

            batch_predictions, batch_acc, sim = sess.run([predictions,accuracy,sim], feed_dict=feed)

            print("type batch_predictions {}".format(type(batch_predictions))) # numpy.ndarray
            print("type batch_acc {}".format(type(batch_acc))) # numpy.float32
            print("type sim {}".format(type(sim))) # numpy.ndarray

            all_predictions = np.concatenate([all_predictions, batch_predictions])

            print("\n printing batch predictions {} \n".format(batch_predictions))

            all_d = np.concatenate([all_d, sim])

            print("DEV acc {} \n".format(batch_acc))

I am getting this error. I tried to use print statement in sess.run() to find the type but it didn`t work.

Traceback (most recent call last):
  File "eval.py", line 92, in <module>
    batch_predictions, batch_acc, sim = sess.run([predictions,accuracy,sim], feed_dict=feed)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1105, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 414, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 234, in for_fetch
    return _ListFetchMapper(fetch)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 341, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 242, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 275, in __init__
    % (fetch, type(fetch), str(e)))
TypeError: Fetch argument array([ 1.,  1.,  0.,  0.,  0.,  1.,  1.,  0.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,
        0.,  1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,
        0.,  0.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,  1.,
        1.,  0.,  0.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,
        0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,
        0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,
        0.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,
        1.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,
        0.,  1.,  0.,  0.,  1.,  0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,  1.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  1.,  0.,  0.,  1.,
        1.,  0.,  0.,  1.,  0.,  1.,  0.,  0.,  0.], dtype=float32) has invalid type <type 'numpy.ndarray'>, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)

Actually, I am trying to do a query similarity, comparing the query vector to all document vectors in my corpus and rank the sentences based on the similarity score. I know that currently the LSTM is just comparing two sentences with each other and output the similarity as 0 or 1. How can I do that?

Body:
The problem is that you are replacing the value of sim, which (I suppose) initially contains a reference to a TensorFlow tensor or operation, with the result of evaluating it (which is a NumPy array), so the second iteration fails because sim is not a TensorFlow tensor or operation anymore.

You can try something like this:

for db in batches:
            x1_dev_b,x2_dev_b,y_dev_b = zip(*db)
            #x1_dev_b = tf.convert_to_tensor(x1_dev_b,)
            print("type x1_dev_b {}".format(type(x1_dev_b))) # tuple
            print("type x2_dev_b {}".format(type(x2_dev_b))) # tuple
            print("type y_dev_b {}\n".format(type(y_dev_b))) # tuple

            feed = {input_x1: x1_dev_b,
                    input_x2: x2_dev_b,
                    input_y:y_dev_b,
                    dropout_keep_prob: 1.0}

            batch_predictions, batch_acc, batch_sim = sess.run([predictions,accuracy,sim], feed_dict=feed)

            print("type batch_predictions {}".format(type(batch_predictions))) # numpy.ndarray
            print("type batch_acc {}".format(type(batch_acc))) # numpy.float32
            print("type batch_sim {}".format(type(batch_sim))) # numpy.ndarray

            all_predictions = np.concatenate([all_predictions, batch_predictions])

            print("\n printing batch predictions {} \n".format(batch_predictions))

            all_d = np.concatenate([all_d, batch_sim])

            print("DEV acc {} \n".format(batch_acc))


问:
How do i get right the directory of my application?
I've made a small console application (first publish in c#). but i cant use my resource files. I used textfiles can give it. It worked when i used the debug directory

My goal is to create a directory like this:
Applicationmap
+ application.exe
+ setup
resource map
+ configurations.txt
Logger
+ .

Now if i try to reach the configuration file it sends me to:
C:\Users\<username> \AppData\Local\Apps\2.0\D01L7N51.9EW\R7HB7NAB.B7Y
\sele..tion_0000000000000000_0001.0000_92af5262ce6f49d8

While i'm expecting C:/Users/<username>/ Documents/<application>/ + resources/config.txt.

I've tried

```<code>string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine(dir);
</code>```

&&

```<code>Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
</code>```

&&

```<code>Console.WriteLine(Directory.GetCurrentDirectory());
</code>```

but i always end up at the appdata map.

答:
You could simply use Application.StartupPath (reference), but the outcome will always depend on where you place/install the executable file

If you always want to point the current user's Documents folder (which is registered as a special folder within the operating system), like in your example, you could either use:

```<code>String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

or (but at your own risk since its much less safe):

```<code>String path = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents");
</code>```

Once you have retrieved the correct Documents folder path with either the first or the second approach, combine it with the last part:

```<code>path = Path.Combine(path, "resources/config.txt");
</code>```

For more information concerning the two approaches:

Environment.GetFolderPath

Environment.ExpandEnvironmentVariables

Body:
I've made a small console application (first publish in c#). but i cant use my resource files. I used textfiles can give it. It worked when i used the debug directory

My goal is to create a directory like this:
Applicationmap
+ application.exe
+ setup
resource map
+ configurations.txt
Logger
+ .

Now if i try to reach the configuration file it sends me to:
C:\Users\<username> \AppData\Local\Apps\2.0\D01L7N51.9EW\R7HB7NAB.B7Y
\sele..tion_0000000000000000_0001.0000_92af5262ce6f49d8

While i'm expecting C:/Users/<username>/ Documents/<application>/ + resources/config.txt.

I've tried

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Console.WriteLine(dir);

&&

Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

&&

Console.WriteLine(Directory.GetCurrentDirectory());

but i always end up at the appdata map.

Body:
You could simply use Application.StartupPath (reference), but the outcome will always depend on where you place/install the executable file

If you always want to point the current user's Documents folder (which is registered as a special folder within the operating system), like in your example, you could either use:

String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

or (but at your own risk since its much less safe):

String path = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents");

Once you have retrieved the correct Documents folder path with either the first or the second approach, combine it with the last part:

path = Path.Combine(path, "resources/config.txt");

For more information concerning the two approaches:

Environment.GetFolderPath

Environment.ExpandEnvironmentVariables


问:
Google PlayStore console 2017 - obb extension file upload
I am using APK with external OBB Extension file.

PlayStore Console UI has changed since I used this feature last.
I can not figure out how to upload the OBB file.

Even the PlayStore help describes the wrong, old way.

https://support.google.com/googleplay/android-developer/answer/2481797?hl=de

Can someone please give me a hint.

Seems to be solved - the small + button was missing in the German UI Version. I changed my language to English and the + button was there. Now in 2018 the + button is also visible in the German UI. Thanx Google

答:
I've been able to chat with Google support about this, and it's indeed kind of hard to miss. This is not like before where you could set the expansion file at APK upload anymore.

To upload an expansion file or use an existing expansion file, you can only do that while uploading the APK, not after you click on Save.

Once you uploaded the APK, on the line where the APK name is, there's a small + icon with the tooltip "Update APK", you have to click on this icon, and there there's the ability to set/upload expansion file.


问:
Change dependency version number in multi project gradle build
I have a multi module gradle project which contains core and client. client depends on core which is declared like this:

```<code>dependencies {
    compile project(':core')
}
</code>```

If I publish core and client to Ivy or Maven the dependency from client to core uses the exact version that is currently defined for the core (e.g. 1.0.0).

Is there a way to change that? Let's say the core is guaranteed to be compatible between minor releases. So instead of 1.0.0 i'd like the dependency to be to version 1.+.

答:
In order to replace the version in the generated pom.xml I created a helper function:

```<code>// helper function to replace dependency version in maven pom.xml
def replaceDependencyVersion(root, groupId, artifactId, version) {
    // replace version
    root.dependencies.dependency.findAll() { node ->
        node.groupId.text() == groupId && node.artifactId.text() == artifactId
    }.each() { node ->
        node.version*.value = version
    }
}
</code>```

This function can then be used in publishing to replace the version number:

```<code>// publishing
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java

            pom.withXml {
                replaceDependencyVersion(asNode(), 'com.test', 'core', '1.+')
            }
        }
    }
}
</code>```

Body:
I have a multi module gradle project which contains core and client. client depends on core which is declared like this:

dependencies {
    compile project(':core')
}

If I publish core and client to Ivy or Maven the dependency from client to core uses the exact version that is currently defined for the core (e.g. 1.0.0).

Is there a way to change that? Let's say the core is guaranteed to be compatible between minor releases. So instead of 1.0.0 i'd like the dependency to be to version 1.+.

Body:
In order to replace the version in the generated pom.xml I created a helper function:

// helper function to replace dependency version in maven pom.xml
def replaceDependencyVersion(root, groupId, artifactId, version) {
    // replace version
    root.dependencies.dependency.findAll() { node ->
        node.groupId.text() == groupId && node.artifactId.text() == artifactId
    }.each() { node ->
        node.version*.value = version
    }
}

This function can then be used in publishing to replace the version number:

// publishing
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java

            pom.withXml {
                replaceDependencyVersion(asNode(), 'com.test', 'core', '1.+')
            }
        }
    }
}