问:
restsharp PUT request error --> "StatusCode: InternalServerError, Content-Type: application/json, Content-Length: -1)"
I want to do a PUT request via a REST API. I've got the access_token, which should be correct. I'm trying to upload a JSON object of relation, but I get the following error:

restsharp PUT request error:

“StatusCode: InternalServerError, Content-Type: application/json,
  Content-Length: -1)”

```<code>public void Store(HiveClient hiveClient,string _putUrl, string _url, string _clientId, string _clientSecret, HiveObject objToStore)
{
    hiveClient = new HiveClient(_url, _clientId, _clientSecret);
    hiveClient.CheckIfFileExists();
    string token = hiveClient.restToken;
    HiveObject hiveObject = objToStore;
    var json = JsonConvert.SerializeObject(hiveObject);
    RestClient restClient = new RestClient(_putUrl);
    RestRequest request = new RestRequest(Method.PUT);
    request.AddHeader("Authorization", token);
    request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
    request.AddJsonBody(json);
    request.RequestFormat = DataFormat.Json;
    IRestResponse respons = restClient.Execute<HiveObject>(request);
    var deserialize = new JsonDeserializer();
    var output = deserialize.Deserialize<Dictionary<string, string>>(respons);
}
</code>```

答:
I suggest reading the docs, really.</p>

```<code>public void Store(string _putUrl, string _url, string _clientId, string _clientSecret, HiveObject objToStore)
{
    var hiveClient = new HiveClient(_url, _clientId, _clientSecret);
    hiveClient.CheckIfFileExists();
    string token = hiveClient.restToken;

    var restClient = new RestClient(_putUrl);
    var request = new RestRequest()
        .AddHeader("Authorization", token)
        .AddJsonBody(objToStore);

    var result = restClient.Put<Dictionary<string, string>>(request);
}
</code>```

Body:
I want to do a PUT request via a REST API. I've got the access_token, which should be correct. I'm trying to upload a JSON object of relation, but I get the following error:

restsharp PUT request error:

“StatusCode: InternalServerError, Content-Type: application/json,
  Content-Length: -1)”

public void Store(HiveClient hiveClient,string _putUrl, string _url, string _clientId, string _clientSecret, HiveObject objToStore)
{
    hiveClient = new HiveClient(_url, _clientId, _clientSecret);
    hiveClient.CheckIfFileExists();
    string token = hiveClient.restToken;
    HiveObject hiveObject = objToStore;
    var json = JsonConvert.SerializeObject(hiveObject);
    RestClient restClient = new RestClient(_putUrl);
    RestRequest request = new RestRequest(Method.PUT);
    request.AddHeader("Authorization", token);
    request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
    request.AddJsonBody(json);
    request.RequestFormat = DataFormat.Json;
    IRestResponse respons = restClient.Execute<HiveObject>(request);
    var deserialize = new JsonDeserializer();
    var output = deserialize.Deserialize<Dictionary<string, string>>(respons);
}

Body:
I suggest reading the docs, really.

public void Store(string _putUrl, string _url, string _clientId, string _clientSecret, HiveObject objToStore)
{
    var hiveClient = new HiveClient(_url, _clientId, _clientSecret);
    hiveClient.CheckIfFileExists();
    string token = hiveClient.restToken;

    var restClient = new RestClient(_putUrl);
    var request = new RestRequest()
        .AddHeader("Authorization", token)
        .AddJsonBody(objToStore);

    var result = restClient.Put<Dictionary<string, string>>(request);
}


来源: stackexchange

问:
How to download the latest artifact from Artifactory repository?
I need the latest artifact (for example, a snapshot) from a repository in Artifactory. This artifact needs to be copied to a server (Linux) via a script.

What are my options? Something like Wget / SCP? And how do I get the path of the artifact?

I found some solutions which require Artifactory Pro. But I just have Artifactory, not Artifactory Pro.

Is it possible at all to download from Artifactory without the UI and not having the Pro-Version? What is the experience?

I'm on OpenSUSE 12.1 (x86_64) if that matters.

答:
In case you need to download an artifact in a Dockerfile, instead of using wget or curl or the likes you can simply use the 'ADD' directive:

ADD ${ARTIFACT_URL} /opt/app/app.jar

Of course, the tricky part is determining the ARTIFACT_URL, but there's enough about that in all the other answers.

However, Docker best practises strongly discourage using ADD for this purpose and recommend using wget or curl.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Python math calculation proportional
I'm trying to do a proportional calculation in Python. I am just at the point where I have to recognize the values as proportional or not proportional before I can calculate

As a typical default a text.

20 workers need 15 days with 8 hours each to paint the apartment.
How many hours per day would 24 workers have to work if the job is to be completed in 12 days.

Logically, I would proceed as follows

```<code>Worker      Days
20          15       8 hours
24          12
</code>```

In this case, both values are not proportional, as less becomes more. Or more to less.

How can I combine this detection whether proportional or disproportional in one formula?

In example, I have some num values

```<code>Num_worker_1 = 20
Num_worker_2 = 24
Num_days_1 = 15
Num_days_2 = 12
Num_hours_1 = 8
Num_hours_2 = ??
</code>```

答:
I provide first a trivial approach to the problem where I assume that each worker have the same efficiency and the same capacity to work. Lastly, I provide you library that you could use to formulate the problem as Linear Programming task (LP) and then solve with it.

Proportionally each worker having the same total amount of work in hours and efficiency

You need 2400 man hours to complete the work

```<code>>>> 20*8*15
2400
</code>```

so for 24 workers, you have

```<code>2400 = 24 * D
</code>```

where D is work per day so D = 2400.0/24

```<code>>>> 2400.0/24
100
</code>```

so each man has to work 100 hours during the 12 days.

How is it if workers have different capacity to work?

It means more constraints which you solve as a linear optimisation problem (LP). I suggest you to look at Python package such as CVXPY for convex optimisation here.

Title: Python math calculation proportional

Body:
I'm trying to do a proportional calculation in Python. I am just at the point where I have to recognize the values as proportional or not proportional before I can calculate

As a typical default a text.

20 workers need 15 days with 8 hours each to paint the apartment.
How many hours per day would 24 workers have to work if the job is to be completed in 12 days.

Logically, I would proceed as follows

Worker      Days
20          15       8 hours
24          12

In this case, both values are not proportional, as less becomes more. Or more to less.

How can I combine this detection whether proportional or disproportional in one formula?

In example, I have some num values

Num_worker_1 = 20
Num_worker_2 = 24
Num_days_1 = 15
Num_days_2 = 12
Num_hours_1 = 8
Num_hours_2 = ??

Body:
I provide first a trivial approach to the problem where I assume that each worker have the same efficiency and the same capacity to work. Lastly, I provide you library that you could use to formulate the problem as Linear Programming task (LP) and then solve with it.

Proportionally each worker having the same total amount of work in hours and efficiency

You need 2400 man hours to complete the work

>>> 20*8*15
2400

so for 24 workers, you have

2400 = 24 * D

where D is work per day so D = 2400.0/24

>>> 2400.0/24
100

so each man has to work 100 hours during the 12 days.

How is it if workers have different capacity to work?

It means more constraints which you solve as a linear optimisation problem (LP). I suggest you to look at Python package such as CVXPY for convex optimisation here.


问:
Bootstrap 4 Safari Images and text overlap
The image and the text of the columns overlap.
Maybe the height of the image is wrong or the image does not resize well.

This happens in safari browser on small screens with bootstrap 4.

I tried different solutions for the Bootstrap 4 Safari on Mac Grid issue but it does not help to solve the problem.

Example:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</script>

My Awsome - Tutorial

Welcome

      Welcome to the esatus Wallet - Tutorial.

      If you haven't installed the app allready you can donwload the App now for
      iPhone or
      Android.

      The tutorial has the follwoing topics.

here some text

here some text

here some text

here some text

here some text

here some text

     <button href="#" type="button" class="invisible btn btn-primary m-auto invisible" >INVISBLE</button>
     <button href="#" type="button" class="btn btn-primary m-auto" onclick="return show('Step1','Step0');">Next</button>

```

答:
You just have to use the class justify-content-center in the parent element of the image.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</script>

My Awsome - Tutorial

Welcome

      Welcome to the esatus Wallet - Tutorial.

      If you haven't installed the app allready you can donwload the App now for
      iPhone or
      Android.

      The tutorial has the follwoing topics.

here some text

here some text

here some text

here some text

here some text

here some text

     <button href="#" type="button" class="invisible btn btn-primary m-auto invisible" >INVISBLE</button>
     <button href="#" type="button" class="btn btn-primary m-auto" onclick="return show('Step1','Step0');">Next</button>

```

Body:
You just have to use the class justify-content-center in the parent element of the image.

<html>
<head>
<!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</script>
</head>
<body>
 <div id="Step0" style="margin-left:auto; margin-right:auto;" >
  <div class="container-fluid d-flex flex-column h-100 justify-content-between">
   <div class="row mt-5">
    <div class="col-12">
     <h1 class="text-center">My Awsome - Tutorial</h1>
    </div>
    <div class="col-12 mt-4">
     <h3 class="text-center">Welcome</h3>
    </div>
   </div>
   <div class="row">
    <div class="col-12">
     <p class="mx-5 text-center">
      Welcome to the esatus Wallet - Tutorial.
      <br>
      If you haven't installed the app allready you can donwload the App now for
      iPhone or
      Android.
      <br><br>
      The tutorial has the follwoing topics.
     </p>
    </div>
    <div class="col-12 d-flex">
     <div class="mx-auto">
      <ul>
       <li>here some text</li>
       <li>here some text</li>
       <li>here some text</li>
       <li>here some text</li>
       <li>here some text</li>
       <li>here some text</li>
      </ul>
     </div>
    </div>
    <div class="col-12 d-flex justify-content-center">
     <img src="https://www1-lw.xda-cdn.com/files/2017/05/stack-overflow.png" class="mx-auto img-fluid">
    </div>
   </div>
   <div class="row justify-content-end mb-5">
    <div class="col-12 d-flex">
     <button href="#" type="button" class="invisible btn btn-primary m-auto invisible" >INVISBLE</button>
     <button href="#" type="button" class="btn btn-primary m-auto" onclick="return show('Step1','Step0');">Next</button>
    </div>
   </div>
  </div>
 </div>
</body>
</html>


问:
Avoid circular reference when creating a "plug"
I have a Walk/Bridge between a beginning balance (BB) and an ending balance (EB):
E.g.

```<code>------------
BB            $100     no formula
+             $ 30     no formula
-             $(50)    no formula
Adjustment    $  x     if confirmed ending balance (CEB) = 0 then x = 0; when confirmed balance <> 0 then x = CEB - EB
EB            $ 80     Sum(of above)
------------
CEB           $ 50     no formula
</code>```

When I get a confirmed ending balance I would like to "plug" the value automatically that will cause the ending balance to = the confirmed ending balance; I am stuck as this is causing me circular references.

Is there a formula that could act as a work around or an adjustment to my logic that would meet this requirement?

in the case where the CEB <> 0 the Adjustment value (x) = ($30) in which case the EB = CEB

(if possible I would like to avoid solver-addin)

答:
The adjustment =CEB - SUM(BB, Plus, Minus)

or using your numbers =50-SUM(100,30,-50)

Then EB = SUM (BB, Plus,minus,adjustment)

Body:
I have a Walk/Bridge between a beginning balance (BB) and an ending balance (EB):
E.g.

------------
BB            $100     no formula
+             $ 30     no formula
-             $(50)    no formula
Adjustment    $  x     if confirmed ending balance (CEB) = 0 then x = 0; when confirmed balance <> 0 then x = CEB - EB
EB            $ 80     Sum(of above)
------------
CEB           $ 50     no formula

When I get a confirmed ending balance I would like to "plug" the value automatically that will cause the ending balance to = the confirmed ending balance; I am stuck as this is causing me circular references.

Is there a formula that could act as a work around or an adjustment to my logic that would meet this requirement?

in the case where the CEB <> 0 the Adjustment value (x) = ($30) in which case the EB = CEB

(if possible I would like to avoid solver-addin)


问:
python: subsetting and renaming columns by name in list of dataframes
I have a list of dataframes, all with the same columns.  I wish to first select a subset of the columns and then rename the columns.

I have a list of columns on which to subset

```<code>rename_cols_list = ['Portfolio', 'CalendarYear', 'Count']
</code>```

and apply a dictionary to change the column names:

```<code>rename_cols_dict = {'Portfolio': 'Index',
                    'CalendarYear': 'Year',
                    'Count': 'Constituents'}
</code>```

This works as expected when when applied to a single data frame in the list:

```<code>cdx_analysis = cdx_analysis[rename_cols_list].rename(rename_cols_dict,
                                                     axis='columns')
</code>```

But fails, i.e. no columns are subset and no changes are made, when I loop through a list of dataframes:

```<code>base_df = [cdx_analysis, cdx_ex_commod_analysis, cdx_commod_analysis,
           itraxx_all_analysis, itraxx_nonfins_analysis, itraxx_fins_analysis]

for df in base_df:
    df = df[rename_cols_list].rename(rename_cols_dict, axis='columns')
</code>```

Thanks

答:
You are juut resetting the loop variable in your loop to a new dataframe, not actually updating the list (think references/pointers). The easiest solution is to use the inplace flag:

```<code>for df in base_df:
    df[rename_cols_list].rename(rename_cols_dict, axis='columns', inplace=True)
</code>```

Body:
I have a list of dataframes, all with the same columns.  I wish to first select a subset of the columns and then rename the columns.

I have a list of columns on which to subset

rename_cols_list = ['Portfolio', 'CalendarYear', 'Count']

and apply a dictionary to change the column names:

rename_cols_dict = {'Portfolio': 'Index',
                    'CalendarYear': 'Year',
                    'Count': 'Constituents'}

This works as expected when when applied to a single data frame in the list:

cdx_analysis = cdx_analysis[rename_cols_list].rename(rename_cols_dict,
                                                     axis='columns')

But fails, i.e. no columns are subset and no changes are made, when I loop through a list of dataframes:

base_df = [cdx_analysis, cdx_ex_commod_analysis, cdx_commod_analysis,
           itraxx_all_analysis, itraxx_nonfins_analysis, itraxx_fins_analysis]

for df in base_df:
    df = df[rename_cols_list].rename(rename_cols_dict, axis='columns')

Thanks

Body:
You are juut resetting the loop variable in your loop to a new dataframe, not actually updating the list (think references/pointers). The easiest solution is to use the inplace flag:

for df in base_df:
    df[rename_cols_list].rename(rename_cols_dict, axis='columns', inplace=True)


问:
Dropdown menu positioning and styling
How do I make it so that the hover effects are full width of the dropdown and so that the text changes  colour on hovering on the li not the a.

So it should be a black dropdown menu, when each link is hovered on the background of the li should change to rgba(255,255,255, 0.1) and the text should change to rgba(102,245,66, 0.8) the li and a sections shouldn't overflow the normal dropdown section (I tried overflow: hidden)

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #1c1c1c;
  min-width: 240px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 12px 16px;
  z-index: 1;
  height: 300px;
  position: absolute;
  right: 0;
  top: 100;
}

ul {
  list-style: none;
  overflow: hidden;
}

li {
  font-size: 1em;
  text-align: center;
  padding-top: .5em;
  height: 75px;
  width: 240px;
  overflow: hidden;
}

a {
  color: #fff;
  text-decoration: none;
  font-size: 2rem;
  font-family: $main-font;
  width: 240px;
}

a:hover {
  color: rgba(102, 245, 66, 0.8);
}

li:hover {
  background: rgba(255, 255, 255, .2);
  color: #8FC3A1;
  width: 240px;
  cursor: pointer;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown">
  <span><i class="fa fa-bars">Just hover on it</i></span>
  <div class="dropdown-content">
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Line Up</li>
      <li>Contact</li>
    </ul>
  </div>
</div></code>```

答:
I think you are looking for this i m not pretty much sure, please do let me know if it fulfills you requirement, the solution is change color of a when we hover li

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #1c1c1c;
  min-width: 240px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 0;
  z-index: 1;
  height: 300px;
  position: absolute;
  right: 0;
      left: 0;
}

ul {
  list-style: none;
  overflow: hidden;
  margin: 0;
    padding: 0;
}

li {
    font-size: 1em;
    text-align: center;
    margin-bottom: 10px;
}

li:hover {
  background: rgba(255,255,255, 0.1);
  color: #8FC3A1;
  cursor: pointer;
}
li:hover a{
  color: rgba(102,245,66, 0.8)
}

a {
  color: #fff;
  text-decoration: none;
  font-size: 2rem;
  font-family: $main-font;
  width: 240px;
}
.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown">
  <span><i class="fa fa-bars">fa-bar dropdown</i></span>
  <div class="dropdown-content">
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Line Up</li>
      <li>Contact</li>
    </ul>
  </div>
</div></code>```

Title: Dropdown menu positioning and styling

Body:
How do I make it so that the hover effects are full width of the dropdown and so that the text changes  colour on hovering on the li not the a.

So it should be a black dropdown menu, when each link is hovered on the background of the li should change to rgba(255,255,255, 0.1) and the text should change to rgba(102,245,66, 0.8) the li and a sections shouldn't overflow the normal dropdown section (I tried overflow: hidden)

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #1c1c1c;
  min-width: 240px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 12px 16px;
  z-index: 1;
  height: 300px;
  position: absolute;
  right: 0;
  top: 100;
}

ul {
  list-style: none;
  overflow: hidden;
}

li {
  font-size: 1em;
  text-align: center;
  padding-top: .5em;
  height: 75px;
  width: 240px;
  overflow: hidden;
}

a {
  color: #fff;
  text-decoration: none;
  font-size: 2rem;
  font-family: $main-font;
  width: 240px;
}

a:hover {
  color: rgba(102, 245, 66, 0.8);
}

li:hover {
  background: rgba(255, 255, 255, .2);
  color: #8FC3A1;
  width: 240px;
  cursor: pointer;
}

.dropdown:hover .dropdown-content {
  display: block;
}

  Just hover on it

Home

About

Line Up

Contact

Body:
I think you are looking for this i m not pretty much sure, please do let me know if it fulfills you requirement, the solution is change color of a when we hover li

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #1c1c1c;
  min-width: 240px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 0;
  z-index: 1;
  height: 300px;
  position: absolute;
  right: 0;
      left: 0;
}

ul {
  list-style: none;
  overflow: hidden;
  margin: 0;
    padding: 0;
}

li {
    font-size: 1em;
    text-align: center;
    margin-bottom: 10px;
}

li:hover {
  background: rgba(255,255,255, 0.1);
  color: #8FC3A1;
  cursor: pointer;
}
li:hover a{
  color: rgba(102,245,66, 0.8)
}

a {
  color: #fff;
  text-decoration: none;
  font-size: 2rem;
  font-family: $main-font;
  width: 240px;
}
.dropdown:hover .dropdown-content {
  display: block;
}

<div class="dropdown">
  <span><i class="fa fa-bars">fa-bar dropdown</i></span>
  <div class="dropdown-content">
    <ul>
      <li><a href="#home">Home</a></li>
      <li><a href="#about">About</a></li>
      <li><a href="#lin">Line Up</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
  </div>
</div>


问:
How to remove class name of li in angular 8
Tried to remove classname of all li but not working.I do not know how to do that in angular 8.If anyone know please help to find solution.

app.component.html:

```<code><tr>
<div class="wrapper">
  <ul>
    <li class="name"><span>Test 1</span></li>
    <li class="name"><span>Test 2</span></li>
    <li class="name"><span>Test 3</span></li>
    <li class="name"><span>Test 4</span></li>
    <li class="name"><span>Test 5</span></li>
  </ul>
</div>
</tr>
</code>```

app.component.ts:

```<code> setInnertext(event){
    let getTr=event.target.closest('tr');
    this.renderer.removeClass(getTr.querySelector('.wrapper > ul > li'),'name'))
  }
</code>```

答:
I had similar situation when we needed trigger dynamically added class on click. For your case first target the closest tr and then iterate via querySelectorAll through its children li.

app.component.ts

```<code>    setInnertext($event: any) {
        $event.target.closest("ul").querySelectorAll("li").forEach(item => {
            this.renderer.removeClass(item, "name");
        });
    }
</code>```

Hope it helps.

Body:
Tried to remove classname of all li but not working.I do not know how to do that in angular 8.If anyone know please help to find solution.

app.component.html:

Test 1

Test 2

Test 3

Test 4

Test 5

app.component.ts:

 setInnertext(event){
    let getTr=event.target.closest('tr');
    this.renderer.removeClass(getTr.querySelector('.wrapper > ul > li'),'name'))
  }

Body:
I had similar situation when we needed trigger dynamically added class on click. For your case first target the closest tr and then iterate via querySelectorAll through its children li.

app.component.ts

    setInnertext($event: any) {
        $event.target.closest("ul").querySelectorAll("li").forEach(item => {
            this.renderer.removeClass(item, "name");
        });
    }

Hope it helps.


问:
Hello in Xamarin For Display Alert message I have used Acr.UserDialog .there is any soluction for change font size of title in case of uwp
await UserDialogs.Instance.AlertAsync(new AlertConfig
            {</p>

```<code>           Title="bhjgjh",
            Message = "hgfhg",
            OkText = "Ok"
        });
</code>```

答:
"The library wasn't really designed or meant for this. It was meant for using native dialogs. That's it. If you need something more customizable, this is not the library for it." - this text is copied from github repo "https://github.com/aritchie/userdialogs".

So if you want to make your own custom dialog then try this
https://github.com/rotorgames/Rg.Plugins.Popup

or this
https://github.com/michaeled/FormsPopup

Body:
await UserDialogs.Instance.AlertAsync(new AlertConfig
            {

           Title="bhjgjh",
            Message = "hgfhg",
            OkText = "Ok"
        });


问:
ChromeDriver v80 doesn't work even though Chrome version is matched (Chrome v80)
chromedriver.exe file is in the folder it works.

the version is 80.0.3987.116. also the chrome's version is 80.0.3987.116.

```<code>driver = webdriver.Chrome()
</code>```

this doesn't work. with that error message.

```<code>WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist
</code>```

I thought this error is because of updating chrome hours ago

Then I changed my code with chromeoptions

```<code>chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument("--remote-debugging-port=9222")
driver = webdriver.Chrome('chromedriver', options= chrome_options)
</code>```

also doesn't work with another error.

```<code>SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80
</code>```

The version is matched with chrome version.

I tried installing a different version of chromedriver and got the same error.

```<code>SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 79
</code>```

how can i fix it?

答:
This error message...

```<code>SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80
</code>```

...implies that the ChromeDriver v80 was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser where is version is other then 80.0.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You mentioned about using chromedriver=80 and chrome=80 but somehow while your program execution ChromeDriver other then v80 is being invoked.

So, it's quite evident your have other versions of ChromeDriver other then chromedriver=81.0 present within your system and is present within the system PATH variable which gets invoked while you:

```<code>driver = webdriver.Chrome()
</code>```

Solution

The easiest solution will be to override the default chromedriver binary location with chromedriver v80.0 binary location as follows:

```<code>from selenium import webdriver

driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
driver.get('http://google.com/')
</code>```

Reference

You can find a couple of relevant discussions in:

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

Ubuntu: selenium.common.exceptions: session not created: This version of ChromeDriver only supports Chrome version 79

Body:
chromedriver.exe file is in the folder it works.

the version is 80.0.3987.116. also the chrome's version is 80.0.3987.116.

driver = webdriver.Chrome()

this doesn't work. with that error message.

WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist

I thought this error is because of updating chrome hours ago

Then I changed my code with chromeoptions

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument("--remote-debugging-port=9222")
driver = webdriver.Chrome('chromedriver', options= chrome_options)

also doesn't work with another error.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

The version is matched with chrome version.

I tried installing a different version of chromedriver and got the same error.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 79

how can i fix it?

Body:
This error message...

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

...implies that the ChromeDriver v80 was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser where is version is other then 80.0.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You mentioned about using chromedriver=80 and chrome=80 but somehow while your program execution ChromeDriver other then v80 is being invoked.

So, it's quite evident your have other versions of ChromeDriver other then chromedriver=81.0 present within your system and is present within the system PATH variable which gets invoked while you:

driver = webdriver.Chrome()

Solution

The easiest solution will be to override the default chromedriver binary location with chromedriver v80.0 binary location as follows:

from selenium import webdriver

driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
driver.get('http://google.com/')

Reference

You can find a couple of relevant discussions in:

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 80

Ubuntu: selenium.common.exceptions: session not created: This version of ChromeDriver only supports Chrome version 79


问:
Rails for Zombies Level 5 Challenge 5
The problem statement is
Create a named route. It should generate a path like '/zombies/:name' where :name is a parameter, and points to the index action in ZombiesController. Name the route 'graveyard'

the resources are
Resources

```<code>zombies
id  name    graveyard
1   Ash     Glen Haven Memorial Cemetary
2   Bob     Chapel Hill Cemetary
3   Jim     My Fathers Basement
</code>```

my solution is

```<code>TwitterForZombies::Application.routes.draw do
  match ':name' => 'Zombies#index', :as => 'graveyard'
end
</code>```

i also tried

```<code>TwitterForZombies::Application.routes.draw do
      match ':name' => 'Zombie#index', :as => 'graveyard'
    end
</code>```

the error that i get in both cases is

```<code>Sorry, Try Again
Did not route to ZombiesController index action with :name parameter
</code>```

What am i doing wrong??

答:
Try this:

match '/zombies/:name',:to=> 'zombies#index', :as => 'graveyard'

RailsForZombies::Application.routes.draw do
    resources :zombie
    match '/zombies/:name',:to=> 'Zombies#index', :as => 'graveyard'
end
```

Title: Rails for Zombies Level 5 Challenge 5

Body:
The problem statement is
Create a named route. It should generate a path like '/zombies/:name' where :name is a parameter, and points to the index action in ZombiesController. Name the route 'graveyard'

the resources are
Resources

zombies
id  name    graveyard
1   Ash     Glen Haven Memorial Cemetary
2   Bob     Chapel Hill Cemetary
3   Jim     My Fathers Basement

my solution is

TwitterForZombies::Application.routes.draw do
  match ':name' => 'Zombies#index', :as => 'graveyard'
end

i also tried

TwitterForZombies::Application.routes.draw do
      match ':name' => 'Zombie#index', :as => 'graveyard'
    end

the error that i get in both cases is

Sorry, Try Again
Did not route to ZombiesController index action with :name parameter

What am i doing wrong??


问:
Set Search Filter Panel to Always Display
I am working on editing search functionality for a knowledge base. The knowledge base has a filter panel that can be displayed where users can select which database or category they want to use to filter search results. Currently it is set to "hidden" until the link/icon is clicked on for it. I would like to make it always visible if possible. Below I have the script file, css file, and html for the search and filter section. I would like for the show/hide link/icon to still work. I just want the default to be that the filter pane is shown.

//Link function
function(scope,element,attr){
 if(scope.data.set_foccus)
 setTimeout(function(){
  element.find('#kb_search_input').focus();
 },0);

 var c = scope.c;
 $rootScope = $injector.get("$rootScope");

 c.showFiltersButton = true;

 c.showAndHideFilters = function(){
  if(c.showFiltersButton==true){
   $(".hide-filters").addClass("show-filters").removeClass("hide-filters");
   $(".expand-width").addClass("original-width").removeClass("expand-width");
   c.showFiltersButton = false;
  }else{
   $(".show-filters").addClass("hide-filters").removeClass("show-filters");
   $(".original-width").addClass("expand-width").removeClass("original-width");
   c.showFiltersButton = true;
  }
 }

 c.hideFilters = function(){
   $(".show-filters").addClass("hide-filters").removeClass("show-filters");
  $(".original-width").addClass("expand-width").removeClass("original-width");
  c.showFiltersButton = true;
 }

 c.toggleFacets = function(){
  $rootScope.showFacet = !$rootScope.showFacet;
  $rootScope.showLanguageFacet = false;
 }

 c.showLanguageFacet = function(){
  $rootScope.showFacet = !$rootScope.showFacet;
  $rootScope.showLanguageFacet = true;
 }

 c.keywordChanged = function(event){
  c.keyword = c.keyword.trim();

  if(c.keyword != c.oldKeyword){
   //handle keyboard events for enter and keyup
   if(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(!c.data.allow_instant_search && keycode != 13)
     return;
   }

   //throw update event based on options
   if( (c.data.allow_empty_search && c.keyword == "") || (c.keyword && c.keyword.length >= c.data.min_search_char)){
    $rootScope.$emit('sp.kb.updated.keyword',{'keyword':c.keyword});
    c.hideFilters();
   }

   c.oldKeyword = angular.copy(c.keyword);
  }

  scope.$evalAsync(function(){
   if($("#kb_search_input"))
    $("#kb_search_input").focus();
  });
 };

 //If instant search enable then wait for 200ms for the next input then throw event
 $("#kb_search_input").keyup(_.debounce(function(event){
  c.keywordChanged(event);
 },c.options.search_wait));

 $(window).resize(function() {
  var width1 = $(window).width();
  if(width1<=992 && !$rootScope.isMobile){
   $rootScope.isMobile = true;
  }else if(width1>992 && $rootScope.isMobile ){
   $rootScope.showFacet = false;
   $rootScope.isMobile = false;
  }
 });

 //set keyword onload from url and throw event
 if(c.data.keyword){
  c.keyword = c.data.keyword;
  c.keywordChanged();
 }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media only screen and (max-width: 991px) {
    .kb-search-block {
      padding-top : 7px !important;
    }
    .filter-icon-padding {
      padding-left : 0px !important;
      padding-right : 0px !important;
      text-align : center;
    }
    .kb-search-display-none {
      display :none !important;
    }
    .kb-search-block .lang-icon {
      font-size : 18px;
      float :left;
      padding-right:9px;
    }
  }
   @media only screen and (min-width:991px) {
   .expand-width {
     width :100%;
    }
    .hide-filters {
     display :none;
    }
    .original-width{
     width : 75%;
    }
    .show-filters {
     display:block;
    }
 }</code>```

        <input id="kb_search_input" name="q" type="text" ng-model="c.keyword" aria-label="{{::options.title}}"  placeholder="{{::options.title}}" class="form-control">

          <button name="search" type="submit" aria-label="search" class="btn btn-{{::c.options.color}}" ng-click="c.keywordChanged('')">

          </button>

    ${Show filters}
    ${Hide filters}

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//client script
function($rootScope,$window,$timeout,KnowledgeSearchService,$scope) {
 var c = this;

 c.keyword = c.data.keyword || "";
 c.oldKeyword = c.data.keyword || "";
 c.options.glyph = c.options.glyph || 'search';
 c.filterCount =0;
 c.applycolor =false;
 c.items =[];
 c.showLanguageIcon = false;
 if($rootScope.showLanguageIcon){
  c.showLanguageIcon = $rootScope.showLanguageIcon;
 }
 var qry;

 //Subscribe search element to service on load
 if(KnowledgeSearchService){
  var input = {};
  input.element = "search";
  input.alt_url_params = c.options.alt_search_url_params;
  KnowledgeSearchService.subscribe(input);
 }
 var refreshSearchFilter = $rootScope.$on('sp.kb.refresh.filter',function (event,data){
  if(data){
   c.items = data;
  }
  if(c.items.length>0){
   c.filterCount = c.items.length;
   c.applycolor = true;
  }else{
   c.filterCount = 0;
   c.applycolor = false;
  }
 });

 var refreshKeyword = $rootScope.$on('sp.kb.refresh.keyword',function(event,data){
  if(data)
   c.keyword = data.keyword;
 });

 $scope.$on('$destroy',function(){
  refreshSearchFilter();
  refreshKeyword();
 });</code>```

//Server script
(function($sp) {

 options.alt_search_url_params = options.alt_search_url_params || "";

 //Set keyword from url
 data.keyword = "";
 var keywordParm = $sp.getParameter('query') || "";

 if(keywordParm == ""){
  if(options.alt_search_url_params){
   var qParams =  options.alt_search_url_params.toString().split(",");
   qParams.forEach(function(key){
    if($sp.getParameter(key))
     keywordParm = $sp.getParameter(key);
   });
  }
 }

 if(keywordParm)
  data.keyword = keywordParm;

 //set values based on options and properties.
 //options will be given precedence if value exit
 data.set_foccus = gs.getProperty('glide.knowman.portal_search_focus') == 'true' || false;
 data.min_search_char = parseInt(options.min_search_char || gs.getProperty('glide.knowman.search_character_limit') || 3);
 data.allow_instant_search = options.allow_instant_search ? (options.allow_instant_search == 'Use system property' ?  gs.getProperty('glide.knowman.search.instant_results') == 'true' : options.allow_instant_search == 'Yes') : gs.getProperty('glide.knowman.search.instant_results') == 'true' || false;
 data.allow_empty_search = options.allow_empty_search ? (options.allow_empty_search == 'Use system property' ?  gs.getProperty('glide.knowman.allow_empty_search') == 'true' : options.allow_empty_search == 'Yes') : gs.getProperty('glide.knowman.allow_empty_search') == 'true' || false;

 options.search_wait = options.search_wait || 500;
 options.title = options.title || gs.getMessage('Search (minimum {0} characters)',data.min_search_char+'');

 var langOption = {};
 langOption.alt_lang_url_params = options.alt_lang_url_params || "";
 data.language_picker = $sp.getWidget("kb-language-picker",langOption);
})($sp);```

答:
Add this to your Link Function, right between c.showFiltersButton = true; and c.showAndHideFilters:

```<code>$(".hide-filters").addClass("show-filters").removeClass("hide-filters");
$(".expand-width").addClass("original-width").removeClass("expand-width");
</code>```

Body:
I am working on editing search functionality for a knowledge base. The knowledge base has a filter panel that can be displayed where users can select which database or category they want to use to filter search results. Currently it is set to "hidden" until the link/icon is clicked on for it. I would like to make it always visible if possible. Below I have the script file, css file, and html for the search and filter section. I would like for the show/hide link/icon to still work. I just want the default to be that the filter pane is shown.

//Link function
function(scope,element,attr){
 if(scope.data.set_foccus)
 setTimeout(function(){
  element.find('#kb_search_input').focus();
 },0);

 var c = scope.c;
 $rootScope = $injector.get("$rootScope");

 c.showFiltersButton = true;

 c.showAndHideFilters = function(){
  if(c.showFiltersButton==true){
   $(".hide-filters").addClass("show-filters").removeClass("hide-filters");
   $(".expand-width").addClass("original-width").removeClass("expand-width");
   c.showFiltersButton = false;
  }else{
   $(".show-filters").addClass("hide-filters").removeClass("show-filters");
   $(".original-width").addClass("expand-width").removeClass("original-width");
   c.showFiltersButton = true;
  }
 }

 c.hideFilters = function(){
   $(".show-filters").addClass("hide-filters").removeClass("show-filters");
  $(".original-width").addClass("expand-width").removeClass("original-width");
  c.showFiltersButton = true;
 }

 c.toggleFacets = function(){
  $rootScope.showFacet = !$rootScope.showFacet;
  $rootScope.showLanguageFacet = false;
 }

 c.showLanguageFacet = function(){
  $rootScope.showFacet = !$rootScope.showFacet;
  $rootScope.showLanguageFacet = true;
 }

 c.keywordChanged = function(event){
  c.keyword = c.keyword.trim();

  if(c.keyword != c.oldKeyword){
   //handle keyboard events for enter and keyup
   if(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(!c.data.allow_instant_search && keycode != 13)
     return;
   }

   //throw update event based on options
   if( (c.data.allow_empty_search && c.keyword == "") || (c.keyword && c.keyword.length >= c.data.min_search_char)){
    $rootScope.$emit('sp.kb.updated.keyword',{'keyword':c.keyword});
    c.hideFilters();
   }

   c.oldKeyword = angular.copy(c.keyword);
  }

  scope.$evalAsync(function(){
   if($("#kb_search_input"))
    $("#kb_search_input").focus();
  });
 };

 //If instant search enable then wait for 200ms for the next input then throw event
 $("#kb_search_input").keyup(_.debounce(function(event){
  c.keywordChanged(event);
 },c.options.search_wait));

 $(window).resize(function() {
  var width1 = $(window).width();
  if(width1<=992 && !$rootScope.isMobile){
   $rootScope.isMobile = true;
  }else if(width1>992 && $rootScope.isMobile ){
   $rootScope.showFacet = false;
   $rootScope.isMobile = false;
  }
 });

 //set keyword onload from url and throw event
 if(c.data.keyword){
  c.keyword = c.data.keyword;
  c.keywordChanged();
 }
}

@media only screen and (max-width: 991px) {
    .kb-search-block {
      padding-top : 7px !important;
    }
    .filter-icon-padding {
      padding-left : 0px !important;
      padding-right : 0px !important;
      text-align : center;
    }
    .kb-search-display-none {
      display :none !important;
    }
    .kb-search-block .lang-icon {
      font-size : 18px;
      float :left;
      padding-right:9px;
    }
  }
   @media only screen and (min-width:991px) {
   .expand-width {
     width :100%;
    }
    .hide-filters {
     display :none;
    }
    .original-width{
     width : 75%;
    }
    .show-filters {
     display:block;
    }
 }

        <input id="kb_search_input" name="q" type="text" ng-model="c.keyword" aria-label="{{::options.title}}"  placeholder="{{::options.title}}" class="form-control">

          <button name="search" type="submit" aria-label="search" class="btn btn-{{::c.options.color}}" ng-click="c.keywordChanged('')">

          </button>

    ${Show filters}
    ${Hide filters}

//client script
function($rootScope,$window,$timeout,KnowledgeSearchService,$scope) {
 var c = this;

 c.keyword = c.data.keyword || "";
 c.oldKeyword = c.data.keyword || "";
 c.options.glyph = c.options.glyph || 'search';
 c.filterCount =0;
 c.applycolor =false;
 c.items =[];
 c.showLanguageIcon = false;
 if($rootScope.showLanguageIcon){
  c.showLanguageIcon = $rootScope.showLanguageIcon;
 }
 var qry;

 //Subscribe search element to service on load
 if(KnowledgeSearchService){
  var input = {};
  input.element = "search";
  input.alt_url_params = c.options.alt_search_url_params;
  KnowledgeSearchService.subscribe(input);
 }
 var refreshSearchFilter = $rootScope.$on('sp.kb.refresh.filter',function (event,data){
  if(data){
   c.items = data;
  }
  if(c.items.length>0){
   c.filterCount = c.items.length;
   c.applycolor = true;
  }else{
   c.filterCount = 0;
   c.applycolor = false;
  }
 });

 var refreshKeyword = $rootScope.$on('sp.kb.refresh.keyword',function(event,data){
  if(data)
   c.keyword = data.keyword;
 });

 $scope.$on('$destroy',function(){
  refreshSearchFilter();
  refreshKeyword();
 });

//Server script
(function($sp) {

 options.alt_search_url_params = options.alt_search_url_params || "";

 //Set keyword from url
 data.keyword = "";
 var keywordParm = $sp.getParameter('query') || "";

 if(keywordParm == ""){
  if(options.alt_search_url_params){
   var qParams =  options.alt_search_url_params.toString().split(",");
   qParams.forEach(function(key){
    if($sp.getParameter(key))
     keywordParm = $sp.getParameter(key);
   });
  }
 }

 if(keywordParm)
  data.keyword = keywordParm;

 //set values based on options and properties.
 //options will be given precedence if value exit
 data.set_foccus = gs.getProperty('glide.knowman.portal_search_focus') == 'true' || false;
 data.min_search_char = parseInt(options.min_search_char || gs.getProperty('glide.knowman.search_character_limit') || 3);
 data.allow_instant_search = options.allow_instant_search ? (options.allow_instant_search == 'Use system property' ?  gs.getProperty('glide.knowman.search.instant_results') == 'true' : options.allow_instant_search == 'Yes') : gs.getProperty('glide.knowman.search.instant_results') == 'true' || false;
 data.allow_empty_search = options.allow_empty_search ? (options.allow_empty_search == 'Use system property' ?  gs.getProperty('glide.knowman.allow_empty_search') == 'true' : options.allow_empty_search == 'Yes') : gs.getProperty('glide.knowman.allow_empty_search') == 'true' || false;

 options.search_wait = options.search_wait || 500;
 options.title = options.title || gs.getMessage('Search (minimum {0} characters)',data.min_search_char+'');

 var langOption = {};
 langOption.alt_lang_url_params = options.alt_lang_url_params || "";
 data.language_picker = $sp.getWidget("kb-language-picker",langOption);
})($sp);

Body:
Add this to your Link Function, right between c.showFiltersButton = true; and c.showAndHideFilters:

$(".hide-filters").addClass("show-filters").removeClass("hide-filters");
$(".expand-width").addClass("original-width").removeClass("expand-width");


问:
How to re-order a xml-file with xslt while keeping structure
I know it is a basic problem but I'm very new to XSL and I don't get it to work. I have a XML-File with a given structure and I want to rearrange the XML in alphabetical order based on one node while keeping the structure. I need that XSLT-Stylesheet to reorder a XML when importing it in Adobe InDesign.

My File:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
</Root>
</code>```

I want to rearange the document in the way that it is sorted alphabetically based on the tag <Last_name>. My desired output is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
</Root>
</code>```

I found some solutions to re-arange my output but it's always in respect to output HTML and not XML.

Update: As requested here is my atempt to solve the problem. I stuck because it copyies now all in one tag <Employee>.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
  <Employee>
      <xsl:for-each select="Root/Employee">
      <xsl:sort select="Last_Name"/>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
      </xsl:for-each>
  </Employee>
  </Root>
</xsl:template>

</xsl:stylesheet>
</code>```

答:
Or simply:</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Root">
    <xsl:copy>
        <xsl:for-each select="Employee">
            <xsl:sort select="Last_Name"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I know it is a basic problem but I'm very new to XSL and I don't get it to work. I have a XML-File with a given structure and I want to rearrange the XML in alphabetical order based on one node while keeping the structure. I need that XSLT-Stylesheet to reorder a XML when importing it in Adobe InDesign.

My File:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
</Root>

I want to rearange the document in the way that it is sorted alphabetically based on the tag <Last_name>. My desired output is:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Employee>
        <First_Name>Donald</First_Name>
        <Last_Name>Abernathey</Last_Name>
        <Salary>95000</Salary>
        <Performance>7</Performance>
    </Employee>
    <Employee>
        <First_Name>Betsy</First_Name>
        <Last_Name>Clarke</Last_Name>
        <Salary>105000</Salary>
        <Performance>10</Performance>
    </Employee>
    <Employee>
        <First_Name>Andrew</First_Name>
        <Last_Name>Miller</Last_Name>
        <Salary>100000</Salary>
        <Performance>8</Performance>
    </Employee>
</Root>

I found some solutions to re-arange my output but it's always in respect to output HTML and not XML.

Update: As requested here is my atempt to solve the problem. I stuck because it copyies now all in one tag <Employee>.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
  <Root>
  <Employee>
      <xsl:for-each select="Root/Employee">
      <xsl:sort select="Last_Name"/>
        <First_Name><xsl:value-of select="First_Name"/></First_Name>
        <Last_Name><xsl:value-of select="Last_Name"/></Last_Name>
        <Salary><xsl:value-of select="Salary"/></Salary>
        <Performance><xsl:value-of select="Performance"/></Performance>
      </xsl:for-each>
  </Employee>
  </Root>
</xsl:template>

</xsl:stylesheet>

Body:
Or simply:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Root">
    <xsl:copy>
        <xsl:for-each select="Employee">
            <xsl:sort select="Last_Name"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


问:
Gif is not playing after shared element transition. Glide v 4.8.0
Gifs are playing in the list.
But after shared element transition it stops.</p>

```<code>.diskCacheStrategy(DiskCacheStrategy.ALL)
</code>```

```<code> GlideApp.with(this)
                .load(arguments?.getString(EXTRA_IMAGE_URL))
                .onlyRetrieveFromCache(true)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                        startPostponedEnterTransition()
                        return false
                    }

                    override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                        startPostponedEnterTransition()
                        return false
                    }
                })
                .into(view.ivDialog)
</code>```

答:
An ugly hack that works in my case (in Java sorry):</p>

```<code>.listener(new RequestListener<Drawable>() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
          return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
          if (resource instanceof GifDrawable){
            final Handler handler = new Handler();
            handler.post(() -> resource.setVisible(true, true));
          }
          return false;
        }
      });
</code>```

Body:
Gifs are playing in the list.
But after shared element transition it stops.

.diskCacheStrategy(DiskCacheStrategy.ALL)

 GlideApp.with(this)
                .load(arguments?.getString(EXTRA_IMAGE_URL))
                .onlyRetrieveFromCache(true)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean): Boolean {
                        startPostponedEnterTransition()
                        return false
                    }

                    override fun onResourceReady(resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                        startPostponedEnterTransition()
                        return false
                    }
                })
                .into(view.ivDialog)

Body:
An ugly hack that works in my case (in Java sorry):

.listener(new RequestListener<Drawable>() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
          return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
          if (resource instanceof GifDrawable){
            final Handler handler = new Handler();
            handler.post(() -> resource.setVisible(true, true));
          }
          return false;
        }
      });


问:
java regex : getting a substring from a string which can vary
I have a String like - "Bangalore,India=Karnataka". From this String I would like to extract only the substring "Bangalore". In this case the regex can be - (.+),.*=.*. But the problem is, the String can sometimes come like only "Bangalore". Then in that case the above regex wont work. What will be the regex to get the substring "Bangalore" whatever the String be ?

答:
If you are only interested to check that "Bangalore" is contained in the string then you don't need a regexp for this.

Python:

```<code>In [1]: s = 'Bangalorejkdjiefjiojhdu'

In [2]: 'Bangalore' in s
Out[2]: True
</code>```

Body:
If you are only interested to check that "Bangalore" is contained in the string then you don't need a regexp for this.

Python:

In [1]: s = 'Bangalorejkdjiefjiojhdu'

In [2]: 'Bangalore' in s
Out[2]: True


问:
Change global variable from event function
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main">
<table>
    <tr>
        <td class="b1-1"></td>
        <td class="b1-2"></td>
        <td class="b1-3"></td>
    </tr>
    <tr>
        <td class="b2-1"></td>
        <td class="b2-2"></td>
        <td class="b2-3"></td>
    </tr>
    <tr>
        <td class="b3-1"></td>
        <td class="b3-2"></td>
        <td class="b3-3"></td>
    </tr>
</table>
</div>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
</code>```

CSS

```<code>.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}
</code>```

Javascript

```<code>var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};
</code>```

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

答:
Your mistake is that you create the events in such a manner that they depend only on the current value of gameState, before any moves were made. You need to check and change the value of gameState inside the event:

```<code>var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    action[i].addEventListener("click", function() {
      this.textContent = (gameState = (gameState + 1) % 2) ? 'x' : '0';
  })
}
</code>```

https://jsfiddle.net/fby3g12v/

Body:
I am trying to learn Javascript.

I watched some Javascript course on Youtube and am trying to create my first project.

Project should be simple tic-tac-toe game.

Functionality:
First click on box should fill with "X"
Second click on another box should fill with "Y"
Third click on another box should fill with "X" again and so on until all boxes will be filled with character.

there is my codes
HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

CSS

.main {
    padding: 100px 0;
    width: 360px;
    margin: 0 auto;
}

table, tbody {
    margin: 0;
    padding: 0;
    width: 360px;
    height: 360px;
}

tr {
    width:360px;
    height: 120px;
    margin: 0;
    padding: 0;
}

td {
    text-align: center;
    width:120px;
    height: 120px;
    border: 1px solid #333;
    margin: 0;
    padding: 0;
    font-size: 50px;
}

Javascript

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    getClassName = "." + action[i].classList.value;
        if (gameState === 0) {
            document.querySelector(getClassName).addEventListener("click", chasviX(i));
        } else {
            document.querySelector(getClassName).addEventListener("click", chasviO(i));
        }
}

function chasviX(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "X";
            gameState = 1;
        });
};

function chasviO(cord) {
        document.querySelector("." + action[cord].classList.value).addEventListener("click", event => {
            document.querySelector("." + action[cord].classList.value).textContent = "O";
            gameState = 0;
        });
};

There is project link also - https://jsfiddle.net/qwy2k571/

At the moment each box is filling with "X".
I know i didn't understand closures and scope chains exactly but please give me an correct code to understand it by example.

Thanks in advance and best regards.

Body:
Your mistake is that you create the events in such a manner that they depend only on the current value of gameState, before any moves were made. You need to check and change the value of gameState inside the event:

var action = document.querySelectorAll('td');
var gameState = 0;
for (var i = 0; i <= action.length - 1; i++) {
    action[i].addEventListener("click", function() {
      this.textContent = (gameState = (gameState + 1) % 2) ? 'x' : '0';
  })
}

https://jsfiddle.net/fby3g12v/


问:
'Simple' Conversion from C# to Python
Using Python, I am trying to create an exe that will print barcode labels. This will interact with BarTender labeling software. I understand this is possible but I am new to Python and not sure how to go about this.
I have it in C# but I need to convert to Python. Would this be a simple conversion for someone who knows both languages ;)

```<code>// Declare a BarTender application variable
BarTender.Application btApp;
// Declare two BarTender document variables
BarTender.Format btFormat1;
BarTender.Format btFormat2;
// Create a new instance of BarTender
btApp = new BarTender.Application();
// Set the BarTender application visible
btApp.Visible = true;
// Open a BarTender document
btFormat1 = btApp.Formats.Open("c:\\Format1.btw", false, "");
// Open a second BarTender document
btFormat2 = btApp.Formats.Open("c:\\Format2.btw", false, "");
// Set focus to the first opened document
btFormat1.Activate();
// End the BarTender process
btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);
</code>```

So far I have

```<code>import win32.com.client

btApp = win32com.client.Dispatch("BarTender.Application")
btApp.Visible = 1
btFormat = btApp.Formats.Open(r"C:\Users\kmoe\Desktop\Print-Self_Labels.btw", false, "")
</code>```

The first argument is required and is a string containing the path and file name of the document to open. The second argument is a Boolean: if it is true, the method will close the default blank document called "Document1" that BarTender automatically opens when it starts. It cannot close documents that have any other name. The third argument specifies a printer to use.

However, this only opens the correct label template but does not print to the default printer

More info can be found here

http://help.seagullscientific.com/2016/en/#../Subsystems/ActiveX/Content/opening_format.htm%3FTocPath%3DAutomating%2520BarTender%7CAutomation%2520with%2520ActiveX%7CGetting%2520Started%7CExamples%2520Using%2520ActiveX%2520Automation%7C_____1

Thanks in advance!

答:
I had to implement Bartender label print from web server and I was unable to use Integration builder due version of the Bartender installed, so I decided to go ahead with ActiveX.
Old post, but here is tested code if someone else needs it.</p>

```<code>import win32com.client as win32

btApp = win32.Dispatch("BarTender.Application")
btApp.Visible = True

btFormat = btApp.Formats.Open("C:\\Users\\someUser\\Desktop\\YourLabel.btw", False, "PrinterName")

btFormat.SetNamedSubStringValue("btField1", "Data1")
btFormat.SetNamedSubStringValue("btField2", "Data2")
btFormat.SetNamedSubStringValue("btField3", "Data3")

btFormat.IdenticalCopiesOfLabel = 1
btFormat.PrintOut(False, False)
btFormat.Close(1)
btApp.Quit(1)
</code>```

Title: 'Simple' Conversion from C# to Python

Body:
Using Python, I am trying to create an exe that will print barcode labels. This will interact with BarTender labeling software. I understand this is possible but I am new to Python and not sure how to go about this.
I have it in C# but I need to convert to Python. Would this be a simple conversion for someone who knows both languages ;)

// Declare a BarTender application variable
BarTender.Application btApp;
// Declare two BarTender document variables
BarTender.Format btFormat1;
BarTender.Format btFormat2;
// Create a new instance of BarTender
btApp = new BarTender.Application();
// Set the BarTender application visible
btApp.Visible = true;
// Open a BarTender document
btFormat1 = btApp.Formats.Open("c:\\Format1.btw", false, "");
// Open a second BarTender document
btFormat2 = btApp.Formats.Open("c:\\Format2.btw", false, "");
// Set focus to the first opened document
btFormat1.Activate();
// End the BarTender process
btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);

So far I have

import win32.com.client

btApp = win32com.client.Dispatch("BarTender.Application")
btApp.Visible = 1
btFormat = btApp.Formats.Open(r"C:\Users\kmoe\Desktop\Print-Self_Labels.btw", false, "")

The first argument is required and is a string containing the path and file name of the document to open. The second argument is a Boolean: if it is true, the method will close the default blank document called "Document1" that BarTender automatically opens when it starts. It cannot close documents that have any other name. The third argument specifies a printer to use.

However, this only opens the correct label template but does not print to the default printer

More info can be found here

http://help.seagullscientific.com/2016/en/#../Subsystems/ActiveX/Content/opening_format.htm%3FTocPath%3DAutomating%2520BarTender%7CAutomation%2520with%2520ActiveX%7CGetting%2520Started%7CExamples%2520Using%2520ActiveX%2520Automation%7C_____1

Thanks in advance!

Body:
I had to implement Bartender label print from web server and I was unable to use Integration builder due version of the Bartender installed, so I decided to go ahead with ActiveX.
Old post, but here is tested code if someone else needs it.

import win32com.client as win32

btApp = win32.Dispatch("BarTender.Application")
btApp.Visible = True

btFormat = btApp.Formats.Open("C:\\Users\\someUser\\Desktop\\YourLabel.btw", False, "PrinterName")

btFormat.SetNamedSubStringValue("btField1", "Data1")
btFormat.SetNamedSubStringValue("btField2", "Data2")
btFormat.SetNamedSubStringValue("btField3", "Data3")

btFormat.IdenticalCopiesOfLabel = 1
btFormat.PrintOut(False, False)
btFormat.Close(1)
btApp.Quit(1)


问:
C# - Finding a string between two strings
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

```<code>int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);
</code>```

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

答:
When important value is the 2nd from the end, LastIndexOf instead of IndexOf is a quite natural choice; please, note that since we seach from the end, it's pTo which we compute first.

```<code>  string path = "Value->Value2->Value3->ImportantValue->val";

  string delimiter = "->";

  int pTo   = path.LastIndexOf(delimiter);
  int pFrom = pTo >= 0 ? path.LastIndexOf(delimiter, pTo) + delimiter.Length : -1;

  // Either important value or null
  string result = pFrom >= 0
    ? path.Substring(pFrom, pTo - pFrom)
    : null; // or throw exception here
</code>```

Body:
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

Body:
When important value is the 2nd from the end, LastIndexOf instead of IndexOf is a quite natural choice; please, note that since we seach from the end, it's pTo which we compute first.

  string path = "Value->Value2->Value3->ImportantValue->val";

  string delimiter = "->";

  int pTo   = path.LastIndexOf(delimiter);
  int pFrom = pTo >= 0 ? path.LastIndexOf(delimiter, pTo) + delimiter.Length : -1;

  // Either important value or null
  string result = pFrom >= 0
    ? path.Substring(pFrom, pTo - pFrom)
    : null; // or throw exception here


问:
How can I send data via TCP
I have a client front panel that will send whatever button is being pressed over to the server which is listening for the signals. How should I send the signal?

block diagram of client

答:
You can use an Event Structure in a While loop to catch the Value Change event on your array and use a custom message to describe which switch was pressed.

If you want to handle multiple arrays of switches, you can create multiple event cases.

Block diagram

Title: How can I send data via TCP


问:
How to import a CSS file in a React Component
I want to import a CSS file into a react component.

I've tried import disabledLink from "../../../public/styles/disabledLink"; but I get the error below;

Module not found: Error: Cannot resolve 'file' or 'directory' ../../../public/styles/disabledLink in c:\Users\User\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2

C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.css is the location of the CSS file I'm trying to load.

To me it seems like import is not looking up the correct path.

I thought with ../../../ it would start to look up the path three folder layers above.

C:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js is the location of the file that should import the CSS file.

What am I doing wrong and how can I fix it?

答:
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.

Button.module.css

```<code>.error {
  background-color: red;
}
</code>```

another-stylesheet.css

```<code>.error {
  color: red;
}
</code>```

Button.js

```<code>import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}
</code>```

Body:
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.

Button.module.css

.error {
  background-color: red;
}

another-stylesheet.css

.error {
  color: red;
}

Button.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}


问:
WC Bookings - filter - to few arguments passed
Using WooCoomerce along with WooCommerce Bookings plugin. In their API Reference, there's a listed filter for modifying booking cost: woocommerce_bookings_calculated_booking_cost. To cut it short, here's how it's applied in the code:

```<code>return apply_filters( 'woocommerce_bookings_calculated_booking_cost', $booking_cost, $product, $data );
</code>```

Now, I've added following code, to try and change the price:

```<code>function foobar_price_changer( $booking_cost, $product, $data ) {
   return $booking_cost;
}

add_filter( 'woocommerce_bookings_calculated_booking_cost', 'foobar_price_changer' );
</code>```

Now, when I use that code, it throws an error in my logs:

```<code>PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function sbnb_modify_wc_bookings_price(), 1 passed in /mywppath/wp-includes/class-wp-hook.php on line 290 and exactly 3 expected in /mywppath/wp-content/themes/enfold-child/functions.php:155
</code>```

As far as I read it, 3 arguments are passed to the add_filter callbacks, but in my case it only passes one. What could be the issue here?

答:
Give it a try this way

function foobar_price_changer( $booking_cost, $product, $data ) {
   return $booking_cost;
}
add_filter( 'woocommerce_bookings_calculated_booking_cost', 'foobar_price_changer', 10, 3 ); // Where $priority is 10, $args is 3.
```

Body:
Using WooCoomerce along with WooCommerce Bookings plugin. In their API Reference, there's a listed filter for modifying booking cost: woocommerce_bookings_calculated_booking_cost. To cut it short, here's how it's applied in the code:

return apply_filters( 'woocommerce_bookings_calculated_booking_cost', $booking_cost, $product, $data );

Now, I've added following code, to try and change the price:

function foobar_price_changer( $booking_cost, $product, $data ) {
   return $booking_cost;
}

add_filter( 'woocommerce_bookings_calculated_booking_cost', 'foobar_price_changer' );

Now, when I use that code, it throws an error in my logs:

PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function sbnb_modify_wc_bookings_price(), 1 passed in /mywppath/wp-includes/class-wp-hook.php on line 290 and exactly 3 expected in /mywppath/wp-content/themes/enfold-child/functions.php:155

As far as I read it, 3 arguments are passed to the add_filter callbacks, but in my case it only passes one. What could be the issue here?


问:
How to delete characters till the end after digits
I have input as below

```<code>1sum
2subtract
3multipy
4divide
...
</code>```

Expected output:

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

I tried %s/[0-9].*//g
But it is deleting digits also
I want to retain digits..pls help

Body:
I have input as below

1sum
2subtract
3multipy
4divide
...

Expected output:

1
2
3
4
...

I tried %s/[0-9].*//g
But it is deleting digits also
I want to retain digits..pls help

Body:
How about this one:

:%s/\([0-9]\).*/\1 /g


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
You may suffer from "too many architects in the team" syndrome. One or two people at most should design/architect a system which will be coded by a team of 5 to 10 people. Input is welcome from everyone but architectural decision makers should be few and experienced.

(the numbers are semi-random and could be different depending on other factors as well)

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: cherouvim


问:
What's a good way to organize projects with shared dependencies in Mercurial?
Currently, I'm moving from a legacy version control system and moving my group's project to mercurial.  As one example of the kinds of code I'm moving, I have a 25+ project Visual Studio solution, containing several separate application areas that all depend on common code.  Looking over Stack Overflow, the closest question I found was this one, but it merely mentioned version control.  I'm looking for a bit further advice, on specific implementation techniques of using Mercurial to manage these dependencies.

A simplified view of the dependencies look something like the following.  (This is for illustration and example only; the actual dependencies are significantly more complex but similar in nature.)

```<code>                     Common Lib 1
                    /      |      \
                ----       |       -----
               /           |        \   \
            App 1    Common Lib 2    \ App 2
                       /   |   \      \
                -------    |    ------ |
               /           |          \|
             App 3       App 4      App 5
</code>```

The Common Lib modules would be shared code - this would be a DLL or SO or some other library that would be used between all the apps simultaneously - both at compile and run time.  Applications would otherwise be able to run independently from each other.

I have a couple goals with setting up my mercurial repositories:

Give each significant application or component group its own repository.

Make each repository self contained.

Make the sum total of the project self contained.

Make it easy to build the entire codebase at once.  (eventually, all these programs and libraries end up in a single installer.)

Keep it simple.

One other point is that I have a server set up where I have separate repositories for each of these projects.

I see a couple ways of laying these projects out.

1. Create a "Shell" repository that contains everything.

This would use url-based subrepos (eg, in the .hgsub, I'd do something like App1 = https://my.server/repo/app1.)  Laid out, it would look like the following:

```<code>+---------------------------+
| Main Repository           |
| | +---------------------+ |
| +-| Build               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 1        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 2        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 1               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 2               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 3               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 4               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 5               | |
|   +---------------------+ |
+---------------------------+
</code>```

Each main folder in the shell repository would contain a subrepo, one for each project area.  Dependencies would be relative: Eg, since App 4 needs Common Lib 2, it would simply use relative paths to reference that common library.

Pros of this approach:

Each library is pulled down once and only once.

Mercurial's subreos will ensure that the same version of the library is used across all project automatically, since only one version of that subrepo exists in the project.

It's easy to find each resource.

Cons of this approach:

I can't work on an App independently.  Eg, if I work on App 2, and it needs a change to the common libraries, all of the other apps will have to take those changes right now.

If I pull an App repo by itself, I have to figure out (or know) what other dependent repos it requires by hand if I want to build it.

Dependencies are not strongly separated - it would be tempting to insert a new feature  anywhere since it was easy to get at all the features.

2. Have dependent subrepos be wholly contained.

In this approach, each application would have its own repository (as before) but this time also contain subrepositories: one for its own source, and one for each dependent subrepository.  An overall repository would then contain each of these project repositories, and know how to build the entire solution.  This would look like the following:

```<code>+-----------------------------------------------------------------------+
| Main Repository                                                       |
| +--------------------+ +--------------------+ +--------------------+  |
| | Build              | | Common Lib 1       | | Common Lib 2       |  |
| +--------------------+ | | +--------------+ | | | +--------------+ |  |
|                        | +-| Lib 1 Source | | | +-| Common Lib 1 | |  |
|                        |   +--------------+ | | | +--------------+ |  |
|                        |                    | | | +--------------+ |  |
|                        |                    | | +-| Lib 2 Source | |  |
|                        |                    | |   +--------------+ |  |
|                        +--------------------+ +--------------------+  |
| +--------------------+ +--------------------+ +---------------------+ |
| | App 1              | | App 2              | |  App 3              | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| Common Lib 1 | | | +-| Common Lib 1 | | |  +-| Common Lib 2 | | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| App 1 Source | | | +-| App 2 Source | | |  +-| App 3 Source | | |
| |   +--------------+ | |   +--------------+ | |    +--------------+ | |
| +--------------------+ +--------------------+ +---------------------+ |
| +--------------------+ +--------------------+                         |
| | App 4              | | App 5              |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| Common Lib 2 | | | +-| Common Lib 1 | |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| App 4 Source | | | +-| Common Lib 2 | |                         |
| |   +--------------+ | | | +--------------+ |                         |
| +--------------------+ + | +--------------+ |                         |
|                        | +-| App 5 Source | |                         |
|                        |   +--------------+ |                         |
|                        +--------------------+                         |
+-----------------------------------------------------------------------+
</code>```

Pros:

Each application can be built by itself, independent of each other.

Dependent versions of libraries can be tracked per-app, instead of globally.  It takes an explicit act of inserting a subrepo into the project to add a new dependency.

Cons:

When doing the final build, each app might be using a different version of a shared library.  (might need to write tools to sync the common lib subrepos.  Eww.)

If I want to build the entire source, I end up pulling down shared libraries multiple times.  In the case of Common Lib 1, I would have to pull it eight (!) times.

3.  Don't include dependencies at all as subrepos - bring them in as part of the build.

This approach would look much like approach 1, except the common libraries would only be pulled as part of the build.  Each app would know what repos it needed, and put them in the common location.

Pros:

Each app could build by itself.

Common libraries would only need to be pulled once.

Cons:

We'd have to keep track of versions of libraries currently used by each app.  This duplicates subrepo features.

We'd have to build an infrastructure to support this, which means more stuff going into build scripts.  Ugh.

4.  What else?

Is there another way of handling it?  A better way?  What ways have you tried and succeeded, what ways have you tried but hated?  I'm currently leaning towards 1, but the lack of application independence, when it should be able to, really bothers me.  Is there a way to get the nice separation of method 2 without the massive duplicate code pull and dependency maintenance nightmare, while not having to write scripts to handle it (like in option 3)?

答:
Dependencies management is an important aspect of a project's organization, to my eyes. You exposed in great details various solutions, based on the subrepos feature of Mercurial, and I agree with all the pros/cons that you gave.

I think SCMs are not well suited for dependencies management. I prefer having a dedicated tool for that (this would be your solution n°3).

My current project is in Java. It was built with Apache Ant, and I first set up Apache Ivy as a dependencies management tool. In the end, the setup consisted of some Ivy configuration files in a shared directory, and one XML file listing the dependencies for each module of the project. Ivy can be invoked by Ant targets, so I added two new actions in each module : "resolve dependencies", and "deploy the built artifact". The deployment adds the result of the buid (called an artifact) in the shared directory. The dependencies resolution means transitively resolving the dependencies of the module, and copying the resolved artifacts in the "lib" folder of the module's sources.

This solution is applicable to a C++ project, since Ivy is not specific to managing Java dependencies : artifacts can be anything. In C++, the artifacts produced by a module would be :

a so/dll at runtime

the header files at compile time.

This is not a perfect solution: Ivy is not easy to set up, you still have to tell your build script what dependencies to use, and you do not have direct access to the sources of the dependencies for debugging purpose. But you do end up with independent SCM repositories.

In our project, we then switched form Ant+Ivy to Apache Maven, which takes care of both the build and the dependencies management. The artifacts are deployed in an Apache Archiva instead of a shared folder. This is a huge improvement, but it will work well for Java projects only.

Body:
Currently, I'm moving from a legacy version control system and moving my group's project to mercurial.  As one example of the kinds of code I'm moving, I have a 25+ project Visual Studio solution, containing several separate application areas that all depend on common code.  Looking over Stack Overflow, the closest question I found was this one, but it merely mentioned version control.  I'm looking for a bit further advice, on specific implementation techniques of using Mercurial to manage these dependencies.

A simplified view of the dependencies look something like the following.  (This is for illustration and example only; the actual dependencies are significantly more complex but similar in nature.)

                     Common Lib 1
                    /      |      \
                ----       |       -----
               /           |        \   \
            App 1    Common Lib 2    \ App 2
                       /   |   \      \
                -------    |    ------ |
               /           |          \|
             App 3       App 4      App 5

The Common Lib modules would be shared code - this would be a DLL or SO or some other library that would be used between all the apps simultaneously - both at compile and run time.  Applications would otherwise be able to run independently from each other.

I have a couple goals with setting up my mercurial repositories:

Give each significant application or component group its own repository.

Make each repository self contained.

Make the sum total of the project self contained.

Make it easy to build the entire codebase at once.  (eventually, all these programs and libraries end up in a single installer.)

Keep it simple.

One other point is that I have a server set up where I have separate repositories for each of these projects.

I see a couple ways of laying these projects out.

1. Create a "Shell" repository that contains everything.

This would use url-based subrepos (eg, in the .hgsub, I'd do something like App1 = https://my.server/repo/app1.)  Laid out, it would look like the following:

+---------------------------+
| Main Repository           |
| | +---------------------+ |
| +-| Build               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 1        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 2        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 1               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 2               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 3               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 4               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 5               | |
|   +---------------------+ |
+---------------------------+

Each main folder in the shell repository would contain a subrepo, one for each project area.  Dependencies would be relative: Eg, since App 4 needs Common Lib 2, it would simply use relative paths to reference that common library.

Pros of this approach:

Each library is pulled down once and only once.

Mercurial's subreos will ensure that the same version of the library is used across all project automatically, since only one version of that subrepo exists in the project.

It's easy to find each resource.

Cons of this approach:

I can't work on an App independently.  Eg, if I work on App 2, and it needs a change to the common libraries, all of the other apps will have to take those changes right now.

If I pull an App repo by itself, I have to figure out (or know) what other dependent repos it requires by hand if I want to build it.

Dependencies are not strongly separated - it would be tempting to insert a new feature  anywhere since it was easy to get at all the features.

2. Have dependent subrepos be wholly contained.

In this approach, each application would have its own repository (as before) but this time also contain subrepositories: one for its own source, and one for each dependent subrepository.  An overall repository would then contain each of these project repositories, and know how to build the entire solution.  This would look like the following:

+-----------------------------------------------------------------------+
| Main Repository                                                       |
| +--------------------+ +--------------------+ +--------------------+  |
| | Build              | | Common Lib 1       | | Common Lib 2       |  |
| +--------------------+ | | +--------------+ | | | +--------------+ |  |
|                        | +-| Lib 1 Source | | | +-| Common Lib 1 | |  |
|                        |   +--------------+ | | | +--------------+ |  |
|                        |                    | | | +--------------+ |  |
|                        |                    | | +-| Lib 2 Source | |  |
|                        |                    | |   +--------------+ |  |
|                        +--------------------+ +--------------------+  |
| +--------------------+ +--------------------+ +---------------------+ |
| | App 1              | | App 2              | |  App 3              | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| Common Lib 1 | | | +-| Common Lib 1 | | |  +-| Common Lib 2 | | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| App 1 Source | | | +-| App 2 Source | | |  +-| App 3 Source | | |
| |   +--------------+ | |   +--------------+ | |    +--------------+ | |
| +--------------------+ +--------------------+ +---------------------+ |
| +--------------------+ +--------------------+                         |
| | App 4              | | App 5              |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| Common Lib 2 | | | +-| Common Lib 1 | |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| App 4 Source | | | +-| Common Lib 2 | |                         |
| |   +--------------+ | | | +--------------+ |                         |
| +--------------------+ + | +--------------+ |                         |
|                        | +-| App 5 Source | |                         |
|                        |   +--------------+ |                         |
|                        +--------------------+                         |
+-----------------------------------------------------------------------+

Pros:

Each application can be built by itself, independent of each other.

Dependent versions of libraries can be tracked per-app, instead of globally.  It takes an explicit act of inserting a subrepo into the project to add a new dependency.

Cons:

When doing the final build, each app might be using a different version of a shared library.  (might need to write tools to sync the common lib subrepos.  Eww.)

If I want to build the entire source, I end up pulling down shared libraries multiple times.  In the case of Common Lib 1, I would have to pull it eight (!) times.

3.  Don't include dependencies at all as subrepos - bring them in as part of the build.

This approach would look much like approach 1, except the common libraries would only be pulled as part of the build.  Each app would know what repos it needed, and put them in the common location.

Pros:

Each app could build by itself.

Common libraries would only need to be pulled once.

Cons:

We'd have to keep track of versions of libraries currently used by each app.  This duplicates subrepo features.

We'd have to build an infrastructure to support this, which means more stuff going into build scripts.  Ugh.

4.  What else?

Is there another way of handling it?  A better way?  What ways have you tried and succeeded, what ways have you tried but hated?  I'm currently leaning towards 1, but the lack of application independence, when it should be able to, really bothers me.  Is there a way to get the nice separation of method 2 without the massive duplicate code pull and dependency maintenance nightmare, while not having to write scripts to handle it (like in option 3)?


问:
Get two or more strings in one string
I want to get two or more strings in one string for example:

```<code>var data = 'xxxxxxxxxxxxxxxxx"link":"/main","link":"/old"xxxxxxxxxxxxxxxxxxxxx"link":"/new"xxxxx';

var index = 'link":"';

data.substring(data.lastIndexOf(index) + index.length,data.lastIndexOf('"')); // i want to get all /main , /old , /new in the var data
</code>```

Result:
/new

答:
Trying to guess what you want achieve. You could use the following code to get all the links of your string as a array

var data = 'xxxxxxxxxxxxxxxxx"link":"/main","link":"/old"xxxxxxxxxxxxxxxxxxxxx"link":"/new"xxxxx';

var result = data.match(/\/.+?(?=")/g)
```

The result would be the following:

(3) ["/main", "/old", "/new"]

0: "/main"

1: "/old"

2: "/new"

length: 3

Title: Get two or more strings in one string

Body:
I want to get two or more strings in one string for example:

var data = 'xxxxxxxxxxxxxxxxx"link":"/main","link":"/old"xxxxxxxxxxxxxxxxxxxxx"link":"/new"xxxxx';

var index = 'link":"';

data.substring(data.lastIndexOf(index) + index.length,data.lastIndexOf('"')); // i want to get all /main , /old , /new in the var data

Result:
/new

Body:
Trying to guess what you want achieve. You could use the following code to get all the links of your string as a array

var data = 'xxxxxxxxxxxxxxxxx"link":"/main","link":"/old"xxxxxxxxxxxxxxxxxxxxx"link":"/new"xxxxx';

var result = data.match(/\/.+?(?=")/g)

The result would be the following:

(3) ["/main", "/old", "/new"]

0: "/main"

1: "/old"

2: "/new"

length: 3