问:
correctness of json document for elasticsearch?
I am new for Json Document,i hava database with the following fileds:

On the basis of database field i have created Json document:

================================================================

```<code>{"Id":["fifth","first","four","second","thrid"],"keyword":["michel","sam","jerry","John","smith"]}
</code>```

================================================================

I just want to know that the prepared json document is correct for elastic search or not? if wrong then what will be correct document for that.

Thanks

答:
I dont think it is good. You should create json in following format.

```<code>var data = {
    "fifth" : "michel",
    "first" : "sam",
    "four" : "jerry",
    "second" : "John",
    "thrid" : "smith"
}
</code>```

So when you need to get the fourth element, so can just get it by following

```<code>var fourth = data["four"];
</code>```

hope this helps!

Body:
I am new for Json Document,i hava database with the following fileds:

On the basis of database field i have created Json document:

================================================================

{"Id":["fifth","first","four","second","thrid"],"keyword":["michel","sam","jerry","John","smith"]}

================================================================

I just want to know that the prepared json document is correct for elastic search or not? if wrong then what will be correct document for that.

Thanks

Body:
I dont think it is good. You should create json in following format.

var data = {
    "fifth" : "michel",
    "first" : "sam",
    "four" : "jerry",
    "second" : "John",
    "thrid" : "smith"
}

So when you need to get the fourth element, so can just get it by following

var fourth = data["four"];

hope this helps!


来源: stackexchange

问:
How to remove Empty Rows from a list in Python 3.5
```<code>apple
mango
banana

tea

coffee
</code>```

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

```<code>apple
mango
banana
tea
coffee
</code>```

答:
LIST

```<code>list = ["apple", "mango", "banana", "", "tea", "", "coffee"]
while "" in list:
    del list[list.index("")]
print(list)
</code>```

Output:

```<code>["apple", "mango", "banana", "tea", "coffee"]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
apple
mango
banana

tea

coffee

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

apple
mango
banana
tea
coffee

Body:
LIST

list = ["apple", "mango", "banana", "", "tea", "", "coffee"]
while "" in list:
    del list[list.index("")]
print(list)

Output:

["apple", "mango", "banana", "tea", "coffee"]


问:
Few bugs on my google homepage project
The "advertising" and "About" show up purple when I run my code while the rest of the list items are black like they should be. I would also like to get rid of the outline on the search and feeling lucky buttons. outline:none; or border:none; won't work.

HTML

```<code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet"
    type="text/css"
    href="style.css">
</head>

<body>

<title>Google</title>

<div class="options">
    <ul>
          <li> <a href="button">Gmail</li>
          <li> <a href="button">Images</li>
          <li> <a href="button"><img src="http://www.myiconfinder.com/uploads/iconsets/256-256-f6227d477e683ae5bd1270aac11b93e5-grid.png"width="25px" height="25px"></li>
          <li> <a href="button"><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/338473-200.png"width="25" height="25"></li>
          <li> <a href="button"><img src=https://lh3.googleusercontent.com/-gsXjacdjY8E/AAAAAAAAAAI/AAAAAAAAAAA/AI6yGXxkQbqvng1PHA5RhhTLQowbW3ykkQ/s32-c-mo/photo.jpg></li>
    </ul>
</div>

<h1><img src=https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png></h1>

<div class="fake-input">
    <input type="text"/>
</div>

<div class="buttons">
    <ul>
      <li><input type="submit"input value="Google Search"></li>
      <li><input type="submit"input value="I'm feeling lucky!"></li>
    </ul>
</div>

<footer>
<div class="footer">
    <ul style="float:left;list-style-type:none;">
          <li><a href="https://www.google.com/intl/en/ads/?fg=1">Advertising</li>
          <li><a href="https://www.google.com/services/?fg=1">Business</li>
          <li><a href="https://www.google.com/intl/en/about/">About</li>
    </ul>

    <ul style="float:right;list-style-type:none;">
          <li><a href="https://www.google.com/intl/en/policies/privacy/?fg=1">Privacy</li>
          <li><a href="https://www.google.com/intl/en/policies/terms/?fg=1">Terms</li>
          <li><a href="https://www.google.com/preferences?hl=en">Settings</li>
    </ul>
</div>
</footer>

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

CSS

```<code>.options ul{
  text-align: right;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.options li{
  font-size:14px;
  padding: 5px;
  display: inline;
}

a:link{
text-decoration:none;
color:black;
}

img{
  border-radius:15px;
  font-family: arial,sans-serif;
}

h1{
  text-align:center;
  margin-top:160px;
}

h2{
  text-align:center;

}

input[type='text'] {
    margin-left:375px;
    width:500px;
    height:50px;
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAACrElEQVR42u2Xz2sTQRSAX8VSb1K8iNqKooJH2Ux6Ksn+iPQqxZMIehJB0do/IMhmQWsvHr2KSEGk0tSLIoWIYNUKij20F2/N7iaUZnYT0kYzzhMKs0HDJiTdLcwHDwKZSd63781LBiQSSW9JZdkhzfKm1Rz9mjZp/W9YdEU3vXv4HsQZ40FtNG36q5rls//Ej4tmbSS2T15Mvp3ExOPmEMQNbBtMMEyoljcFcQN7PqyAlqNfIG7gYQ0tYNIaxA1MrJPY3wImbUqBKAXSFv0tBSIVMOkvKRDtGKWN/T6FdqRAxFNoWwpEPIXqUqBT6ALU/UVgu8GW4GD3f6f9TRDYNJTDrk7YbtiqUumHwIYoUJuHERDAS0r4CvgFECgbY+cFAR7KT+g1POmCKFDNw6WggHc3fBtVb4CAoyauBgXIG+g1Xh5mRAGah6cggBd11fK/h7lOprIs0H6uRl6KAo5O7kOv4QmPiwJ4Jqqv4FiwCtXjvD2+tRmfK6kZ/ygI2HritK0rDVGgrClJ6DWMwYC/AGuCBMYcIC2V0CzvjmbRz3j3xUjn6CfeYreUJ2wQkGD75INPX1mFfsEFrrcIYCvdhC4paWQakxajpJMr0C9YFg54i7AsClRmh9/xnr0NHcInzZStk2aLwAcGMAD9pPIazvFKVDD5rdnhJeHLX5RTyRPQHpz5o66emMc9wdlPtvA8wF7Aq2BUHh1525qEo5JtR1WeOXpickO9cJIpyuD6xJmhYiZ5ytWSl3mlnuOaf+2zDaLDXmJrSgZ/MYVEugo+gSh+FkSBa4yd5Ul87DZ5XpFl/AyIEjzYjkau8WqshU2cr13HPbgX4gJOD97n465GZlyVvC9mSKloKI2iTnbwNT+gBX54H+IaXAtxJzE3ycSAFqSAFJACUkAikXD+AHj5/wx2o5osAAAAAElFTkSuQmCC);
    background-position: 450px 7px;
    background-repeat: no-repeat;
}

.buttons ul{
  text-align:center;
  list-style-type:none;
  margin:0;
  padding:0;
}

.buttons li{
  background-color: #f2f2f2;
  padding: 5px;
  display: inline-block;
  border:none;
}

input:focus {
  outline-style: none;
}

.footer {
  background: #f2f2f2;
  position: fixed;
  bottom: 0px;
  width:95%;
}

.footer li{
  display:inline;
  text-decoration: none;
  font-family: arial,sans-serif;
  font-size: small;
  color: #666;
}
</code>```

答:
The links in the footer are purple because you clicked them before. You can override this with the following CSS:

```<code>footer li a:visited {    /* visited selector used for links which have been visited or clicked on already */
    color: black;
}
</code>```

To remove the border simply use this CSS code:

```<code>input[type=submit] {
    border: none;
}
</code>```

Title: Few bugs on my google homepage project

Body:
The "advertising" and "About" show up purple when I run my code while the rest of the list items are black like they should be. I would also like to get rid of the outline on the search and feeling lucky buttons. outline:none; or border:none; won't work.

HTML

<!DOCTYPE html>

    <link rel="stylesheet"
    type="text/css"
    href="style.css">

<title>Google</title>

 Gmail

 Images

    <input type="text"/>

<input type="submit"input value="Google Search">

<input type="submit"input value="I'm feeling lucky!">

Advertising

Business

About

Privacy

Terms

Settings

CSS

.options ul{
  text-align: right;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.options li{
  font-size:14px;
  padding: 5px;
  display: inline;
}

a:link{
text-decoration:none;
color:black;
}

img{
  border-radius:15px;
  font-family: arial,sans-serif;
}

h1{
  text-align:center;
  margin-top:160px;
}

h2{
  text-align:center;

}

input[type='text'] {
    margin-left:375px;
    width:500px;
    height:50px;
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAACrElEQVR42u2Xz2sTQRSAX8VSb1K8iNqKooJH2Ux6Ksn+iPQqxZMIehJB0do/IMhmQWsvHr2KSEGk0tSLIoWIYNUKij20F2/N7iaUZnYT0kYzzhMKs0HDJiTdLcwHDwKZSd63781LBiQSSW9JZdkhzfKm1Rz9mjZp/W9YdEU3vXv4HsQZ40FtNG36q5rls//Ej4tmbSS2T15Mvp3ExOPmEMQNbBtMMEyoljcFcQN7PqyAlqNfIG7gYQ0tYNIaxA1MrJPY3wImbUqBKAXSFv0tBSIVMOkvKRDtGKWN/T6FdqRAxFNoWwpEPIXqUqBT6ALU/UVgu8GW4GD3f6f9TRDYNJTDrk7YbtiqUumHwIYoUJuHERDAS0r4CvgFECgbY+cFAR7KT+g1POmCKFDNw6WggHc3fBtVb4CAoyauBgXIG+g1Xh5mRAGah6cggBd11fK/h7lOprIs0H6uRl6KAo5O7kOv4QmPiwJ4Jqqv4FiwCtXjvD2+tRmfK6kZ/ygI2HritK0rDVGgrClJ6DWMwYC/AGuCBMYcIC2V0CzvjmbRz3j3xUjn6CfeYreUJ2wQkGD75INPX1mFfsEFrrcIYCvdhC4paWQakxajpJMr0C9YFg54i7AsClRmh9/xnr0NHcInzZStk2aLwAcGMAD9pPIazvFKVDD5rdnhJeHLX5RTyRPQHpz5o66emMc9wdlPtvA8wF7Aq2BUHh1525qEo5JtR1WeOXpickO9cJIpyuD6xJmhYiZ5ytWSl3mlnuOaf+2zDaLDXmJrSgZ/MYVEugo+gSh+FkSBa4yd5Ul87DZ5XpFl/AyIEjzYjkau8WqshU2cr13HPbgX4gJOD97n465GZlyVvC9mSKloKI2iTnbwNT+gBX54H+IaXAtxJzE3ycSAFqSAFJACUkAikXD+AHj5/wx2o5osAAAAAElFTkSuQmCC);
    background-position: 450px 7px;
    background-repeat: no-repeat;
}

.buttons ul{
  text-align:center;
  list-style-type:none;
  margin:0;
  padding:0;
}

.buttons li{
  background-color: #f2f2f2;
  padding: 5px;
  display: inline-block;
  border:none;
}

input:focus {
  outline-style: none;
}

.footer {
  background: #f2f2f2;
  position: fixed;
  bottom: 0px;
  width:95%;
}

.footer li{
  display:inline;
  text-decoration: none;
  font-family: arial,sans-serif;
  font-size: small;
  color: #666;
}

Body:
The links in the footer are purple because you clicked them before. You can override this with the following CSS:

footer li a:visited {    /* visited selector used for links which have been visited or clicked on already */
    color: black;
}

To remove the border simply use this CSS code:

input[type=submit] {
    border: none;
}


问:
Replacing last occurrence of character group with Oracle REGEXP_REPLACE
I have strings like the following in my Oracle 11g table:

```<code>ABCDEF000xyz12345abcdefgh

GHIJK0000def67890abcdefgh
</code>```

I.e., the strings begin with capital letters followed by a series of zeros, followed by three characters, digits and characters again.

How can I replace the xyz12345abcdefgh and def67890abcdefgh with a certain string using REGEXP_REPLACE in Oracle?

答:
```<code>select regexp_replace(column_name,'(.*)([0]{2,})(.*)','\1\2xxxx') from table_name;
</code>```

Body:
I have strings like the following in my Oracle 11g table:

ABCDEF000xyz12345abcdefgh

GHIJK0000def67890abcdefgh

I.e., the strings begin with capital letters followed by a series of zeros, followed by three characters, digits and characters again.

How can I replace the xyz12345abcdefgh and def67890abcdefgh with a certain string using REGEXP_REPLACE in Oracle?


问:
How to access constants from a java class through other variable?
I have java class which has all constants as given below:

```<code>public final class CategoryIDs {

  public static final String Extraction_of_natural_gas = "1111";
  public static final String Mining_of_hard_coal = "2222";
  public static final String Mining_of_iron_ores = "3333";
  public static final String Mining_of_lignite = "4444";

}
</code>```

Now I want to access these constants in some other class through a variable which holds name of the variable.

For example:

```<code>String temp = "Extraction_of_natural_gas";
</code>```

Using this temp variable I want to access constants from above class. But I can't do  CategoryIDs.temp as it isn't allowed. So what is the best way to achieve this?

答:
If you really, really need to do this with your current structure, you could use reflection.

However, you may well find that an enum would be a better fit. Something like:

```<code>public enum CategoryID {

    EXTRACTION_OF_NATURAL_GAS("Extraction_of_natural_gas", 1111),
    MINING_OF_HARD_COAL("Mining_of_hard_coal", 2222),
    MINING_OF_IRON_ORES("Mining_of_iron_ores", 3333),
    MINING_OF_LIGNITE("Mining_of_lignite", 4444);

    private static final Map<String, CategoryID> keyMap;

    static {
        keyMap = new HashMap<>();
        for (CategoryID category : CategoryID.values()) {
            keyMap.put(category.getKey(), category);
        }
    }

    private final String key;
    private final int value;

    public int getValue() {
        return value;
    }

    public String getKey() {
        return key;
    }

    private CategoryID(String key, int value) {
        this.key = key;
        this.value = value;
    }

    public static CategoryID fromKey(String key) {
        return keyMap.get(key);
    }
}
</code>```

Benefits of this approach:

You separate the name in the code (which is now more conventional for Java) from the key you'd provide in the data. That means you can use whatever keys you'd like in the data, including ones with spaces in etc. They no longer need to be valid identifiers.

You still get compile-time safety when you refer to the enum values from code.

You get better safety as you'll never accidentally use a string instead of a category ID, which you could easily have done using your constants.

Body:
I have java class which has all constants as given below:

public final class CategoryIDs {

  public static final String Extraction_of_natural_gas = "1111";
  public static final String Mining_of_hard_coal = "2222";
  public static final String Mining_of_iron_ores = "3333";
  public static final String Mining_of_lignite = "4444";

}

Now I want to access these constants in some other class through a variable which holds name of the variable.

For example:

String temp = "Extraction_of_natural_gas";

Using this temp variable I want to access constants from above class. But I can't do  CategoryIDs.temp as it isn't allowed. So what is the best way to achieve this?

Body:
If you really, really need to do this with your current structure, you could use reflection.

However, you may well find that an enum would be a better fit. Something like:

public enum CategoryID {

    EXTRACTION_OF_NATURAL_GAS("Extraction_of_natural_gas", 1111),
    MINING_OF_HARD_COAL("Mining_of_hard_coal", 2222),
    MINING_OF_IRON_ORES("Mining_of_iron_ores", 3333),
    MINING_OF_LIGNITE("Mining_of_lignite", 4444);

    private static final Map<String, CategoryID> keyMap;

    static {
        keyMap = new HashMap<>();
        for (CategoryID category : CategoryID.values()) {
            keyMap.put(category.getKey(), category);
        }
    }

    private final String key;
    private final int value;

    public int getValue() {
        return value;
    }

    public String getKey() {
        return key;
    }

    private CategoryID(String key, int value) {
        this.key = key;
        this.value = value;
    }

    public static CategoryID fromKey(String key) {
        return keyMap.get(key);
    }
}

Benefits of this approach:

You separate the name in the code (which is now more conventional for Java) from the key you'd provide in the data. That means you can use whatever keys you'd like in the data, including ones with spaces in etc. They no longer need to be valid identifiers.

You still get compile-time safety when you refer to the enum values from code.

You get better safety as you'll never accidentally use a string instead of a category ID, which you could easily have done using your constants.


问:
Quickest way to build a bunch of DLL files with the same settings in VS 2008
I'm currently porting a POSIX C++ application to run on Windows without Cygwin or anything. No problem so far. Now, the application (ZNC, an IRC bouncer, in case you're interested) supports loading modules from .so shared library files on Linux/BSD etc.

I ported the main executable without much of a problem, all wrapped into a VS 2008 project file and stuff. Now, said modules are all separate .cpp files which can't be linked into the executable as they all export symbols like GetVersion(). And it isn't feasible anyway.

So, to cut a long story short, I want to (have to) compile all the modules (over 20) into separate DLL files. I don't want to create a single VS project for each however. Which means I'll probably have to create a makefile? Or something the like? I've never done that before on Windows, so that's my question. What is the best approach to compile a bunch of .cpps into separate DLL files (with the same settings, all stored conveniently in one place/file)?

Thanks in Advance!
I.R.

答:
As far as I know there is no built in way to do this. So here is what I would do:

Convert one of the modules into a DLL, make sure it works and everything is kosher.

Write a script to generate the other 20 vcproj's from the one reference vcproj that works. I don't know the details of your module system so i'm not sure how strait forward that will be.

Add them into the solution.

Hopefully that works.

OwnerDisplayName: KiNgMaR

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jon Clegg


问:
Securing API in lumen
im new in lumen and im trying to secure my registration api by putting a code called Api-Token so only users that know the code can create a new user but everytime i try to create a new user i cant do it

here is what ive done so far

Middleware/Authenticate

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use App\User;

class Authenticate
{
/**
 * The authentication guard factory instance.
 *
 * @var \Illuminate\Contracts\Auth\Factory
 */
protected $auth;

/**
 * Create a new middleware instance.
 *
 * @param  \Illuminate\Contracts\Auth\Factory  $auth
 * @return void
 */
public function __construct(Auth $auth)
{
    $this->auth = $auth;
}

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null)
{

    if ($this->auth->guard($guard)->guest()) {
        if ($request->has('api_token')) {
            $token = $request->input('api_token');
            $check_token = User::where('api_token', $token)->first();
            if ($check_token == null) {
                $res['success'] = false;
                $res['message'] = 'Permission not allowed!';

                return response($res);
            }
        }else{
            $res['success'] = false;
            $res['message'] = 'Unauthorized!';

            return response($res);
        }
    }
    return $next($request);
}
}
</code>```

AuthServiceProvider

```<code><?php

namespace App\Providers;

use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
</code>```

{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

```<code>/**
 * Boot the authentication services for the application.
 *
 * @return void
 */
public function boot()
{
    // Here you may define how you wish users to be authenticated for your Lumen
    // application. The callback which receives the incoming request instance
    // should return either a User instance or null. You're free to obtain
    // the User instance via an API token or any other method necessary.

    // $this->app['auth']->viaRequest('api', function ($request) {
    //     $header = $request->header('Api-Token');

    //     if ($header && $header == 'bird is a word') {
    //         return new User();
    //     }

    //     return null;

    $this->app['auth']->viaRequest('api', function ($request) {
        if ($request->input('api_token')) {
            return User::where('api_token', $request->input('api_token'))->first();
        }

    });
}
}
</code>```

Routes

```<code><?php

$app->get('/', function () use ($app) {
$res['success'] = true;
$res['result'] = "Hello there welcome to web api using lumen tutorial!";
return response($res);
});

$app->post('/login', 'LoginController@index');
$app->post('/register', ['middleware' => 'auth', 'uses' => 'UserController@register']);
$app->get('/user/{id}', ['middleware' => 'auth', 'uses' =>  'UserController@get_user']);
</code>```

答:
I am recommending to use JWT (JSON WEB TOKEN) Authentication to secure your API

https://packagist.org/packages/tymon/jwt-auth

Installation document

Try this package to integrate authentication with your Lumen Application

Title: Securing API in lumen

Body:
im new in lumen and im trying to secure my registration api by putting a code called Api-Token so only users that know the code can create a new user but everytime i try to create a new user i cant do it

here is what ive done so far

Middleware/Authenticate

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use App\User;

class Authenticate
{
/**
 * The authentication guard factory instance.
 *
 * @var \Illuminate\Contracts\Auth\Factory
 */
protected $auth;

/**
 * Create a new middleware instance.
 *
 * @param  \Illuminate\Contracts\Auth\Factory  $auth
 * @return void
 */
public function __construct(Auth $auth)
{
    $this->auth = $auth;
}

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null)
{

    if ($this->auth->guard($guard)->guest()) {
        if ($request->has('api_token')) {
            $token = $request->input('api_token');
            $check_token = User::where('api_token', $token)->first();
            if ($check_token == null) {
                $res['success'] = false;
                $res['message'] = 'Permission not allowed!';

                return response($res);
            }
        }else{
            $res['success'] = false;
            $res['message'] = 'Unauthorized!';

            return response($res);
        }
    }
    return $next($request);
}
}

AuthServiceProvider

<?php

namespace App\Providers;

use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider

{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    }

/**
 * Boot the authentication services for the application.
 *
 * @return void
 */
public function boot()
{
    // Here you may define how you wish users to be authenticated for your Lumen
    // application. The callback which receives the incoming request instance
    // should return either a User instance or null. You're free to obtain
    // the User instance via an API token or any other method necessary.

    // $this->app['auth']->viaRequest('api', function ($request) {
    //     $header = $request->header('Api-Token');

    //     if ($header && $header == 'bird is a word') {
    //         return new User();
    //     }

    //     return null;

    $this->app['auth']->viaRequest('api', function ($request) {
        if ($request->input('api_token')) {
            return User::where('api_token', $request->input('api_token'))->first();
        }

    });
}
}

Routes

<?php

$app->get('/', function () use ($app) {
$res['success'] = true;
$res['result'] = "Hello there welcome to web api using lumen tutorial!";
return response($res);
});

$app->post('/login', 'LoginController@index');
$app->post('/register', ['middleware' => 'auth', 'uses' => 'UserController@register']);
$app->get('/user/{id}', ['middleware' => 'auth', 'uses' =>  'UserController@get_user']);

ContentLicense: CC BY-SA 4.0


问:
How to condition script based on SAP system?
I am doing a task which connects excel with SAP system via SAP GUI.

I want to use SUIM transaction but the problem is the view is different for different systems.

For eg :

In system A,
i have this code :

```<code>session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02  1      2"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03  2      7"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04  2      8", "1"
' ** START OF DIFFERENCE **
session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3").Select
session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3/ssub%_SUBSCREEN_TAB:RSUSR002:1003/btn%_ACTGRPS_%_APP_%-VALU_PUSH").press
' ** END OF DIFFERENCE **
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*********"
</code>```

and for system B,

```<code>session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02  1      2"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03  2      7"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04  2      8", "1"
' ** START OF DIFFERENCE **
session.findById("wnd[0]/usr/btn%_ACTGRPS_%_APP_%-VALU_PUSH").press
' ** END OF DIFFERENCE **
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*******"
</code>```

So, as you see, only the lines marked have the difference.

What should I do to get a common code so that I can run in both the systems with just one code?

答:
try this</p>

```<code>Private Sub MySAPSub(SystemType As String)
    session.findById("wnd[0]").maximize
    session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
    session.findById("wnd[0]").sendVKey 0
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02 1 2"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03 2 7"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04 2 8", "1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04 2 8", "1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04 2 8", "1"

    If (SystemType = "ABC 100") Then
        session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3").Select
        session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3/ssub%_SUBSCREEN_TAB:RSUSR002:1003/btn%ACTGRPS%APP%-VALU_PUSH").press
    ElseIf (SystemType = "ABC 200") Then
        session.findById("wnd[0]/usr/btn%ACTGRPS%APP%-VALU_PUSH").press
    End If

    session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*******"
End Sub

Private Sub CallMySAPSub()

    ' Call System ABC 100
    MySAPSub ("ABC 100")

    ' Call System ABC 200
    MySAPSub ("ABC 200")
End Sub
</code>```

Body:
I am doing a task which connects excel with SAP system via SAP GUI.

I want to use SUIM transaction but the problem is the view is different for different systems.

For eg :

In system A,
i have this code :

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02  1      2"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03  2      7"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04  2      8", "1"
' ** START OF DIFFERENCE **
session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3").Select
session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3/ssub%_SUBSCREEN_TAB:RSUSR002:1003/btn%_ACTGRPS_%_APP_%-VALU_PUSH").press
' ** END OF DIFFERENCE **
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*********"

and for system B,

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02  1      2"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03  2      7"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04  2      8", "1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01  1      1"
session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04  2      8", "1"
' ** START OF DIFFERENCE **
session.findById("wnd[0]/usr/btn%_ACTGRPS_%_APP_%-VALU_PUSH").press
' ** END OF DIFFERENCE **
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*******"

So, as you see, only the lines marked have the difference.

What should I do to get a common code so that I can run in both the systems with just one code?

Body:
try this

Private Sub MySAPSub(SystemType As String)
    session.findById("wnd[0]").maximize
    session.findById("wnd[0]/tbar[0]/okcd").Text = "suim"
    session.findById("wnd[0]").sendVKey 0
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "02 1 2"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").expandNode "03 2 7"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").selectItem "04 2 8", "1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").ensureVisibleHorizontalItem "04 2 8", "1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").topNode = "01 1 1"
    session.findById("wnd[0]/usr/cntlTREE_CONTROL_CONTAINER/shellcont/shell").clickLink "04 2 8", "1"

    If (SystemType = "ABC 100") Then
        session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3").Select
        session.findById("wnd[0]/usr/tabsTABSTRIP_TAB/tabpTAB3/ssub%_SUBSCREEN_TAB:RSUSR002:1003/btn%ACTGRPS%APP%-VALU_PUSH").press
    ElseIf (SystemType = "ABC 200") Then
        session.findById("wnd[0]/usr/btn%ACTGRPS%APP%-VALU_PUSH").press
    End If

    session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = "*******"
End Sub

Private Sub CallMySAPSub()

    ' Call System ABC 100
    MySAPSub ("ABC 100")

    ' Call System ABC 200
    MySAPSub ("ABC 200")
End Sub


问:
Bulk 'find and replace' function for multiple lines in Notepad++ or Programmer's Notepad?
I have a file with thousands of code lines where I need to first find a file name (text between <path>./THIS-TEXT.rom</path>), copy that text, and then replace the very following line (text between <name>this-one-replaced</name>) with that text. Then move on until the next sequence is found.

I've been manually doing this before realizing it will likely take me 8 hours of manually doing this to complete my project. I figure there must be some easier way to do this. Below is an example of the two code blocks in succession. Mind you that it's just two out of several thousand in succession.

```<code><game id="494">
    <path>./The Legend of Zelda.rom</path>
    <name>legend of zelda, the (en,eu,it)</name>
    <genre>Miscellaneous</genre>
</game>
<game id="954">
    <path>./Final Fantasy.rom</path>
    <name>final fantasy (usa, europe)</name>
    <genre>Miscellaneous</genre>
</game>
</code>```

Basically, I need to figure out how to take text between <path>./ and
.rom</path>, and replace the next line with it between <name> and </name> to look like this as it moves down the file for the next occurrence.

```<code><game id="494">
    <path>./The Legend of Zelda.rom</path>
    <name>The Legend of Zelda</name>
    <genre>Miscellaneous</genre>
</game>
<game id="954">
    <path>./Final Fantasy.rom</path>
    <name>Final Fantasy</name>
    <genre>Miscellaneous</genre>
</game>
</code>```

答:
In Notepad++ this can be done with a simple regular expression. Search for:

```<code>^(\h*<path>\./)([^<>\r\n]+)(\.rom</path>\h*[\r\n]+\h*<name>)[^<>\r\n]*(</name>)
</code>```

and replace it with

```<code>\1\2\3\2\4
</code>```

Explanation:

^(\h*<path>\./) Gets the opening path text and saves it in capture group \1.

([^<>\r\n]+) Gets the wanted file name text from the path line, saving it to \2.

(\.rom</path> Gets the remainder of the path line.

\h*[\r\n]+\h*<name>) Gets the line break and the whitespace and the start of the name line. This text and the remainder of the path line are saved to \3.

[^<>\r\n]* Gets the unwanted part of the name line and does not save it.

(</name>) Gets the final part of the name line and saves it to \4.

Reassembly. The \1\2\3 makes the path line and the start of the name line. The next \2 replaces the unwanted name line text with the wanted part of the file name. The final \4 completes the new name line.

Of course, "Regular expression" must be selected in the replace window of Notepad++.

Body:
I have a file with thousands of code lines where I need to first find a file name (text between <path>./THIS-TEXT.rom</path>), copy that text, and then replace the very following line (text between <name>this-one-replaced</name>) with that text. Then move on until the next sequence is found.

I've been manually doing this before realizing it will likely take me 8 hours of manually doing this to complete my project. I figure there must be some easier way to do this. Below is an example of the two code blocks in succession. Mind you that it's just two out of several thousand in succession.

<game id="494">
    <path>./The Legend of Zelda.rom</path>
    <name>legend of zelda, the (en,eu,it)</name>
    <genre>Miscellaneous</genre>
</game>
<game id="954">
    <path>./Final Fantasy.rom</path>
    <name>final fantasy (usa, europe)</name>
    <genre>Miscellaneous</genre>
</game>

Basically, I need to figure out how to take text between <path>./ and
.rom</path>, and replace the next line with it between <name> and </name> to look like this as it moves down the file for the next occurrence.

<game id="494">
    <path>./The Legend of Zelda.rom</path>
    <name>The Legend of Zelda</name>
    <genre>Miscellaneous</genre>
</game>
<game id="954">
    <path>./Final Fantasy.rom</path>
    <name>Final Fantasy</name>
    <genre>Miscellaneous</genre>
</game>

Body:
In Notepad++ this can be done with a simple regular expression. Search for:

^(\h*<path>\./)([^<>\r\n]+)(\.rom</path>\h*[\r\n]+\h*<name>)[^<>\r\n]*(</name>)

and replace it with

\1\2\3\2\4

Explanation:

^(\h*<path>\./) Gets the opening path text and saves it in capture group \1.

([^<>\r\n]+) Gets the wanted file name text from the path line, saving it to \2.

(\.rom</path> Gets the remainder of the path line.

\h*[\r\n]+\h*<name>) Gets the line break and the whitespace and the start of the name line. This text and the remainder of the path line are saved to \3.

[^<>\r\n]* Gets the unwanted part of the name line and does not save it.

(</name>) Gets the final part of the name line and saves it to \4.

Reassembly. The \1\2\3 makes the path line and the start of the name line. The next \2 replaces the unwanted name line text with the wanted part of the file name. The final \4 completes the new name line.

Of course, "Regular expression" must be selected in the replace window of Notepad++.


问:
How does [ ] work with a function, is the mean the function become and element?
I have a low triangle matrix:

```<code>> Mat1
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    1    0    0    0    0
[3,]    3    3    0    0    0
[4,]    4    4    4    0    0
[5,]    4    1    1    3    0
</code>```

lower.tri returns a matrix of logicals the same size of a given matrix with entries TRUE in the lower or upper triangle (R help).

Then lets

```<code>lowt <– lower.tri(Mat1)
xx <– Mat1[lowt]
xx
[1] 1 3 4 4 3 4 1 4 1 3
</code>```

My question is how does Mat1[lowt] work? how do we use the function as an element by using [ ]?! what is the idea? any help please?

答:
how do we use the function as an element by using [ ]?!

lowt is not a function, but a boolean matrix, as you said yourself:
lowt <– lower.tri(Mat1) saves the return variable of lower.tri in lowt; Mat1[lowt] therefore returns values from Mat1, by logical indexing - a widely used concept in R.

Body:
I have a low triangle matrix:

> Mat1
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    1    0    0    0    0
[3,]    3    3    0    0    0
[4,]    4    4    4    0    0
[5,]    4    1    1    3    0

lower.tri returns a matrix of logicals the same size of a given matrix with entries TRUE in the lower or upper triangle (R help).

Then lets

lowt <– lower.tri(Mat1)
xx <– Mat1[lowt]
xx
[1] 1 3 4 4 3 4 1 4 1 3

My question is how does Mat1[lowt] work? how do we use the function as an element by using [ ]?! what is the idea? any help please?


问:
Add current date as value to a tag in ISO 8601 format XSLT
I have an xml like below:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
</properties>
</code>```

I want to add two new tags one contain the value of current date in ISO 8601 format and another one with the date set to current date + 10 years in ISO 8601 format and transform it into a new xml file using xslt, the output xml should be like this

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
<entry key="doc:uploadDate">2017-07-04T22:18:08Z</entry>
<entry key="doc:deleteDate">2027-07-04T22:18:08Z</entry>
</properties>
</code>```

I am using the below xslt.

```<code><xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:variable name="currentDate">
        <xsl:value-of select="current-dateTime()" />
    </xsl:variable>

    <xsl:template match="entry[@key='doc:uploadDate']">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:value-of
                select="replace(normalize-space($currentDate),
        '^(\d{2})-(\d{2})-(\d{4})\s+(.*)','$3-$1-$2T$4Z')" />
        </xsl:copy>
    </xsl:template>

  <xsl:template match="@*|node()">
      <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
  </xsl:template>
</xsl:transform>
</code>```

Could someone please help me with this..

答:
Why can't you do simply:</p>

```<code><xsl:template match="/properties">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <entry key="doc:uploadDate">
            <xsl:value-of select="current-dateTime()"/>
        </entry>
        <entry key="doc:deleteDate">
            <xsl:value-of select="current-dateTime() + xs:yearMonthDuration('P10Y')"/>
        </entry>
    </xsl:copy>
</xsl:template>
</code>```

Body:
I have an xml like below:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
</properties>

I want to add two new tags one contain the value of current date in ISO 8601 format and another one with the date set to current date + 10 years in ISO 8601 format and transform it into a new xml file using xslt, the output xml should be like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<properties>
<entry key="user">1234</entry>
<entry key="doc:uploadDate">2017-07-04T22:18:08Z</entry>
<entry key="doc:deleteDate">2027-07-04T22:18:08Z</entry>
</properties>

I am using the below xslt.

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">

    <xsl:variable name="currentDate">
        <xsl:value-of select="current-dateTime()" />
    </xsl:variable>

    <xsl:template match="entry[@key='doc:uploadDate']">
        <xsl:copy>
            <xsl:apply-templates select="@*" />
            <xsl:value-of
                select="replace(normalize-space($currentDate),
        '^(\d{2})-(\d{2})-(\d{4})\s+(.*)','$3-$1-$2T$4Z')" />
        </xsl:copy>
    </xsl:template>

  <xsl:template match="@*|node()">
      <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
  </xsl:template>
</xsl:transform>

Could someone please help me with this..

Body:
Why can't you do simply:

<xsl:template match="/properties">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <entry key="doc:uploadDate">
            <xsl:value-of select="current-dateTime()"/>
        </entry>
        <entry key="doc:deleteDate">
            <xsl:value-of select="current-dateTime() + xs:yearMonthDuration('P10Y')"/>
        </entry>
    </xsl:copy>
</xsl:template>


答:
You can add a duration of ten years to the current date:</p>

```<code>    <xsl:variable name="curr-date" select="current-dateTime()"/>
    <entry>
        <xsl:value-of select="$curr-date"/>
    </entry>
    <entry>
        <xsl:value-of select="$curr-date + xs:yearMonthDuration('P10Y')"/>
    </entry>
</code>```

Title: Add current date as value to a tag in ISO 8601 format XSLT

Body:
You can add a duration of ten years to the current date:

    <xsl:variable name="curr-date" select="current-dateTime()"/>
    <entry>
        <xsl:value-of select="$curr-date"/>
    </entry>
    <entry>
        <xsl:value-of select="$curr-date + xs:yearMonthDuration('P10Y')"/>
    </entry>


问:
Give different ID to each element in for loop
I have a far loop which check the number and output the result to number of that.

For exmaple, in below picture the "cut image" is displayed in multiples times. I have  tag in the far loop so it outputs the image according to number of times. And that number come from database.

MY Question.
Obviously all the images in first row will have same ID. Currently user can only click the first image of the row. I would like to give each element different ID  if possible. Than I would like to use JQuery to add click event. So if I click on 4th image in first row, it alert message and if i click 5th image it shows different alert message.

How I can assign different ID to each element in far loop so  it does only make first Image clickable but instead all elements clickable.

My loop

```<code> <table class="table table-bordered">
    <thead>
    <tbody>
      <tr>
        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
            ?>

            <td><img alt="" class="yellow-process center-block " id ="cut-full-roll-<?php echo $row['id_vnr']; ?>" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png"></td>
        <?php
        }
        ?>

      </tr>
    </tbody>
  </table>
</code>```

My jquery selector
If I can give each element different ID, than I can do something like this to add clicked event to clicked image.

```<code>jQuery( "#vinyl-roll-down-<?php echo $row['id_vnr']; ?>" ).click(function() {
</code>```

But I need help assign different unique to each element in far loop.

Thanks in advance.

答:
I think your loop in PHP is okay like that.
The problem lies in your jquery, try getting the right id by using use attribute
selector attr("id").

```<code>jQuery( ".yellow-process" ).click(function() {
    var selected = jQuery(this).attr("id");
    alert(selected); // to show the selected image id
    // use the variable selected to do something with it.
}
</code>```

After trying this jquery code you could advance it for your use.

Body:
I have a far loop which check the number and output the result to number of that.

For exmaple, in below picture the "cut image" is displayed in multiples times. I have  tag in the far loop so it outputs the image according to number of times. And that number come from database.

MY Question.
Obviously all the images in first row will have same ID. Currently user can only click the first image of the row. I would like to give each element different ID  if possible. Than I would like to use JQuery to add click event. So if I click on 4th image in first row, it alert message and if i click 5th image it shows different alert message.

How I can assign different ID to each element in far loop so  it does only make first Image clickable but instead all elements clickable.

My loop

        <?php
        for($x=0; $x < $row['noof10s_vnr']; $x++){
            ?>

            <img alt="" class="yellow-process center-block " id ="cut-full-roll-<?php echo $row['id_vnr']; ?>" name="<?php echo $row['id_vnr']; ?>" src="../../css/icons/vinyl-rolls/cut.png">
        <?php
        }
        ?>

My jquery selector
If I can give each element different ID, than I can do something like this to add clicked event to clicked image.

jQuery( "#vinyl-roll-down-<?php echo $row['id_vnr']; ?>" ).click(function() {

But I need help assign different unique to each element in far loop.

Thanks in advance.

Body:
I think your loop in PHP is okay like that.
The problem lies in your jquery, try getting the right id by using use attribute
selector attr("id").

jQuery( ".yellow-process" ).click(function() {
    var selected = jQuery(this).attr("id");
    alert(selected); // to show the selected image id
    // use the variable selected to do something with it.
}

After trying this jquery code you could advance it for your use.


问:
why refresh html page is slow
For some reason the method display is being processed before location.reload(). Here is my syntax:

$(document).ready(function() {
  $("#refresh").click(function() {
    alert("before refresh")
    location.reload();
    display()
  })
})

function display() {
  alert("hello world")
}```
<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>
<button id="refresh">
  refersh and continue
</button></code>```

My goal here is to refresh the page when the button is clicked then call display method.
The problem is that display method is being called before the page is refreshed.
First of all, is what I am trying to achieve achievable. If not, what other ways can go take in order to solve the problem?

答:
You could try assigning your display method to the document.onload event. Try changing your click handler to:

```<code>alert('before refresh');
$(document).on('load', display);
location.reload;
</code>```

Title: why refresh html page is slow

Body:
For some reason the method display is being processed before location.reload(). Here is my syntax:

$(document).ready(function() {
  $("#refresh").click(function() {
    alert("before refresh")
    location.reload();
    display()
  })
})

function display() {
  alert("hello world")
}

<button id="refresh">
  refersh and continue
</button>

My goal here is to refresh the page when the button is clicked then call display method.
The problem is that display method is being called before the page is refreshed.
First of all, is what I am trying to achieve achievable. If not, what other ways can go take in order to solve the problem?

Body:
You could try assigning your display method to the document.onload event. Try changing your click handler to:

alert('before refresh');
$(document).on('load', display);
location.reload;


问:
Type or namespace not found, when queuing build on VSTS
I have an MVC web app on which I have added few existing project(using add existing project on VS2015), I then installed all the packages such as entity framework 6.1.3). I am then using VSTS online to queue and release builds, I have created the build definition and added all variable as expected, however when I queue the builds, I get an error that reads "The type or namespace name 'Entity' does not exist in the namespace" these errors(about 600) seems to be coming from the projects(the existing projects) that I have added to this new one.

What confuses me the most is the fact that the app seems to be working fine when running locally on my visual studio and all the packages were installed via nuget package manager.

Below is the screenshot of all the properties from the BuildSolution task

答:
Edit your build definition

Click Add Task> Select NuGet Restore task >Add (Before Visual Studio Build task)


问:
RxJs V4 Operator that combines forkJoin and map
I am trying to find an operator that lets me handle the operations performed by forkJoin and map in one step instead of two.

My input is an array of observables with varying lengths and I would like to wait until all of them have completed and then create a computed result from the observable outputs that I can subscribe to.

I haven't come across one that allows for those requirements and takes an array as input.

Below an example of a use case:

```<code>const observable1 = Rx.Observable.create(
  (observer) => {
    observer.onNext([1, 2, 3, 4]);
    observer.complete();
  }
);

const observable2 = Rx.Observable.create(
  (observer) => {
    observer.onNext([5, 6, 7, 8]);
    observer.complete();
  }
);

Rx.Observable.magigOperator([observable1, observable2])
   .subscribe(
     (result) => console.log
   );
</code>```

Now the result I am trying to get is an output of [1,2,3,4,5,6,7,8];
I can achieve it by using forkJoin and map and running a flatten function, but I was wondering whether there is a single operator that allows me to do this in one go.

Thanks.

答:
You don't have to use map, you can just pass a result selector function as a last argument of forkJoin, e.g.:

```<code>Rx.Observable.forkJoin([observable1, observable2], _.concat)
</code>```

Also note that observable1 and observable2 in your example do not complete which prevents forkJoin from emitting the result.

Body:
I am trying to find an operator that lets me handle the operations performed by forkJoin and map in one step instead of two.

My input is an array of observables with varying lengths and I would like to wait until all of them have completed and then create a computed result from the observable outputs that I can subscribe to.

I haven't come across one that allows for those requirements and takes an array as input.

Below an example of a use case:

const observable1 = Rx.Observable.create(
  (observer) => {
    observer.onNext([1, 2, 3, 4]);
    observer.complete();
  }
);

const observable2 = Rx.Observable.create(
  (observer) => {
    observer.onNext([5, 6, 7, 8]);
    observer.complete();
  }
);

Rx.Observable.magigOperator([observable1, observable2])
   .subscribe(
     (result) => console.log
   );

Now the result I am trying to get is an output of [1,2,3,4,5,6,7,8];
I can achieve it by using forkJoin and map and running a flatten function, but I was wondering whether there is a single operator that allows me to do this in one go.

Thanks.

Body:
You don't have to use map, you can just pass a result selector function as a last argument of forkJoin, e.g.:

Rx.Observable.forkJoin([observable1, observable2], _.concat)

Also note that observable1 and observable2 in your example do not complete which prevents forkJoin from emitting the result.


问:
How to get fat scroll bar on div using CSS?
If I use the CSS overflow property:

```<code>overflow: scroll;
</code>```

I get a thin scrollbar by default. How can I style it to get a fat (and flat) scrollbar?

答:
It should work for you...

/* scrollbar */
::-webkit-scrollbar {
    width: 100px;
}

/* track */
::-webkit-scrollbar-track {
    background: #f1f1f1;
    background-clip: content-box; /* it is important */
}

/* buttons */
::-webkit-scrollbar-button {
    background: black;
}

/* handle */
::-webkit-scrollbar-thumb {
    background: #c1c1c1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. </p>
<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. </p>
<p>Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. </p>
<p>Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. </p>
<p>Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. </p>
<p>Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. </p>
<p>Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. </p>
<p>Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. </p>
<p>Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. </p>
<p>In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. </p></code>```

Body:
If I use the CSS overflow property:

overflow: scroll;

I get a thin scrollbar by default. How can I style it to get a fat (and flat) scrollbar?

Body:
It should work for you...

/* scrollbar */
::-webkit-scrollbar {
    width: 100px;
}

/* track */
::-webkit-scrollbar-track {
    background: #f1f1f1;
    background-clip: content-box; /* it is important */
}

/* buttons */
::-webkit-scrollbar-button {
    background: black;
}

/* handle */
::-webkit-scrollbar-thumb {
    background: #c1c1c1;
}

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. </p>
<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. </p>
<p>Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. </p>
<p>Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. </p>
<p>Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. </p>
<p>Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. </p>
<p>Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. </p>
<p>Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. </p>
<p>Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. </p>
<p>In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. </p>


问:
How to sort file names in ascending order?
I have a set of files in a folder, and all of them starting with a similar name, except one. Here is an example:

```<code>Coordinate.txt
Spectrum_1.txt
Spectrum_2.txt
Spectrum_3.txt
.
.
.
Spectrum_11235
</code>```

I am able to list all the files from the specified folder, but the list is not in an ascending order of the spectrum number. Example: I get the following result when the program is executed:

```<code>Spectrum_999.txt
Spectrum_9990.txt
Spectrum_9991.txt
Spectrum_9992.txt
Spectrum_9993.txt
Spectrum_9994.txt
Spectrum_9995.txt
Spectrum_9996.txt
Spectrum_9997.txt
Spectrum_9998.txt
Spectrum_9999.txt
</code>```

But this order is not correct. There should be Spectrum_1000.txt file after Spectrum_999.txt. Can anyone help? Here is the code:

```<code>import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

    public class FileInput {

        public void userInput()
        {
            Scanner scanner = new Scanner( System.in );
            System.out.println("Enter the file path: ");
            String dirPath = scanner.nextLine(); // Takes the directory path as the user input

            File folder = new File(dirPath);
            if(folder.isDirectory())
            {
                File[] fileList = folder.listFiles();

                Arrays.sort(fileList);

                System.out.println("\nTotal number of items present in the directory: " + fileList.length );

                // Lists only files since we have applied file filter
                for(File file:fileList)
                {
                    System.out.println(file.getName());
                }

                // Creating a filter to return only files.
                FileFilter fileFilter = new FileFilter()
                {
                    @Override
                    public boolean accept(File file) {
                        return !file.isDirectory();
                    }
                };

                fileList = folder.listFiles(fileFilter);

                // Sort files by name
                Arrays.sort(fileList, new Comparator()
                {
                    @Override
                    public int compare(Object f1, Object f2) {
                        return ((File) f1).getName().compareTo(((File) f2).getName());
                    }
                });

                //Prints the files in file name ascending order
                for(File file:fileList)
                {
                    System.out.println(file.getName());
                }

            }
        }
    }
</code>```

答:
Just another way to do it, but using the power of java8</p>

```<code>List<Path> x = Files.list(Paths.get("C:\\myPath\\Tools"))
            .filter(p -> Files.exists(p))
            .map(s -> s.getFileName())
            .sorted()
            .collect(Collectors.toList());

x.forEach(System.out::println);
</code>```

Body:
I have a set of files in a folder, and all of them starting with a similar name, except one. Here is an example:

Coordinate.txt
Spectrum_1.txt
Spectrum_2.txt
Spectrum_3.txt
.
.
.
Spectrum_11235

I am able to list all the files from the specified folder, but the list is not in an ascending order of the spectrum number. Example: I get the following result when the program is executed:

Spectrum_999.txt
Spectrum_9990.txt
Spectrum_9991.txt
Spectrum_9992.txt
Spectrum_9993.txt
Spectrum_9994.txt
Spectrum_9995.txt
Spectrum_9996.txt
Spectrum_9997.txt
Spectrum_9998.txt
Spectrum_9999.txt

But this order is not correct. There should be Spectrum_1000.txt file after Spectrum_999.txt. Can anyone help? Here is the code:

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

    public class FileInput {

        public void userInput()
        {
            Scanner scanner = new Scanner( System.in );
            System.out.println("Enter the file path: ");
            String dirPath = scanner.nextLine(); // Takes the directory path as the user input

            File folder = new File(dirPath);
            if(folder.isDirectory())
            {
                File[] fileList = folder.listFiles();

                Arrays.sort(fileList);

                System.out.println("\nTotal number of items present in the directory: " + fileList.length );

                // Lists only files since we have applied file filter
                for(File file:fileList)
                {
                    System.out.println(file.getName());
                }

                // Creating a filter to return only files.
                FileFilter fileFilter = new FileFilter()
                {
                    @Override
                    public boolean accept(File file) {
                        return !file.isDirectory();
                    }
                };

                fileList = folder.listFiles(fileFilter);

                // Sort files by name
                Arrays.sort(fileList, new Comparator()
                {
                    @Override
                    public int compare(Object f1, Object f2) {
                        return ((File) f1).getName().compareTo(((File) f2).getName());
                    }
                });

                //Prints the files in file name ascending order
                for(File file:fileList)
                {
                    System.out.println(file.getName());
                }

            }
        }
    }

Body:
Just another way to do it, but using the power of java8

List<Path> x = Files.list(Paths.get("C:\\myPath\\Tools"))
            .filter(p -> Files.exists(p))
            .map(s -> s.getFileName())
            .sorted()
            .collect(Collectors.toList());

x.forEach(System.out::println);


问:
GitLab CI - Cache not working
I'm currently using GitLab in combination with CI runners to run unit tests of my project, to speed up the process of bootstrapping the tests I'm using the built-in cache functionality, however this doesn't seem to work.

Each time someone commits to master, my runner does a git fetch and proceeds to remove all cached files, which means I have to stare at my screen for around 10 minutes to wait for a test to complete while the runner re-downloads all dependencies (NPM and PIP being the biggest time killers).

Output of the CI runner:

```<code>Fetching changes...

Removing bower_modules/jquery/  --+-- Shouldn't happen!
Removing bower_modules/tether/    |
Removing node_modules/            |
Removing vendor/                --'
HEAD is now at 7c513dd Update .gitlab-ci.yml
</code>```

Currently my .gitlab-ci.yml

```<code>image: python:latest

services:
  - redis:latest
  - node:latest

cache:
  key: "$CI_BUILD_REF_NAME"
  untracked: true
  paths:
  - ~/.cache/pip/
  - vendor/
  - node_modules/
  - bower_components/

before_script:
  - python -V

  # Still gets executed even though node is listed as a service??
  - '(which nodejs && which npm) || (apt-get update -q && apt-get -o dir::cache::archives="vendor/apt/" install nodejs npm -yqq)'
  - npm install -g bower gulp

  # Following statements ignore cache!
  - pip install -r requirements.txt
  - npm install --only=dev
  - bower install --allow-root
  - gulp build

test:
  variables:
    DEBUG: "1"
  script:
  - python -m unittest myproject
</code>```

I've tried reading the following articles for help however none of them seem to fix my problem:

http://docs.gitlab.com/ce/ci/yaml/README.html#cache

https://fleschenberg.net/gitlab-pip-cache/

https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/issues/336

答:
Turns out that I was doing some things wrong:

Your script can't cache files outside of your project scope, creating a virtual environment instead and caching that allows you to cache your pip modules.

Most important of all: Your test must succeed in order for it to cache the files.

After using the following config I got a -3 minute time difference:

Currently my configuration looks like follows and works for me.

# Official framework image. Look for the different tagged releases at:
# https://hub.docker.com/r/library/python
image: python:latest

# Pick zero or more services to be used on all builds.
# Only needed when using a docker container to run your tests in.
# Check out: http://docs.gitlab.com/ce/ci/docker/using_docker_images.html#what-is-service
services:
- mysql:latest
- redis:latest

cache:
    untracked: true
    key: "$CI_BUILD_REF_NAME"
    paths:
    - venv/
    - node_modules/
    - bower_components/

# This is a basic example for a gem or script which doesn't use
# services such as redis or postgres
before_script:

# Check python installation
- python -V

# Install NodeJS (Gulp & Bower)
# Default repository is outdated, this is the latest version
- 'curl -sL https://deb.nodesource.com/setup_8.x | bash -'
- apt-get install -y nodejs
- npm install -g bower gulp

# Install dependencie
- pip install -U pip setuptools
- pip install virtualenv

test:

    # Indicate to the framework that it's being unit tested
    variables:
        DEBUG: "1"

    # Test script
    script:

    # Set up virtual environment
    - virtualenv venv -ppython3
    - source venv/bin/activate
    - pip install coverage
    - pip install -r requirements.txt

    # Install NodeJS & Bower + Compile JS
    - npm install --only=dev
    - bower install --allow-root
    - gulp build

    # Run all unit tests
    - coverage run -m unittest project.tests
    - coverage report -m project/**/*.py
```

<h3>Which resulted in the following output:</h3>

```Fetching changes...
Removing .coverage                              --+-- Don't worry about this
Removing bower_components/                        |
Removing node_modules/                            |
Removing venv/                                  --`
HEAD is now at 24e7618 Fix for issue #16
From https://git.example.com/repo
85f2f9b..42ba753  master     -> origin/master
Checking out 42ba7537 as master...
Skipping Git submodules setup
Checking cache for master...                    --+-- The files are back now :)
Successfully extracted cache                    --`

...

project/module/script.py                  157      9    94%   182, 231-244
---------------------------------------------------------------------------
TOTAL                                          1084    328    70%
Creating cache master...
Created cache
Uploading artifacts...
venv/: found 9859 matching files
node_modules/: found 7070 matching files
bower_components/: found 982 matching files
Trying to load /builds/repo.tmp/CI_SERVER_TLS_CA_FILE ...
Dialing: tcp git.example.com:443 ...
Uploading artifacts to coordinator... ok            id=127 responseStatus=201 Created token=XXXXXX
Job succeeded
```

<h3>For the coverage report, I used the following regular expression:</h3>

```^TOTAL\s+(?:\d+\s+){2}(\d{1,3}%)$
```

Title: GitLab CI - Cache not working

Body:
I'm currently using GitLab in combination with CI runners to run unit tests of my project, to speed up the process of bootstrapping the tests I'm using the built-in cache functionality, however this doesn't seem to work.

Each time someone commits to master, my runner does a git fetch and proceeds to remove all cached files, which means I have to stare at my screen for around 10 minutes to wait for a test to complete while the runner re-downloads all dependencies (NPM and PIP being the biggest time killers).

Output of the CI runner:

Fetching changes...

Removing bower_modules/jquery/  --+-- Shouldn't happen!
Removing bower_modules/tether/    |
Removing node_modules/            |
Removing vendor/                --'
HEAD is now at 7c513dd Update .gitlab-ci.yml

Currently my .gitlab-ci.yml

image: python:latest

services:
  - redis:latest
  - node:latest

cache:
  key: "$CI_BUILD_REF_NAME"
  untracked: true
  paths:
  - ~/.cache/pip/
  - vendor/
  - node_modules/
  - bower_components/

before_script:
  - python -V

  # Still gets executed even though node is listed as a service??
  - '(which nodejs && which npm) || (apt-get update -q && apt-get -o dir::cache::archives="vendor/apt/" install nodejs npm -yqq)'
  - npm install -g bower gulp

  # Following statements ignore cache!
  - pip install -r requirements.txt
  - npm install --only=dev
  - bower install --allow-root
  - gulp build

test:
  variables:
    DEBUG: "1"
  script:
  - python -m unittest myproject

I've tried reading the following articles for help however none of them seem to fix my problem:

http://docs.gitlab.com/ce/ci/yaml/README.html#cache

https://fleschenberg.net/gitlab-pip-cache/

https://gitlab.com/gitlab-org/gitlab-ci-multi-runner/issues/336

Body:
Turns out that I was doing some things wrong:

Your script can't cache files outside of your project scope, creating a virtual environment instead and caching that allows you to cache your pip modules.

Most important of all: Your test must succeed in order for it to cache the files.

After using the following config I got a -3 minute time difference:

Currently my configuration looks like follows and works for me.

# Official framework image. Look for the different tagged releases at:
# https://hub.docker.com/r/library/python
image: python:latest

# Pick zero or more services to be used on all builds.
# Only needed when using a docker container to run your tests in.
# Check out: http://docs.gitlab.com/ce/ci/docker/using_docker_images.html#what-is-service
services:
- mysql:latest
- redis:latest

cache:
    untracked: true
    key: "$CI_BUILD_REF_NAME"
    paths:
    - venv/
    - node_modules/
    - bower_components/

# This is a basic example for a gem or script which doesn't use
# services such as redis or postgres
before_script:

# Check python installation
- python -V

# Install NodeJS (Gulp & Bower)
# Default repository is outdated, this is the latest version
- 'curl -sL https://deb.nodesource.com/setup_8.x | bash -'
- apt-get install -y nodejs
- npm install -g bower gulp

# Install dependencie
- pip install -U pip setuptools
- pip install virtualenv

test:

    # Indicate to the framework that it's being unit tested
    variables:
        DEBUG: "1"

    # Test script
    script:

    # Set up virtual environment
    - virtualenv venv -ppython3
    - source venv/bin/activate
    - pip install coverage
    - pip install -r requirements.txt

    # Install NodeJS & Bower + Compile JS
    - npm install --only=dev
    - bower install --allow-root
    - gulp build

    # Run all unit tests
    - coverage run -m unittest project.tests
    - coverage report -m project/**/*.py

Which resulted in the following output:

Fetching changes...
Removing .coverage                              --+-- Don't worry about this
Removing bower_components/                        |
Removing node_modules/                            |
Removing venv/                                  --`
HEAD is now at 24e7618 Fix for issue #16
From https://git.example.com/repo
85f2f9b..42ba753  master     -> origin/master
Checking out 42ba7537 as master...
Skipping Git submodules setup
Checking cache for master...                    --+-- The files are back now :)
Successfully extracted cache                    --`

...

project/module/script.py                  157      9    94%   182, 231-244
---------------------------------------------------------------------------
TOTAL                                          1084    328    70%
Creating cache master...
Created cache
Uploading artifacts...
venv/: found 9859 matching files
node_modules/: found 7070 matching files
bower_components/: found 982 matching files
Trying to load /builds/repo.tmp/CI_SERVER_TLS_CA_FILE ...
Dialing: tcp git.example.com:443 ...
Uploading artifacts to coordinator... ok            id=127 responseStatus=201 Created token=XXXXXX
Job succeeded

For the coverage report, I used the following regular expression:

^TOTAL\s+(?:\d+\s+){2}(\d{1,3}%)$


问:
NameError: uninitialized constant in Rails app when testing with RSpec and Spork
I am trying to run my tests in my first Rails app using the following command in Terminal:

```<code>rspec spec/
</code>```

But it is only resulting in the following error(s):

```<code>Exception encountered: #<NameError: uninitialized constant PagesController>
backtrace:
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-expectations-2.3.0/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/monkey/spork/test_framework/rspec.rb:4:in `run_tests'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:13:in `block in run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:21:in `block in initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `fork'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `new'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/server.rb:47:in `run'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'
</code>```

I can run the site successfully in the browser, and "Spork is ready and listening", which makes me think there is a problem with the Gems I'm running, RSpec, Spork or... something? Rather than the tests I've written as the PagesController and RSpec test were based on the RailsTutorial.org book. I am at a loss.

Here's my Gemfile:

```<code>source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem "nokogiri", '1.4.4'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.3.0'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec', '2.3.0'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.9.0.rc2'
  gem 'factory_girl_rails', '1.0'
end
</code>```

Followed by my local gems list:

```<code>abstract (1.0.0)
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activeresource (3.0.3)
activesupport (3.0.3)
annotate-models (1.0.4)
arel (2.0.6)
autotest (4.3.2)
autotest-fsevent (0.2.2)
autotest-growl (0.2.4)
autotest-rails-pure (4.1.0)
builder (2.1.2)
bundler (1.0.3)
diff-lcs (1.1.2)
erubis (2.6.6)
factory_girl (1.3.2)
factory_girl_rails (1.0)
faker (0.3.1)
gravatar_image_tag (0.1.0)
i18n (0.5.0)
mail (2.2.12)
mime-types (1.16)
nokogiri (1.4.4)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.6)
rails (3.0.3)
railties (3.0.3)
rake (0.8.7)
rdoc (2.5.11)
rspec (2.3.0)
rspec-core (2.3.0)
rspec-expectations (2.3.0)
rspec-mocks (2.3.0)
rspec-rails (2.3.0)
spork (0.9.0.rc2)
sqlite3-ruby (1.2.5)
sys-uname (0.8.4)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.23)
webrat (0.7.1)
will_paginate (3.0.pre2)
</code>```

Does anyone have any ideas or can I help by providing more information? I'm a Rails novice coming back to it every now and then seem to encounter problems before giving up again...

Update My Spec/spec_helper.rb file:

```<code>require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear
  end
end

Spork.each_run do
end
</code>```

And here is the output from Terminal when the contents of spec_helper are removed:

```<code>No DRb server is running. Running in local process instead ...
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant Object::PagesController (NameError)
    from /Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:44:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:10:in `block in autorun'
</code>```

答: It turned out that the problem was caused by a bad validation rule in a different model. It took a lot of random thoughts and attempts but got there in the end without much help from the error message.</p>

Body:
I am trying to run my tests in my first Rails app using the following command in Terminal:

rspec spec/

But it is only resulting in the following error(s):

Exception encountered: #<NameError: uninitialized constant PagesController>
backtrace:
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-expectations-2.3.0/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing'
/Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/monkey/spork/test_framework/rspec.rb:4:in `run_tests'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:13:in `block in run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:21:in `block in initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `fork'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/forker.rb:18:in `initialize'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `new'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/run_strategy/forking.rb:9:in `run'
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/spork-0.9.0.rc2/lib/spork/server.rb:47:in `run'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1558:in `perform_without_block'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1518:in `perform'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1592:in `block (2 levels) in main_loop'
/Users/rich/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/drb/drb.rb:1588:in `loop'

I can run the site successfully in the browser, and "Spork is ready and listening", which makes me think there is a problem with the Gems I'm running, RSpec, Spork or... something? Rather than the tests I've written as the PagesController and RSpec test were based on the RailsTutorial.org book. I am at a loss.

Here's my Gemfile:

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem "nokogiri", '1.4.4'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.3.0'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec', '2.3.0'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.9.0.rc2'
  gem 'factory_girl_rails', '1.0'
end

Followed by my local gems list:

abstract (1.0.0)
actionmailer (3.0.3)
actionpack (3.0.3)
activemodel (3.0.3)
activerecord (3.0.3)
activeresource (3.0.3)
activesupport (3.0.3)
annotate-models (1.0.4)
arel (2.0.6)
autotest (4.3.2)
autotest-fsevent (0.2.2)
autotest-growl (0.2.4)
autotest-rails-pure (4.1.0)
builder (2.1.2)
bundler (1.0.3)
diff-lcs (1.1.2)
erubis (2.6.6)
factory_girl (1.3.2)
factory_girl_rails (1.0)
faker (0.3.1)
gravatar_image_tag (0.1.0)
i18n (0.5.0)
mail (2.2.12)
mime-types (1.16)
nokogiri (1.4.4)
polyglot (0.3.1)
rack (1.2.1)
rack-mount (0.6.13)
rack-test (0.5.6)
rails (3.0.3)
railties (3.0.3)
rake (0.8.7)
rdoc (2.5.11)
rspec (2.3.0)
rspec-core (2.3.0)
rspec-expectations (2.3.0)
rspec-mocks (2.3.0)
rspec-rails (2.3.0)
spork (0.9.0.rc2)
sqlite3-ruby (1.2.5)
sys-uname (0.8.4)
thor (0.14.6)
treetop (1.4.9)
tzinfo (0.3.23)
webrat (0.7.1)
will_paginate (3.0.pre2)

Does anyone have any ideas or can I help by providing more information? I'm a Rails novice coming back to it every now and then seem to encounter problems before giving up again...

Update My Spec/spec_helper.rb file:

require 'rubygems'
require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  unless defined?(Rails)
    require File.dirname(__FILE__) + "/../config/environment"
  end
  require 'rspec/rails'

  # Requires supporting files with custom matchers and macros, etc,
  # in ./support/ and its subdirectories.
  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

  Rspec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, comment the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true

    ### Part of a Spork hack. See http://bit.ly/arY19y
    # Emulate initializer set_clear_dependencies_hook in
    # railties/lib/rails/application/bootstrap.rb
    ActiveSupport::Dependencies.clear
  end
end

Spork.each_run do
end

And here is the output from Terminal when the contents of spec_helper are removed:

No DRb server is running. Running in local process instead ...
/Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/backward_compatibility.rb:20:in `const_missing': uninitialized constant Object::PagesController (NameError)
    from /Users/rich/dev/rails_projects/abunchofletters/spec/controllers/pages_controller_spec.rb:3:in `<top (required)>'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `block in load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `map'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/configuration.rb:388:in `load_spec_files'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/command_line.rb:18:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:55:in `run_in_process'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:44:in `run'
    from /Users/rich/.rvm/gems/ruby-1.9.2-p0@abunchofletters/gems/rspec-core-2.3.0/lib/rspec/core/runner.rb:10:in `block in autorun'


问:
I want to handle message when notification received with app not running
In Android APP, I have already use FCM to receive Cloud Message, when the app is foreground , the MyFirebaseMessageService.java (I defined) runned. However when the app is background or not running ,The MyFirebaseMessageService.java doesn't run, I can also receive notification, when I click the notification, Where can I get the cloud message?

答:
Send your push as data and not as notification, and it will be received always in MyFirebaseMessageService onMessageReceived.

https://firebase.google.com/docs/cloud-messaging/concept-options


问:
How to remove all but the last 3 parts of FQDN?
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

```<code>$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1
</code>```

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

答:
```<code>echo $string | awk -F. '{ if (NF == 2) { print $0 } else { print $(NF-2)"."$(NF-1)"."$NF } }'
</code>```

NF signifies the total number of field separated by "." and so we want the last piece (NF), last but 1 (NF-1) and last but 2 (NF-2)

Body:
I have a list of IP lookups and I wish to remove all but the last 3 parts, so:
98.254.237.114.broad.lyg.js.dynamic.163data.com.cn
would become
163data.com.cn

I have spent hours searching for clues, including parameter substitution, but the closest I got was:

$ string="98.254.237.114.broad.lyg.js.dynamic.163data.com.cn"
$ string1=${string%.*.*.*}
$ echo $string1

Which gives me the inverted answer of:
98.254.237.114.broad.lyg.js.dynamic
which is everything but the last 3 parts.

A script to do a list would be better than just the static example I have here.
Using CentOS 6, I don't mind if it by using sed, cut, awk, whatever.
Any help appreciated.

Thanks, now that I have working answers, may I ask as a follow up to then process the resulting list and if the last part (after last '.') is 3 characters - eg .com .net etc, then to just keep the last 2 parts.

If this is against protocol, please advise how to do a follow up question.

Body:
echo $string | awk -F. '{ if (NF == 2) { print $0 } else { print $(NF-2)"."$(NF-1)"."$NF } }'

NF signifies the total number of field separated by "." and so we want the last piece (NF), last but 1 (NF-1) and last but 2 (NF-2)