问:
Custom Authorize Attribute show denied message without routing to controller
In my ASP.NET web application, I'm using CustomAuthorizeAttribute for access control. So normal way is if the user role is not matched, the user will redirect to a controller and shows the access denied page.

Is there any way to do this like if the user role is not matched with authorization, Can't it show the message or alert or something on the view without routing to the controller?

This is the Model.

```<code>public class RoleAuthorize: AuthorizeAttribute {
  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
      filterContext.Result = new HttpUnauthorizedResult();
    } else {
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
        controller = "Account", action = "AccessDenied"
      }));
    }
  }
}

</code>```

Controller checking the authorization

```<code>[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[RoleAuthorize(Roles = "1")]
public ActionResult DeleteConfirmed(int id) {
  M_Employee m_Employee = db.CreateEmployee.Find(id);
  db.CreateEmployee.Remove(m_Employee);
  db.SaveChanges();
  return RedirectToAction("Index");
}

</code>```

Editing

I tried doing this

```<code> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
   if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
     filterContext.Result = new HttpUnauthorizedResult();
   } else {
     System.Web.HttpContext.Current.Session["error"] = "You're not authorize for this action";

   }
 }
</code>```

And the page I have modified as

```<code>< div class = "form-actions no-color" > @HttpContext.Current.Session["error"] < input type = "submit"
value = "Delete"
class = "btn btn-default" / > | @Html.ActionLink("Back to List", "Index") < /div>
</code>```

But it not working.

答:
You can try this.</p>
```<code> public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else
            {
                filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");
                filterContext.Result = new RedirectResult("~/Error");
            }
        }
</code>```

Body:
In my ASP.NET web application, I'm using CustomAuthorizeAttribute for access control. So normal way is if the user role is not matched, the user will redirect to a controller and shows the access denied page.

Is there any way to do this like if the user role is not matched with authorization, Can't it show the message or alert or something on the view without routing to the controller?

This is the Model.

public class RoleAuthorize: AuthorizeAttribute {
  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
      filterContext.Result = new HttpUnauthorizedResult();
    } else {
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {
        controller = "Account", action = "AccessDenied"
      }));
    }
  }
}

Controller checking the authorization

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[RoleAuthorize(Roles = "1")]
public ActionResult DeleteConfirmed(int id) {
  M_Employee m_Employee = db.CreateEmployee.Find(id);
  db.CreateEmployee.Remove(m_Employee);
  db.SaveChanges();
  return RedirectToAction("Index");
}

Editing

I tried doing this

 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
   if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
     filterContext.Result = new HttpUnauthorizedResult();
   } else {
     System.Web.HttpContext.Current.Session["error"] = "You're not authorize for this action";

   }
 }

And the page I have modified as

 @HttpContext.Current.Session["error"] < input type = "submit"
value = "Delete"
class = "btn btn-default" / > | @Html.ActionLink("Back to List", "Index")

But it not working.

Body:
You can try this.

 public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else
            {
                filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");
                filterContext.Result = new RedirectResult("~/Error");
            }
        }


来源: stackexchange

问:
get out from git repository (VScode)
I'm using both remote connection in VSCode and GitHub. Usually, I would clone my project in "source control" using a URL.

Every time I close the connection, I would automatically "get out" from the git repository.

Today, I used "clone repository" in "explorer", then VSCode started showing 6000+ changes in "source control": they are the old files I stored in my remote folder(nothing about the URL I just cloned).

How can I get out from this status? (or get out from the git repository ?)

(All folders are showing "green U" except the one containing my cloned project)

答:
To get out of Git on Visual Studio Code (on any platform), click on the account symbol (above the cog icon for Settings on the bottom of the left-hand side toolbar), and click Log out. This should log you out of your account.

If you are talking about ignoring the files, then add the following in .gitignore (in the folder you want to ignore).

```<code>*
*/
!.gitignore
</code>```

The first line informs Git to ignore all files in the folder, but add .gitignore, as specified in the third line.

ContentLicense: CC BY-SA 4.0

Title: get out from git repository (VScode)

Body:
To get out of Git on Visual Studio Code (on any platform), click on the account symbol (above the cog icon for Settings on the bottom of the left-hand side toolbar), and click Log out. This should log you out of your account.

If you are talking about ignoring the files, then add the following in .gitignore (in the folder you want to ignore).

*
*/
!.gitignore

The first line informs Git to ignore all files in the folder, but add .gitignore, as specified in the third line.


问:
I am trying to create_all() for a postgresql table but i am getting weird errors
My python flask code (quotes.py) is :

```<code>from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2:// postgres:password@localhost/quotes'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Favquotes(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    author = db.Column(db.String(30))
    quote = db.Column(db.String(2000))

@app.route('/')
def index():
    result = Favquotes.query.all()
    return render_template('index.html', result = result)

@app.route('/quotes')
def quotes():
    return render_template('quotes.html')

@app.route('/process', methods = ['POST'])
def process():
    author = request.form['author']
    quote = request.form['quote']
    quotedata = Favquotes(author = author , quote = quote)
    db.session.add(quotedata)
    db.session.commit()
    return redirect(url_for('index'))
</code>```

Getting the following errors :

```<code>>>> from quotes import db
>>> db.create_all()
Traceback (most recent call last):
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3250, in _wrap_pool_connect
    return fn()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect
    return _ConnectionFairy._checkout(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout
    rec = pool._do_get()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get
    self._dec_overflow()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get
    return self._create_connection()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__
    self.__connect()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect
    return dialect.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\default.py", line 597, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  password authentication failed for user " postgres"
</code>```

my pip list contain :

```<code>(venv) PS C:\Users\KIIT\Desktop\fav-quotes> pip list
Package          Version
---------------- -------
 - click            8.0.3
 - colorama         0.4.4
 - Flask            2.0.2
 - Flask-SQLAlchemy 2.5.1
 - greenlet         1.1.2
 - gunicorn         20.1.0
 - itsdangerous     2.0.1
 - Jinja2           3.0.3
 - MarkupSafe       2.0.1
 - pip              22.0.3
 - psycopg2         2.9.3
 - python-dotenv    0.19.2
 - setuptools       47.1.0
 - SQLAlchemy       1.4.31
 - Werkzeug         2.0.2
</code>```

and as you can see i am using a virtual environment.

答:
Try to use this

```<code> app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{POSTGRES_USERNAME}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DBNAME}"
</code>```

in your case it would be :

```<code> app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://postgres:password@localhost/quotes"
</code>```

Body:
My python flask code (quotes.py) is :

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2:// postgres:password@localhost/quotes'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Favquotes(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    author = db.Column(db.String(30))
    quote = db.Column(db.String(2000))

@app.route('/')
def index():
    result = Favquotes.query.all()
    return render_template('index.html', result = result)

@app.route('/quotes')
def quotes():
    return render_template('quotes.html')

@app.route('/process', methods = ['POST'])
def process():
    author = request.form['author']
    quote = request.form['quote']
    quotedata = Favquotes(author = author , quote = quote)
    db.session.add(quotedata)
    db.session.commit()
    return redirect(url_for('index'))

Getting the following errors :

>>> from quotes import db
>>> db.create_all()
Traceback (most recent call last):
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3250, in _wrap_pool_connect
    return fn()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect
    return _ConnectionFairy._checkout(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout
    rec = pool._do_get()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get
    self._dec_overflow()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get
    return self._create_connection()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__
    self.__connect()
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect
    return dialect.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\sqlalchemy\engine\default.py", line 597, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "C:\Users\KIIT\Desktop\fav-quotes\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL:  password authentication failed for user " postgres"

my pip list contain :

(venv) PS C:\Users\KIIT\Desktop\fav-quotes> pip list
Package          Version
---------------- -------
 - click            8.0.3
 - colorama         0.4.4
 - Flask            2.0.2
 - Flask-SQLAlchemy 2.5.1
 - greenlet         1.1.2
 - gunicorn         20.1.0
 - itsdangerous     2.0.1
 - Jinja2           3.0.3
 - MarkupSafe       2.0.1
 - pip              22.0.3
 - psycopg2         2.9.3
 - python-dotenv    0.19.2
 - setuptools       47.1.0
 - SQLAlchemy       1.4.31
 - Werkzeug         2.0.2

and as you can see i am using a virtual environment.

Body:
Try to use this

 app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{POSTGRES_USERNAME}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DBNAME}"

in your case it would be :

 app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://postgres:password@localhost/quotes"


问:
OpenAPi DateTime with timezone information
I am creating OpenApi Doc for an API.
Having a model object field with DateTime info with timezone.

Example: "2021-12-30T10:00:00+00:00"

The expected input date should be in UTC.

If I use the format: "date-time" then the corresponding generated example is "2021-12-30T10:00:00.123z" where timezone information is missing.

Please suggest the right format to use in the OpenApi spec so that I can get the desired DateTime with a timezone value.

答:
"2021-12-30T10:00:00.123z" ends with a 'z'.

This means this DateTime represents UTC time.

z stands for Zulu Timezone

UTC is sometimes known as "Zulu time"


问:
How to filter users in Active Directory for InActive Users in .Net?
I want to create a filter to fetch all the Active users in Active directory, I used this filter but it didn't worked  </p>

```<code>searcher.Filter = string.Format(
                System.Threading.Thread.CurrentThread.CurrentCulture,
                "(&(|(samaccountname={0})(mailnickname={0}))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
                alias);
</code>```

答:
Grab adfind from www.joeware.net and you can use it to test filters - adfind -f "<your filter here>" -default will do the trick.

What you pasted looks accurate although I would further scope it to users only like this:

```<code>(&(objectClass=user)(objectCategory=person)(|(samaccountname={0})(mailnickname={0}))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create a filter to fetch all the Active users in Active directory, I used this filter but it didn't worked

searcher.Filter = string.Format(
                System.Threading.Thread.CurrentThread.CurrentCulture,
                "(&(|(samaccountname={0})(mailnickname={0}))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
                alias);

Body:
Grab adfind from www.joeware.net and you can use it to test filters - adfind -f "<your filter here>" -default will do the trick.

What you pasted looks accurate although I would further scope it to users only like this:

(&(objectClass=user)(objectCategory=person)(|(samaccountname={0})(mailnickname={0}))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))


问:
How to get the intersection of two sets while recognizing equal set values/items not only by reference but by their equal structures and entries too?
I have two deal with two Set instances.

```<code>const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' },
]);

const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);
</code>```

Any object within a set will feature several and also distinct keys and values. The goal is to find structurally equal objects (same keys and values) in both sets, which is ... The intersection of equal data items in/of set1 and set2.

In the following example the expected result is [ { name: 'd' } ] ...

```<code>console.log([...set1].filter(item => set2.has(item)));
</code>```

... but it logs an empty array / [] instead.

An object features more than 20 keys so one has to compare them one by one, which can not be done in a hard coded way.

How could one achieve a generic approach for an intersection of two lists of structurally equal data items?

答:
const set1 = new Set([
    {name: 'a'},
    {name: 'b', lastname: 'bb'},
    {name: 'c'},
    {name: 'd'}
]);

const set2 = new Set([
    {name: 'b'},
    {name: 'd'}
]);

const names = [...set2].map(s2 => s2.name);

console.log([...set1].filter(item => names.includes(item.name)));```
</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>const set1 = new Set([
    {name: 'a'},
    {name: 'b', lastname: 'bb'},
    {name: 'c'},
    {name: 'd'},
    {name: 'e'}
]);

const set2 = new Set([
    {name: 'c', lastname: 'ccc'},
    {name: 'd'},
    {name: 'b', lastname: 'cc'},
    {name: 'e'}
]);

console.log([...set1].filter(item => {
    const s2Arr = [...set2];
    const itemKeys = Object.keys(item);
    for(let i = 0; i < s2Arr.length; i++){
        const s2Obj = s2Arr[i];
        const s2ObjKeys = Object.keys(s2Obj);
        if(s2ObjKeys.length == itemKeys.length){
            let oneSame = true;
            for(let j = 0; j < s2ObjKeys.length; j++){
                const s2ObjKey = s2ObjKeys[j];
                if(item[s2ObjKey] != s2Obj[s2ObjKey]){
                    oneSame = false;
                }
            }
            if(oneSame)
              return true;
        }
    }
    return false;
}));</code>```

Body:
I have two deal with two Set instances.

const set1 = new Set([
  { name: 'a' },
  { name: 'b', lastname: 'bb' },
  { name: 'c' },
  { name: 'd' },
]);

const set2 = new Set([
  { name: 'b' },
  { name: 'd' },
]);

Any object within a set will feature several and also distinct keys and values. The goal is to find structurally equal objects (same keys and values) in both sets, which is ... The intersection of equal data items in/of set1 and set2.

In the following example the expected result is [ { name: 'd' } ] ...

console.log([...set1].filter(item => set2.has(item)));

... but it logs an empty array / [] instead.

An object features more than 20 keys so one has to compare them one by one, which can not be done in a hard coded way.

How could one achieve a generic approach for an intersection of two lists of structurally equal data items?

Body:
const set1 = new Set([
    {name: 'a'},
    {name: 'b', lastname: 'bb'},
    {name: 'c'},
    {name: 'd'}
]);

const set2 = new Set([
    {name: 'b'},
    {name: 'd'}
]);

const names = [...set2].map(s2 => s2.name);

console.log([...set1].filter(item => names.includes(item.name)));

const set1 = new Set([
    {name: 'a'},
    {name: 'b', lastname: 'bb'},
    {name: 'c'},
    {name: 'd'},
    {name: 'e'}
]);

const set2 = new Set([
    {name: 'c', lastname: 'ccc'},
    {name: 'd'},
    {name: 'b', lastname: 'cc'},
    {name: 'e'}
]);

console.log([...set1].filter(item => {
    const s2Arr = [...set2];
    const itemKeys = Object.keys(item);
    for(let i = 0; i < s2Arr.length; i++){
        const s2Obj = s2Arr[i];
        const s2ObjKeys = Object.keys(s2Obj);
        if(s2ObjKeys.length == itemKeys.length){
            let oneSame = true;
            for(let j = 0; j < s2ObjKeys.length; j++){
                const s2ObjKey = s2ObjKeys[j];
                if(item[s2ObjKey] != s2Obj[s2ObjKey]){
                    oneSame = false;
                }
            }
            if(oneSame)
              return true;
        }
    }
    return false;
}));


问:
How can i make my navigation bar stick to the top of my screen with css
So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

```<code>    <header>
        <div class="container">
            <h1 class="logo">Navigation</h1>

            <nav>
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About us</a></li>
                    <li><a href="#">Contact us</a></li>
                </ul>
            </nav>
        </div>
    </header>
</code>```

And here is my CSS:

```<code>.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}
</code>```

I had to shrink the css code a bit but the ul is not really important here.

答:
Use position: sticky and top:0.

nav { position: sticky; top: 0; }
div { height: 2000px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>My nav</nav>
<div>some long div</div></code>```

This doesn't work in IE 11.

Body:
So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

Navigation

Home

About us

Contact us

And here is my CSS:

.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}

I had to shrink the css code a bit but the ul is not really important here.

Body:
Use position: sticky and top:0.

nav { position: sticky; top: 0; }
div { height: 2000px; }

<nav>My nav</nav>
<div>some long div</div>

This doesn't work in IE 11.


问:
How to get the file's path from file input?
please tell me how to get a full file path from an <input type="file">

i have tried fileinput.value but it shows fakepath.

i have also tried mozFullPath.

答:
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:

```<code>$('input[type=file]').change(function () {
    console.log(this.files[0].mozFullPath);
});
</code>```

https://jsfiddle.net/SCK5A/

Body:
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:

$('input[type=file]').change(function () {
    console.log(this.files[0].mozFullPath);
});

https://jsfiddle.net/SCK5A/


问:
simulate TinyMCE RTL button click after toolbar is instantiated
Is there any way to change the directionality of a textarea that is connected to a TinyMCE toolbar, by directly using the same commands that are created in plugins? What I mean is, I want to programmatically run the RTL directionality without actually clicking on the toolbar's icon.

In the source code of the directionality plugin, the following code is included:

```<code>        ed.addCommand('mceDirectionRTL', function() {
            setDir("rtl");
        });
</code>```

This means that mceDirectionRTL is a command. Can I use it directly in the code? I tried but it isn't recognized.

The reason I'm asking is that I want to run this command AFTER a tinyMCE instance is started, not during the initialization/setup function of the TinyMCE toolbar. I have a bunch of texraeas, some are english and some have the class ar to denote they are for Arabic, which is RTL.

But when I do this:
$('ID of my textarea'_ifr').contents().find('body').attr('dir', 'rtl');

Then everything is fine except that the mceExternalToolbar (the whole toolbar!) not just the textarea, becomes rtl. So the external toolbar basically goes out of place, and leans to the right side of the page. But I only want the textarea that it is connected to to have RTL text, not the whole toolbar!

So I want to somehow externally simulate clicking the RTL button on the toolbar AFTER the toolbar is instantiated. Is this possible?

答:
No need to build a new plugin

Use the directionality plugin

Then add rtl & ltr buttons to toolbar

```<code>      options:{
          selector: '#editor1',
          height: 350,
          language: 'fa_IR',
          plugins: 'directionality',
          toolbar: 'rtl ltr',
      }
</code>```

Body:
Is there any way to change the directionality of a textarea that is connected to a TinyMCE toolbar, by directly using the same commands that are created in plugins? What I mean is, I want to programmatically run the RTL directionality without actually clicking on the toolbar's icon.

In the source code of the directionality plugin, the following code is included:

        ed.addCommand('mceDirectionRTL', function() {
            setDir("rtl");
        });

This means that mceDirectionRTL is a command. Can I use it directly in the code? I tried but it isn't recognized.

The reason I'm asking is that I want to run this command AFTER a tinyMCE instance is started, not during the initialization/setup function of the TinyMCE toolbar. I have a bunch of texraeas, some are english and some have the class ar to denote they are for Arabic, which is RTL.

But when I do this:
$('ID of my textarea'_ifr').contents().find('body').attr('dir', 'rtl');

Then everything is fine except that the mceExternalToolbar (the whole toolbar!) not just the textarea, becomes rtl. So the external toolbar basically goes out of place, and leans to the right side of the page. But I only want the textarea that it is connected to to have RTL text, not the whole toolbar!

So I want to somehow externally simulate clicking the RTL button on the toolbar AFTER the toolbar is instantiated. Is this possible?

Body:
No need to build a new plugin

Use the directionality plugin

Then add rtl & ltr buttons to toolbar

      options:{
          selector: '#editor1',
          height: 350,
          language: 'fa_IR',
          plugins: 'directionality',
          toolbar: 'rtl ltr',
      }


问:
Main Form not displaying when showing modal form in main form's OnShow?
I have created one application in which Main Form Calls Sub Form on FormShow event of Main Form. Sub Form is displayed and gives two options to choose. If First option on sub form is selected then then a Message is displayed and after that Main form will be displayed. Now when application runs on first time then after option selected on subform Meassage will be displayed. But i want to display message with Main Form as Background. So any solution to this. below is the FormShow code.</p>

```<code>Procedure TMainForm.FormShow(Sender:TObject);
begin
  if (SubForm.ShowModal = mrOK) and bOption1 then
  begin
    ShowMessage('Enter the value');
  end;
end;
</code>```

答:
Yet another option would be to drop a TTimer component on your main form to trigger the message dialog.

Drop a TTimer component on your main form and set the enabled property to False and change the time from 1000 to 100.  Code your message dialog and also set the Timer.Enabled property to False in the timer event to avoid repeated firings.

Now you can Enable the Timer at the point where you would have shown the message dialog in your main form's OnShow event.

Body:
I have created one application in which Main Form Calls Sub Form on FormShow event of Main Form. Sub Form is displayed and gives two options to choose. If First option on sub form is selected then then a Message is displayed and after that Main form will be displayed. Now when application runs on first time then after option selected on subform Meassage will be displayed. But i want to display message with Main Form as Background. So any solution to this. below is the FormShow code.

Procedure TMainForm.FormShow(Sender:TObject);
begin
  if (SubForm.ShowModal = mrOK) and bOption1 then
  begin
    ShowMessage('Enter the value');
  end;
end;


问:
How to go exec and pass user input required by the command on run
golang expert, I'm relatively new to go exec stuff and trying to replicate the below command in golang exec

```<code>root@e4187cadd9ed:/opt/sample# ../solana transfer -k ../id.json  --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet
[from] seed phrase:
[from] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue:
</code>```

The program will ask for a seed phrase that needs to be passed so that the program will continue and this can't be passed in the argument.

```<code>cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "found post practice action leave spread impact chair skate coach kingdom coral")
</code>```

after that progmram except one more input that I don't know hot to write it in go lang and continute the program

How to pass this particular value dynamically using go lang ?

package main

//solana transfer --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    app := "../solana"

    arg0 := "transfer"
    arg1 := "--from"
    arg2 := "prompt://?key=0/2"
    arg3 := "DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK"
    arg4 := "0.3"
    arg5 := "--url"
    arg6 := "devnet"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "abx sd sda sd dsa sd sad sda dsa coach asd dds")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err = cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Result: " + out.String())
    stdout, err := cmd.Output()
    fmt.Println(string(stdout))
}
```

The go program which is written takes all the user input but exit in the user prompt any pointer will be great help here.

答:
You can us os.Args for that.

os.Args[1] is the first argument following the app (os.Args[0]) and so on

https://gobyexample.com/command-line-arguments

Body:
golang expert, I'm relatively new to go exec stuff and trying to replicate the below command in golang exec

root@e4187cadd9ed:/opt/sample# ../solana transfer -k ../id.json  --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet
[from] seed phrase:
[from] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue:

The program will ask for a seed phrase that needs to be passed so that the program will continue and this can't be passed in the argument.

cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "found post practice action leave spread impact chair skate coach kingdom coral")

after that progmram except one more input that I don't know hot to write it in go lang and continute the program

How to pass this particular value dynamically using go lang ?

package main

//solana transfer --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    app := "../solana"

    arg0 := "transfer"
    arg1 := "--from"
    arg2 := "prompt://?key=0/2"
    arg3 := "DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK"
    arg4 := "0.3"
    arg5 := "--url"
    arg6 := "devnet"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "abx sd sda sd dsa sd sad sda dsa coach asd dds")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err = cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Result: " + out.String())
    stdout, err := cmd.Output()
    fmt.Println(string(stdout))
}

The go program which is written takes all the user input but exit in the user prompt any pointer will be great help here.


问:
Consider defining a bean of type 'com.example.conferencedemo.services.SessionService' in your configuration
I am trying to implement as of enterprise level, there they have folders like Repository,Service,ServiceImpl

In Services they have interface with method declaration

In ServiceImpl they have class implementing the interface of services

In Repository they have all Repository interfaces

BeanInjection is a class where we have all repositories and service classes and interfaces with
@Autowired annotation.

When I tried to implement "@Autowired" to service class getting this Error.

Tried this no help link

Tried this no help but getting loop error  link

Controller.java

```<code>public class SessionController extends BeanInjectionService {

    @GetMapping
    public ResponseEntity<List<Session>> list(){
        LOGGER.info("Request received to view the sessions");
        List<Session> sessions = sessionService.findAll();
        LOGGER.info("Successfully fetched all the sessions");
        return new ResponseEntity<>(sessions, HttpStatus.OK);
    }
</code>```

SessionService.java(Interface)

```<code>public interface SessionService {

    List<Session> findAll();
}

</code>```

SessionServiceImpl.java(Class)

```<code>public class SessionServiceImpl  extends BeanInjectionService implements SessionService {

    @Override
    public List<Session> findAll(){
        return sessionRepository.findAll();
    }
</code>```

BeanInjectionService.java(Class)

```<code>
public class BeanInjectionService {

    @Autowired
    public SessionRepository sessionRepository;

    **// Error Showing here while starting application
    // Consider defining a bean of type 'com.example.conferencedemo.services.SessionService' in your configuration.**
    @Autowired
    public SessionService sessionService;

    @Autowired
    public SpeakerRepository speakerRepository;

    @Autowired
    public SpeakerService speakerService;

}
</code>```

SessionRepository.java(Interface)

```<code>public interface SessionRepository extends JpaRepository<Session,Long> {

}
</code>```

Thanks in advance

答:
I find using BeanInjectionService a little weird, but I'll answer around it.

Unless you add @Service on SessionServiceImpl, you can't autowire it.

Circular dependency - If you do step 1, it will create a circular dependency because SessionServiceImpl needs its superclass object(BeanInjectionService) to be created first. But BeanInjectionService cannot be created unless it finds an object of SessionServiceImpl.

To break the circular dependency, you have only one option. Don't extend BeanInjectionService. Rather, autowire SessionRepository directly into SessionServiceImpl.

@Service
public class SessionServiceImpl  implements SessionService {

    @Autowired
    private SessionRepository sessionRepository;

    @Override
    public List<Session> findAll(){
        return sessionRepository.findAll();
    }
}
```

Body:
I am trying to implement as of enterprise level, there they have folders like Repository,Service,ServiceImpl

In Services they have interface with method declaration

In ServiceImpl they have class implementing the interface of services

In Repository they have all Repository interfaces

BeanInjection is a class where we have all repositories and service classes and interfaces with
@Autowired annotation.

When I tried to implement "@Autowired" to service class getting this Error.

Tried this no help link

Tried this no help but getting loop error  link

Controller.java

public class SessionController extends BeanInjectionService {

    @GetMapping
    public ResponseEntity<List<Session>> list(){
        LOGGER.info("Request received to view the sessions");
        List<Session> sessions = sessionService.findAll();
        LOGGER.info("Successfully fetched all the sessions");
        return new ResponseEntity<>(sessions, HttpStatus.OK);
    }

SessionService.java(Interface)

public interface SessionService {

    List<Session> findAll();
}

SessionServiceImpl.java(Class)

public class SessionServiceImpl  extends BeanInjectionService implements SessionService {

    @Override
    public List<Session> findAll(){
        return sessionRepository.findAll();
    }

BeanInjectionService.java(Class)

public class BeanInjectionService {

    @Autowired
    public SessionRepository sessionRepository;

    **// Error Showing here while starting application
    // Consider defining a bean of type 'com.example.conferencedemo.services.SessionService' in your configuration.**
    @Autowired
    public SessionService sessionService;

    @Autowired
    public SpeakerRepository speakerRepository;

    @Autowired
    public SpeakerService speakerService;

}

SessionRepository.java(Interface)

public interface SessionRepository extends JpaRepository<Session,Long> {

}

Thanks in advance


问:
How tagging works in GIT
I have a question about tagging in GIT.

Let's imagine that I am working on a repository in which I have a series of changes merged on the master branch and I have tagged that master branch with version 2.1.0.

If I now make other changes and merge them also to the master branch, that 2.1.0 tag will catch those new merged changes or I would have to create another version as 2.1.1 (for example)?

thanks a lot!! :)

答:
Tag is a pointer to a commit

From the documentation

Git supports two types of tags: lightweight and annotated.

A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit.

Annotated tags, however, are stored as full objects in the Git database. >They’re checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too.

So if you change your branch nothing happens to your tag

Title: How tagging works in GIT


问:
Trouble running PowerShell command with subprocess library in Python script runbook (Azure automation account)
I'm new to Azure automation, and have a python script that runs fine on the local machine. The script runs a PowerShell command to get sign in logs, and does some string parsing on them before writing to a storage account table. I was able to install all dependencies for the script via the "Python Packages" blade in the automation account. Is there a way to add powershell.exe somewhere so that the subprocess library can be used to run the PowerShell command? Alternatively, is there a library you can import to be able to run the PowerShell command or grab sign in logs from Azure AD without directly using the powershell.exe file?

Also, Microsoft.Powershell.Core is added in the Modules within the automation account. Am I just using the wrong filename and should use something other than powershell.exe? Is there a different module you have to install, or am I referencing it wrong?

Here is the relevant portion of the script:

```<code>import subprocess
import sys
import json
import azure.core
from azure.core.credentials import AzureNamedKeyCredential
from azure.data.tables import TableServiceClient, TableClient

data = subprocess.check_output(["powershell.exe", "Connect-AzureAD -AccountId placeholder@placeholder.com \n Get-AzureADAuditSignInLogs"]).decode(sys.stdout.encoding)
</code>```

This throws a "FileNotFound" error for powershell.exe. In the context of an Azure Automation runbook, how can you run powershell commands with the subprocess library, then? Any ideas are much appreciated. Many thanks

答:
I have tested in my environment

I get the same error as yours if I use subprocess in my python script to run PowerShell command

This is because the subprocess module is not able to find the powershell.exe path

For the workaround, you can use either of the options:

You can use PowerShell script instead of python script

You can use MS Graph API in your python code instead of PowerShell commands

Body:
I'm new to Azure automation, and have a python script that runs fine on the local machine. The script runs a PowerShell command to get sign in logs, and does some string parsing on them before writing to a storage account table. I was able to install all dependencies for the script via the "Python Packages" blade in the automation account. Is there a way to add powershell.exe somewhere so that the subprocess library can be used to run the PowerShell command? Alternatively, is there a library you can import to be able to run the PowerShell command or grab sign in logs from Azure AD without directly using the powershell.exe file?

Also, Microsoft.Powershell.Core is added in the Modules within the automation account. Am I just using the wrong filename and should use something other than powershell.exe? Is there a different module you have to install, or am I referencing it wrong?

Here is the relevant portion of the script:

import subprocess
import sys
import json
import azure.core
from azure.core.credentials import AzureNamedKeyCredential
from azure.data.tables import TableServiceClient, TableClient

data = subprocess.check_output(["powershell.exe", "Connect-AzureAD -AccountId placeholder@placeholder.com \n Get-AzureADAuditSignInLogs"]).decode(sys.stdout.encoding)

This throws a "FileNotFound" error for powershell.exe. In the context of an Azure Automation runbook, how can you run powershell commands with the subprocess library, then? Any ideas are much appreciated. Many thanks


问:
Sort number array using lodash/Javascript
I have a string array as below.

```<code>let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
</code>```

I want the expected output as below.

```<code>["1+", "1", "1-", "2+", "2", "2-", "3+", "3", "3-", "4", "10"];
</code>```

I tried the below code but it is not giving me the correct result.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
let result = arr.sort((a,b) => {
  return a.localeCompare(b, undefined, {
      numeric: true,
      sensitivity: 'base',
    });
  });

console.log(result);```

答:
You should try convert string to decimal number and then compare.
For example if you convert "2+" to 1.9 and "2-" to 2.1 then you can compare values as a numbers.

const arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

function convertToNumber(text) {
    const offset = text.endsWith("+") ? -0.1 : text.endsWith("-") ? 0.1 : 0;
    if (text.endsWith("+") || text.endsWith("-")) {
        text = text.substring(0, text.length - 1);
    }
    return parseFloat(text) + offset;
}

const sorted = arr.sort((a, b) => {
    return convertToNumber(a) > convertToNumber(b);
});
console.log("Sorted: ", sorted);```

Body:
I have a string array as below.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

I want the expected output as below.

["1+", "1", "1-", "2+", "2", "2-", "3+", "3", "3-", "4", "10"];

I tried the below code but it is not giving me the correct result.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
let result = arr.sort((a,b) => {
  return a.localeCompare(b, undefined, {
      numeric: true,
      sensitivity: 'base',
    });
  });

console.log(result);


问:
Endless loop with std::distance on custom list
For the fun of it, I implemented a std::list similar container by myself.

I will never use it in reality. Just practising . . .

During the comparison of my implemented functionality with the std::list, I found a severe problem.

Testing std::distance with invalid parameters, as part of a simple unit test, shows different results.

Of course I expect UB and indeterminate results, but std::distance on my implementation goes into an endless loop, while it does not with a std::list. Why?

Why is my implementation causing an endles loop with std::distance?

I followd link1 and link2 in CPP reference to the source code of std::distance and tried to reproduce it. But this works also for my implemenation.

Test/driver code:

```<code>int main() {

    // std::list works. No endless loop.
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}
</code>```

What is wrong with my implementation?

Please see the full source code below.

```<code>#include <iostream>
#include <iterator>
#include <vector>
#include <type_traits>
#include <initializer_list>
#include <algorithm>
#include <list>

// ------------------------------------------------------------------------------------------------
// This would be in a header file -----------------------------------------------------------------

// Type trait helper to identify iterators --------------------------------------------------------
template<typename T, typename = void>
struct is_iterator { static constexpr bool value = false; };
template<typename T>
struct is_iterator<T, typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::value_type, void>::value>::type> {
    static constexpr bool value = true;
};

// The List class ---------------------------------------------------------------------------------
template <typename T>
class List {
    // Sub class for a Node -----------
    struct Node {
        Node* next{};
        Node* previous{};
        T data{};
        Node(Node* const n, Node* const p, const T& d) : next(n), previous(p), data(d) {}
        Node(Node* const n, Node* const p) : next(n), previous(p) {}
        Node() {}
    };

    // Private list data and functions --------
    size_t numberOfElements{};
    Node* head{};
    void init() { head = new Node(); head->next = head; head->previous = head; numberOfElements = 0; }

public:
    struct iterator;    // Forward declaration

    // Constructor --------------------
    List() { init(); }
    explicit List(const size_t count, const T& value) { init(); insert(begin(), count, value); };
    explicit List(const size_t count) { init(); insert(begin(), count); }
    template <typename Iter>
    List(const Iter& first, const Iter& last) { init(); insert(begin(),first, last); }
    List(const List& other) { init(), insert(begin(), other.begin(), other.end()); };
    List(List&& other) : head(other.head), numberOfElements(other.numberOfElements) { other.init(); }
    List(const std::initializer_list<T>& il) { init(); insert(begin(), il.begin(), il.end()); }
    template <int N> List(const T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }
    template <int N> List(T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }

    // Assignment ---------------------
    List& operator =(const List& other) { clear(); insert(begin(), other.begin(), other.end()); return *this; }
    List& operator =(List&& other) { clear(); head = other.head; numberOfElements = other.numberOfElements; other.init(); return *this; }
    List& operator =(const std::initializer_list<T>& il) { clear(); insert(begin(),il.begin(),il.end()); return *this; }
    template <int N> List& operator =(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> List& operator =(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this;}

    void assign(const size_t count, const T& value) { clear(); insert(begin(), count, value); }
    void assign(const std::initializer_list<T>& il) { clear(); insert(begin(), il.begin(), il.end()); }
    template <typename Iter> void assign(const Iter& first, const Iter& last) { clear(); insert(begin(), first, last);}
    template <int N> void assign(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> void assign(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }

    // Destructor ---------------------
    ~List() { clear(); }

    // Element Access -----------------
    T& front() { return *begin(); }
    T& back() { return *(--end()); }

    // Iterators ----------------------
    iterator begin() const { return iterator(head->next, head); }
    iterator end() const { return iterator(head, head); }

    // Capacity -----------------------
    size_t size() const { return numberOfElements; }
    bool empty() { return size() == 0; }

    // Modifiers ----------------------
    void clear();

    iterator insert(const iterator& insertBeforePosition, const T& value);
    iterator insert(const iterator& insertBeforePosition);
    template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool> = true>
    iterator insert(const iterator& insertBeforePosition, const Iter& first, const Iter& last);
    iterator insert(const iterator& insertBeforePosition, const size_t& count, const T& value);
    iterator insert(const iterator& insertBeforePosition, const std::initializer_list<T>& il);

    iterator erase(const iterator& posToDelete);
    iterator erase(const iterator& first, const iterator& last);

    void push_back(const T& d) { insert(end(), d); }
    void pop_back() { erase(--end()); };

    void push_front(const T& d) { insert(begin(), d); }
    void pop_front() { erase(begin()); };

    void resize(size_t count);
    void resize(size_t count, const T& value);

    void swap(List& other) { std::swap(head, other.head); std::swap(numberOfElements, other.numberOfElements); }

     // Operations --------------------
    void reverse();

    // Non standard inefficient functions --------------------------
    T& operator[](const size_t index) const { return begin()[index]; }

    // ------------------------------------------------------------------------
    // Define iterator capability ---------------------------------------------
    struct iterator {

        // Definitions ----------------
        using iterator_category = std::bidirectional_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = T;
        using pointer = T*;
        using reference = T&;

        // Data -----------------------
        Node* iter{};
        Node* head{};

        // Constructor ----------------
        iterator(Node*const node, Node* const h) : iter(node), head(h) {};
        iterator() {};

        // Dereferencing --------------
        reference operator*() const { return iter->data; }
        reference operator->() const { return &**this; }

        // Arithmetic operations ------
        iterator operator++() { if (iter != head) iter = iter->next; return *this; }
        iterator operator++(int) { iterator tmp = *this; ++* this; return tmp; }
        iterator operator--() { if (iter != head->next) iter = iter->previous; return *this; }
        iterator operator--(int) { iterator tmp = *this; --* this; return tmp; }

        iterator operator +(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)++temp; else while (k++)--temp; return temp;
        }
        iterator operator +=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)++* this; else while (k++)--* this; return *this;
        };
        iterator operator -(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)--temp; else while (k++)++temp; return temp;
        }
        iterator operator -=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)--* this; else while (k++)++* this; return *this;
        };
        // Comparison -----------------
        bool operator ==(const iterator& other) const { return iter == other.iter; };
        bool operator !=(const iterator& other) const { return iter != other.iter; };
        bool operator < (const iterator& other) const { return other.iter - iter < 0; };
        bool operator <= (const iterator& other) const { return other.iter - iter <= 0; };
        bool operator > (const iterator& other) const { return other.iter - iter > 0; };
        bool operator >= (const iterator& other) const { return other.iter - iter >= 0; };

        // Special non standard functions -----------------
        difference_type operator-(const iterator& other) const;
        reference operator[] (const size_t index);
    };
};

// ------------------------------------------------------------------------------------------------
// Implementation of list functions. This would normally go into a TCC file -----------------------

// List class functions ---------------
template <typename T>
void List<T>::clear() {

    for (Node* nextNode{}, * currentNode(head->next); currentNode != head; currentNode = nextNode) {
        nextNode = currentNode->next;
        delete currentNode;
    }
    init();
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const T& value)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous, value);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}

template <typename T>
template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool>>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const Iter& first, const Iter& last) {
    iterator result(insertBeforePosition.iter, head);
    if (first != last) {
        result = insert(insertBeforePosition, *first);
        Iter i(first);
        for (++i; i != last; ++i)
            insert(insertBeforePosition, *i);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const size_t& count, const T& value) {

    iterator result(insertBeforePosition.iter, head);
    if (count != 0u) {
        result = insert(insertBeforePosition, value);
        for (size_t i{ 1u }; i < count; ++i)
            insert(insertBeforePosition, value);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const std::initializer_list<T>& il) {
    return insert(insertBeforePosition, il.begin(), il.end());
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& posToDelete) {

    iterator result = posToDelete;
    ++result;

    Node* nodeToDelete = posToDelete.iter;

    if (nodeToDelete != head) {

        nodeToDelete->previous->next = nodeToDelete->next;
        nodeToDelete->next->previous = nodeToDelete->previous;

        delete nodeToDelete;
        --numberOfElements;
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& first, const List<T>::iterator& last) {
    iterator result{ end() };
    if (first == begin() && last == end())
        clear();
    else {
        while (first != last)
            first = erase(first);
        result = last;
    }
    return result;
}

template <typename T>
void List<T>::resize(size_t count) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end());
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::resize(size_t count, const T& value) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end(),value);
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::reverse() {
    const Node* oldHead = head;

    for (Node* nptr = head; ; nptr = nptr->previous) {
        std::swap(nptr->next, nptr->previous);
        if (nptr->previous == oldHead) // Previous was the original next
            break;
    }
}

// ------------------------------------
// Iterator functions -----------------
template <typename T>
typename List<T>::iterator::difference_type List<T>::iterator::operator-(const iterator& other) const {

    difference_type result{};
    Node* nptr = head;

    int indexThis{ -1 }, indexOther{ -1 }, index{};

    do {
        nptr = nptr->next;
        if (nptr == iter)
            indexThis = index;
        if (nptr == other.iter)
            indexOther = index;
        ++index;
    } while (nptr != head);

    if (indexThis >= 0 and indexOther >= 0)
        result = indexThis - indexOther;
    return result;
}
template <typename T>
typename List<T>::iterator::reference List<T>::iterator::operator[] (const size_t index) {
    Node* nptr = head->next;
    for (size_t i{}; i < index and nptr != head; ++i, nptr = nptr->next)
        ;
    return nptr->data;
}

// ------------------------------------------------------------------------------------------------
// This would be in a cpp file --------------------------------------------------------------------
int main() {

    // std::list works
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}
</code>```

答:
This:

```<code>// Distance will go into endless loop ****************************
std::cout << std::distance(list2.end(), list2.begin()) << '\n';
</code>```

should be:

```<code>// Distance will go into endless loop ****************************
std::cout << std::distance(list2.begin(), list2.end()) << '\n';
</code>```

What you do here is start from the end and increase the iterator until it reaches the beginning. This is an endless loop

Body:
For the fun of it, I implemented a std::list similar container by myself.

I will never use it in reality. Just practising . . .

During the comparison of my implemented functionality with the std::list, I found a severe problem.

Testing std::distance with invalid parameters, as part of a simple unit test, shows different results.

Of course I expect UB and indeterminate results, but std::distance on my implementation goes into an endless loop, while it does not with a std::list. Why?

Why is my implementation causing an endles loop with std::distance?

I followd link1 and link2 in CPP reference to the source code of std::distance and tried to reproduce it. But this works also for my implemenation.

Test/driver code:

int main() {

    // std::list works. No endless loop.
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}

What is wrong with my implementation?

Please see the full source code below.

#include <iostream>
#include <iterator>
#include <vector>
#include <type_traits>
#include <initializer_list>
#include <algorithm>
#include <list>

// ------------------------------------------------------------------------------------------------
// This would be in a header file -----------------------------------------------------------------

// Type trait helper to identify iterators --------------------------------------------------------
template<typename T, typename = void>
struct is_iterator { static constexpr bool value = false; };
template<typename T>
struct is_iterator<T, typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::value_type, void>::value>::type> {
    static constexpr bool value = true;
};

// The List class ---------------------------------------------------------------------------------
template <typename T>
class List {
    // Sub class for a Node -----------
    struct Node {
        Node* next{};
        Node* previous{};
        T data{};
        Node(Node* const n, Node* const p, const T& d) : next(n), previous(p), data(d) {}
        Node(Node* const n, Node* const p) : next(n), previous(p) {}
        Node() {}
    };

    // Private list data and functions --------
    size_t numberOfElements{};
    Node* head{};
    void init() { head = new Node(); head->next = head; head->previous = head; numberOfElements = 0; }

public:
    struct iterator;    // Forward declaration

    // Constructor --------------------
    List() { init(); }
    explicit List(const size_t count, const T& value) { init(); insert(begin(), count, value); };
    explicit List(const size_t count) { init(); insert(begin(), count); }
    template <typename Iter>
    List(const Iter& first, const Iter& last) { init(); insert(begin(),first, last); }
    List(const List& other) { init(), insert(begin(), other.begin(), other.end()); };
    List(List&& other) : head(other.head), numberOfElements(other.numberOfElements) { other.init(); }
    List(const std::initializer_list<T>& il) { init(); insert(begin(), il.begin(), il.end()); }
    template <int N> List(const T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }
    template <int N> List(T(&other)[N]) { init(); insert(begin(), std::begin(other), std::end(other)); }

    // Assignment ---------------------
    List& operator =(const List& other) { clear(); insert(begin(), other.begin(), other.end()); return *this; }
    List& operator =(List&& other) { clear(); head = other.head; numberOfElements = other.numberOfElements; other.init(); return *this; }
    List& operator =(const std::initializer_list<T>& il) { clear(); insert(begin(),il.begin(),il.end()); return *this; }
    template <int N> List& operator =(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> List& operator =(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this;}

    void assign(const size_t count, const T& value) { clear(); insert(begin(), count, value); }
    void assign(const std::initializer_list<T>& il) { clear(); insert(begin(), il.begin(), il.end()); }
    template <typename Iter> void assign(const Iter& first, const Iter& last) { clear(); insert(begin(), first, last);}
    template <int N> void assign(const T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }
    template <int N> void assign(T(&other)[N]) { clear(); insert(begin(), std::begin(other), std::end(other)); return *this; }

    // Destructor ---------------------
    ~List() { clear(); }

    // Element Access -----------------
    T& front() { return *begin(); }
    T& back() { return *(--end()); }

    // Iterators ----------------------
    iterator begin() const { return iterator(head->next, head); }
    iterator end() const { return iterator(head, head); }

    // Capacity -----------------------
    size_t size() const { return numberOfElements; }
    bool empty() { return size() == 0; }

    // Modifiers ----------------------
    void clear();

    iterator insert(const iterator& insertBeforePosition, const T& value);
    iterator insert(const iterator& insertBeforePosition);
    template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool> = true>
    iterator insert(const iterator& insertBeforePosition, const Iter& first, const Iter& last);
    iterator insert(const iterator& insertBeforePosition, const size_t& count, const T& value);
    iterator insert(const iterator& insertBeforePosition, const std::initializer_list<T>& il);

    iterator erase(const iterator& posToDelete);
    iterator erase(const iterator& first, const iterator& last);

    void push_back(const T& d) { insert(end(), d); }
    void pop_back() { erase(--end()); };

    void push_front(const T& d) { insert(begin(), d); }
    void pop_front() { erase(begin()); };

    void resize(size_t count);
    void resize(size_t count, const T& value);

    void swap(List& other) { std::swap(head, other.head); std::swap(numberOfElements, other.numberOfElements); }

     // Operations --------------------
    void reverse();

    // Non standard inefficient functions --------------------------
    T& operator[](const size_t index) const { return begin()[index]; }

    // ------------------------------------------------------------------------
    // Define iterator capability ---------------------------------------------
    struct iterator {

        // Definitions ----------------
        using iterator_category = std::bidirectional_iterator_tag;
        using difference_type = std::ptrdiff_t;
        using value_type = T;
        using pointer = T*;
        using reference = T&;

        // Data -----------------------
        Node* iter{};
        Node* head{};

        // Constructor ----------------
        iterator(Node*const node, Node* const h) : iter(node), head(h) {};
        iterator() {};

        // Dereferencing --------------
        reference operator*() const { return iter->data; }
        reference operator->() const { return &**this; }

        // Arithmetic operations ------
        iterator operator++() { if (iter != head) iter = iter->next; return *this; }
        iterator operator++(int) { iterator tmp = *this; ++* this; return tmp; }
        iterator operator--() { if (iter != head->next) iter = iter->previous; return *this; }
        iterator operator--(int) { iterator tmp = *this; --* this; return tmp; }

        iterator operator +(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)++temp; else while (k++)--temp; return temp;
        }
        iterator operator +=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)++* this; else while (k++)--* this; return *this;
        };
        iterator operator -(const difference_type& n) const {
            iterator temp{ *this };  difference_type k{ n }; if (k > 0) while (k--)--temp; else while (k++)++temp; return temp;
        }
        iterator operator -=(const difference_type& n) {
            difference_type k{ n }; if (k > 0) while (k--)--* this; else while (k++)++* this; return *this;
        };
        // Comparison -----------------
        bool operator ==(const iterator& other) const { return iter == other.iter; };
        bool operator !=(const iterator& other) const { return iter != other.iter; };
        bool operator < (const iterator& other) const { return other.iter - iter < 0; };
        bool operator <= (const iterator& other) const { return other.iter - iter <= 0; };
        bool operator > (const iterator& other) const { return other.iter - iter > 0; };
        bool operator >= (const iterator& other) const { return other.iter - iter >= 0; };

        // Special non standard functions -----------------
        difference_type operator-(const iterator& other) const;
        reference operator[] (const size_t index);
    };
};

// ------------------------------------------------------------------------------------------------
// Implementation of list functions. This would normally go into a TCC file -----------------------

// List class functions ---------------
template <typename T>
void List<T>::clear() {

    for (Node* nextNode{}, * currentNode(head->next); currentNode != head; currentNode = nextNode) {
        nextNode = currentNode->next;
        delete currentNode;
    }
    init();
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const T& value)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous, value);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}
template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition)
{
    Node* nodeInsertBeforePosition = insertBeforePosition.iter;
    Node* newNode = new Node(nodeInsertBeforePosition, nodeInsertBeforePosition->previous);
    nodeInsertBeforePosition->previous = newNode;
    (newNode->previous)->next = newNode;
    ++numberOfElements;
    return iterator(newNode, head);
}

template <typename T>
template <class Iter, std::enable_if_t<is_iterator<Iter>::value, bool>>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const Iter& first, const Iter& last) {
    iterator result(insertBeforePosition.iter, head);
    if (first != last) {
        result = insert(insertBeforePosition, *first);
        Iter i(first);
        for (++i; i != last; ++i)
            insert(insertBeforePosition, *i);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const size_t& count, const T& value) {

    iterator result(insertBeforePosition.iter, head);
    if (count != 0u) {
        result = insert(insertBeforePosition, value);
        for (size_t i{ 1u }; i < count; ++i)
            insert(insertBeforePosition, value);
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::insert(const List<T>::iterator& insertBeforePosition, const std::initializer_list<T>& il) {
    return insert(insertBeforePosition, il.begin(), il.end());
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& posToDelete) {

    iterator result = posToDelete;
    ++result;

    Node* nodeToDelete = posToDelete.iter;

    if (nodeToDelete != head) {

        nodeToDelete->previous->next = nodeToDelete->next;
        nodeToDelete->next->previous = nodeToDelete->previous;

        delete nodeToDelete;
        --numberOfElements;
    }
    return result;
}

template <typename T>
typename List<T>::iterator List<T>::erase(const List<T>::iterator& first, const List<T>::iterator& last) {
    iterator result{ end() };
    if (first == begin() && last == end())
        clear();
    else {
        while (first != last)
            first = erase(first);
        result = last;
    }
    return result;
}

template <typename T>
void List<T>::resize(size_t count) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end());
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::resize(size_t count, const T& value) {
    if (numberOfElements < count)
        for (size_t i{ numberOfElements }; i < count; ++i)
            insert(end(),value);
    else
        while (count--)
            pop_back();
}
template <typename T>
void List<T>::reverse() {
    const Node* oldHead = head;

    for (Node* nptr = head; ; nptr = nptr->previous) {
        std::swap(nptr->next, nptr->previous);
        if (nptr->previous == oldHead) // Previous was the original next
            break;
    }
}

// ------------------------------------
// Iterator functions -----------------
template <typename T>
typename List<T>::iterator::difference_type List<T>::iterator::operator-(const iterator& other) const {

    difference_type result{};
    Node* nptr = head;

    int indexThis{ -1 }, indexOther{ -1 }, index{};

    do {
        nptr = nptr->next;
        if (nptr == iter)
            indexThis = index;
        if (nptr == other.iter)
            indexOther = index;
        ++index;
    } while (nptr != head);

    if (indexThis >= 0 and indexOther >= 0)
        result = indexThis - indexOther;
    return result;
}
template <typename T>
typename List<T>::iterator::reference List<T>::iterator::operator[] (const size_t index) {
    Node* nptr = head->next;
    for (size_t i{}; i < index and nptr != head; ++i, nptr = nptr->next)
        ;
    return nptr->data;
}

// ------------------------------------------------------------------------------------------------
// This would be in a cpp file --------------------------------------------------------------------
int main() {

    // std::list works
    std::list<int> list1{ 1, 2, 3, 4, 5 };
    std::cout << std::distance(list1.end(), list1.begin()) << '\n';

    // Custom list
    List<int> list2{ 1, 2, 3, 4, 5 };

    // Delta works
    std::cout << list2.begin() - list2.end() << '\n';
    std::cout << list2.end() - list2.begin() << '\n';

    // Hopp Count works
    List<int>::iterator i = list2.end();
    int counter = 0;
    while (i != list2.end()) {
        ++counter;
        ++i;
    }
    std::cout << counter << '\n';

    // Distance will go into endless loop ****************************
    std::cout << std::distance(list2.end(), list2.begin()) << '\n';
}

Body:
This:

// Distance will go into endless loop ****************************
std::cout << std::distance(list2.end(), list2.begin()) << '\n';

should be:

// Distance will go into endless loop ****************************
std::cout << std::distance(list2.begin(), list2.end()) << '\n';

What you do here is start from the end and increase the iterator until it reaches the beginning. This is an endless loop


问:
How do I pass a variable from one Thread Group to another in JMeter
I have a JMeter test with 2 Thread Groups - the first is a single thread (which creates some inventory) and the second has multiple threads (which purchase all the inventory). I use BeanShell Assertions and XPath Extractors to parse the returned value (which is XML) and store variables (such as the ids of the items to be purchased).

But, values that are created in the first Thread Group, whether extracted into standard ${jmeter} type variables, or ${__BeanShell(vars.get("jmeter"))} type vars, are not available in the second Thread Group. Is there anyway to create a variable in the first Thread Group and make it visible to the second?

答:
I was not able to do this with variables (since those are local to individual threads). However, I was able to solve this problem with properties!

Again, my first ThreadGroup does all of the set up, and I need some information from that work to be available to each of the threads in the second ThreadGroup. I have a BeanShell Assertion in the first ThreadGroup with the following:

```<code>${__setProperty(storeid, ${storeid})};
</code>```

The ${storeid} was extracted with an XPath Extractor. The BeanShell Assertion does other stuff, like checking that storeid was returned from the previous call, etc.

Anyway, in the second ThreadGroup, I can use the value of the "storeid" property in Samplers with the following:

```<code>${__property(storeid)}
</code>```

Works like a charm!

OwnerDisplayName: Todd R

Body:
I was not able to do this with variables (since those are local to individual threads). However, I was able to solve this problem with properties!

Again, my first ThreadGroup does all of the set up, and I need some information from that work to be available to each of the threads in the second ThreadGroup. I have a BeanShell Assertion in the first ThreadGroup with the following:

${__setProperty(storeid, ${storeid})};

The ${storeid} was extracted with an XPath Extractor. The BeanShell Assertion does other stuff, like checking that storeid was returned from the previous call, etc.

Anyway, in the second ThreadGroup, I can use the value of the "storeid" property in Samplers with the following:

${__property(storeid)}

Works like a charm!

ContentLicense: CC BY-SA 2.5


问:
How to escape double quotes in JSTL function / EL?
I need to change " to \" with JSTL replace function to use the string in input tag like:

```<code><input type="hidden" name="text" size="40" value="${text}">
</code>```

If the ${text} has the ", the HTML will be broken.

So I tried

```<code><input type="hidden" name="text" size="40" value="${fn:replace(text, "\"", "\\\""}">
</code>```

and

```<code><input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '\"'}">
</code>```

but didn't worked. The page makes errors like

org.apache.el.parser.ParseException: Encountered " "}" "} "" at line
  1, column 32. Was expecting one of:
      "." ...
      ")" ...
      "[" ...
      "," ...
      ">" ...
      "gt" ...
      "<" ...
      "lt" ...
      ">=" ...
      "ge" ...
      "<=" ...
      "le" ...
      "==" ...
      "eq" ...
      "!=" ...
      "ne" ...
      "&&" ...
      "and" ...
      "||" ...
      "or" ...
      "*" ...
      "+" ...
      "-" ...
      "/" ...
      "div" ...
      "%" ...
      "mod" ...

How can I do this?

Update

I missed a close paren of replace function. The right one was this one with a close paren:

```<code><input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '\"')}">
</code>```

Update2

I found out that when posting texts, using \ is not a good idea because of this reason why can't use \" in HTML input tag?. The code should be like this:

```<code><input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '"')}">
</code>```

答:
You may have a typo: I don't see a closing paren in there. Try this:

```<code>${fn:replace(news.title, "\"", "\\\"")}
</code>```

Also, are you trying to OUTPUT the results or are you trying to update news.title so the next time you access news.title the replacement is in place? This will work to output the result, but not to replace the actual value: news.title will not be changed by this call.

Body:
I need to change " to \" with JSTL replace function to use the string in input tag like:

<input type="hidden" name="text" size="40" value="${text}">

If the ${text} has the ", the HTML will be broken.

So I tried

<input type="hidden" name="text" size="40" value="${fn:replace(text, "\"", "\\\""}">

and

<input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '\"'}">

but didn't worked. The page makes errors like

org.apache.el.parser.ParseException: Encountered " "}" "} "" at line
  1, column 32. Was expecting one of:
      "." ...
      ")" ...
      "[" ...
      "," ...
      ">" ...
      "gt" ...
      "<" ...
      "lt" ...
      ">=" ...
      "ge" ...
      "<=" ...
      "le" ...
      "==" ...
      "eq" ...
      "!=" ...
      "ne" ...
      "&&" ...
      "and" ...
      "||" ...
      "or" ...
      "*" ...
      "+" ...
      "-" ...
      "/" ...
      "div" ...
      "%" ...
      "mod" ...

How can I do this?

Update

I missed a close paren of replace function. The right one was this one with a close paren:

<input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '\"')}">

Update2

I found out that when posting texts, using \ is not a good idea because of this reason why can't use \" in HTML input tag?. The code should be like this:

<input type="hidden" name="text" size="40" value="${fn:replace(text, '"', '"')}">

Body:
You may have a typo: I don't see a closing paren in there. Try this:

${fn:replace(news.title, "\"", "\\\"")}

Also, are you trying to OUTPUT the results or are you trying to update news.title so the next time you access news.title the replacement is in place? This will work to output the result, but not to replace the actual value: news.title will not be changed by this call.


问:
Anagrams finder in javascript
I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.:

monk, konm, nkom, bbc, cbb, dell, ledl, llde

The output should be categorised into rows:

```<code>1. monk konm, nkom;
2. bbc cbb;
3. dell ledl, llde;
</code>```

I already sorted them into alphabetical order and put them into an array. i.e.:

kmno kmno bbc bbc dell dell

However I am stuck in comparing and finding the matching anagram within the array.

Any help will be greatly appreciated.

答:
Here, I would first convert list of words in to anagram object. I am pushing anagram words in to new object where key is anagram. if anagram is already found in the object then I would concat the new word.

At last I am just taking out the values of result object. Code is self explanatory and short.

```<code>const input = "monk, konm, nkom, bbc, cbb, dell, ledl, llde";

const anagramCreater = (data) => { return data.split("").sort().join("");}

const anagram = input
.split(", ")
.reduce((acc, word) => {
  const anagramWord = anagramCreater(word);
  acc[anagramWord] = acc[anagramWord]
    ? `${acc[anagramWord]},${word}`
    : word;
  return acc;
}, {});
console.log(Object.values(anagram).join("\n"));
</code>```

Title: Anagrams finder in javascript

Body:
I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.:

monk, konm, nkom, bbc, cbb, dell, ledl, llde

The output should be categorised into rows:

1. monk konm, nkom;
2. bbc cbb;
3. dell ledl, llde;

I already sorted them into alphabetical order and put them into an array. i.e.:

kmno kmno bbc bbc dell dell

However I am stuck in comparing and finding the matching anagram within the array.

Any help will be greatly appreciated.

Body:
Here, I would first convert list of words in to anagram object. I am pushing anagram words in to new object where key is anagram. if anagram is already found in the object then I would concat the new word.

At last I am just taking out the values of result object. Code is self explanatory and short.

const input = "monk, konm, nkom, bbc, cbb, dell, ledl, llde";

const anagramCreater = (data) => { return data.split("").sort().join("");}

const anagram = input
.split(", ")
.reduce((acc, word) => {
  const anagramWord = anagramCreater(word);
  acc[anagramWord] = acc[anagramWord]
    ? `${acc[anagramWord]},${word}`
    : word;
  return acc;
}, {});
console.log(Object.values(anagram).join("\n"));


问:
Oracle Oracle hierarchical query to disable foreign keys
I have some code (see below), which uses a hierarchical query that traverses down a table to find all the related Foriegn keys. This seems to be working fine.

Can this be modified not to display the top level table, in this case the TABLE_NAME='PARENT' as I want to wrap this code in PL/SQL in order to create the desired syntax to enable/disable Foriegn keys for all the descendants of a table.

In my example, I have 3 tables. A grandchild table, which REFERENCES a child table and a child table, which REFERENCES the parent table, which is the master table.

The reason for this is to clean up some massive tables and I am trying to figure out the most effective and efficient way to go about this exercise.

We don't have CASCADE DELETE setup as that is too dangerous and some people learned that the hard way unfortunately.

Below is my test case and expected results, which I plan to execute in a procedure.

create table parent (
  id NUMBER(10),
  value      varchar2(30),
constraint parent_pk primary key (id)
);

CREATE TABLE child
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint child_pk primary key (id,value),
CONSTRAINT parent_child_fk
FOREIGN KEY (id)
REFERENCES parent(id));

CREATE TABLE grandchild
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint grandchild_pk primary key (id,value),
CONSTRAINT child_grandchild_fk
FOREIGN KEY (id,value)
REFERENCES child(id,value));

insert into parent values (1,'a');
insert into parent values (2,'b');
insert into parent values (3,'c');

insert into child  values (1,1);
insert into child  values (1,2);
insert into child  values (1,3);
insert into child  values (2,1);
insert into child  values (2,2);
insert into child  values (2,3);
insert into child  values (3,1);
insert into child  values (3,2);
insert into child  values (3,3);

insert into grandchild  values (1,1);
insert into grandchild  values (1,2);
insert into grandchild  values (1,3);
insert into grandchild  values (2,1);
insert into grandchild  values (2,2);
insert into grandchild  values (2,3);
insert into grandchild  values (3,1);
insert into grandchild  values (3,2);
insert into grandchild  values (3,3);
```
<p>In the query I hard code the column name ID.</p>
<p>If possible, I would like to figure it out else I can live with the hard coded value.</p>
<pre class="lang-sql prettyprint-override"><code>select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type
from (
    SELECT uc.table_name,
    uc.constraint_name,
    cols.column_name,
    (select table_name from user_constraints where constraint_name = uc.r_constraint_name)
        r_table_name,
    (select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position)
        r_column_name,
    cols.position,
    uc.constraint_type
    FROM user_constraints uc
    inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name
    where constraint_type != 'C'
)
start with table_name = 'PARENT' and column_name = 'ID'
connect by nocycle
prior table_name = r_table_name
and prior column_name = r_column_name;
</code>```

TABLE_NAME
CONSTRAINT_NAME
COLUMN_NAME
R_TABLE_NAME
POSITION
CONSTRAINT_TYPE

PARENT
PARENT_PK
ID
-
1
P

GRANDCHILD
CHILD_GRANDCHILD_FK
ID
CHILD
1
R

CHILD
PARENT_CHILD_FK
ID
PARENT
1
R

Expected results for my test CASE is to generate this syntax:

alter table CHILD disable constraint PARENT_CHILD_FK;
alter table GRANDCHILD disable constraint CHILD_GRANDCHILD_FK;
```

答:
You can use:

SELECT 'ALTER TABLE "' || u.owner || '"."' || u.table_name || '" '
       || 'DISABLE CONSTRAINT "' || u.constraint_name || '"' AS statement
FROM   user_constraints u
       INNER JOIN user_constraints r
       ON (   u.constraint_type = 'R'
          AND r.constraint_type IN ('P', 'U')
          AND u.r_owner = r.owner
          AND u.r_constraint_name = r.constraint_name)
START WITH r.table_name       = 'PARENT'
CONNECT BY PRIOR u.owner      = r.owner
AND        PRIOR u.table_name = r.table_name;
```

db<>fiddle here

Body:
I have some code (see below), which uses a hierarchical query that traverses down a table to find all the related Foriegn keys. This seems to be working fine.

Can this be modified not to display the top level table, in this case the TABLE_NAME='PARENT' as I want to wrap this code in PL/SQL in order to create the desired syntax to enable/disable Foriegn keys for all the descendants of a table.

In my example, I have 3 tables. A grandchild table, which REFERENCES a child table and a child table, which REFERENCES the parent table, which is the master table.

The reason for this is to clean up some massive tables and I am trying to figure out the most effective and efficient way to go about this exercise.

We don't have CASCADE DELETE setup as that is too dangerous and some people learned that the hard way unfortunately.

Below is my test case and expected results, which I plan to execute in a procedure.

create table parent (
  id NUMBER(10),
  value      varchar2(30),
constraint parent_pk primary key (id)
);

CREATE TABLE child
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint child_pk primary key (id,value),
CONSTRAINT parent_child_fk
FOREIGN KEY (id)
REFERENCES parent(id));

CREATE TABLE grandchild
( id NUMBER(10) not null,
value NUMBER(10) not null,
constraint grandchild_pk primary key (id,value),
CONSTRAINT child_grandchild_fk
FOREIGN KEY (id,value)
REFERENCES child(id,value));

insert into parent values (1,'a');
insert into parent values (2,'b');
insert into parent values (3,'c');

insert into child  values (1,1);
insert into child  values (1,2);
insert into child  values (1,3);
insert into child  values (2,1);
insert into child  values (2,2);
insert into child  values (2,3);
insert into child  values (3,1);
insert into child  values (3,2);
insert into child  values (3,3);

insert into grandchild  values (1,1);
insert into grandchild  values (1,2);
insert into grandchild  values (1,3);
insert into grandchild  values (2,1);
insert into grandchild  values (2,2);
insert into grandchild  values (2,3);
insert into grandchild  values (3,1);
insert into grandchild  values (3,2);
insert into grandchild  values (3,3);

In the query I hard code the column name ID.

If possible, I would like to figure it out else I can live with the hard coded value.

select distinct table_name, constraint_name, column_name, r_table_name, position, constraint_type
from (
    SELECT uc.table_name,
    uc.constraint_name,
    cols.column_name,
    (select table_name from user_constraints where constraint_name = uc.r_constraint_name)
        r_table_name,
    (select column_name from user_cons_columns where constraint_name = uc.r_constraint_name and position = cols.position)
        r_column_name,
    cols.position,
    uc.constraint_type
    FROM user_constraints uc
    inner join user_cons_columns cols on uc.constraint_name = cols.constraint_name
    where constraint_type != 'C'
)
start with table_name = 'PARENT' and column_name = 'ID'
connect by nocycle
prior table_name = r_table_name
and prior column_name = r_column_name;

TABLE_NAME
CONSTRAINT_NAME
COLUMN_NAME
R_TABLE_NAME
POSITION
CONSTRAINT_TYPE

PARENT
PARENT_PK
ID
-
1
P

GRANDCHILD
CHILD_GRANDCHILD_FK
ID
CHILD
1
R

CHILD
PARENT_CHILD_FK
ID
PARENT
1
R

Expected results for my test CASE is to generate this syntax:

alter table CHILD disable constraint PARENT_CHILD_FK;
alter table GRANDCHILD disable constraint CHILD_GRANDCHILD_FK;

Body:
You can use:

SELECT 'ALTER TABLE "' || u.owner || '"."' || u.table_name || '" '
       || 'DISABLE CONSTRAINT "' || u.constraint_name || '"' AS statement
FROM   user_constraints u
       INNER JOIN user_constraints r
       ON (   u.constraint_type = 'R'
          AND r.constraint_type IN ('P', 'U')
          AND u.r_owner = r.owner
          AND u.r_constraint_name = r.constraint_name)
START WITH r.table_name       = 'PARENT'
CONNECT BY PRIOR u.owner      = r.owner
AND        PRIOR u.table_name = r.table_name;

db<>fiddle here


问:
Running Flutter Web integration tests inside gitlab (probably github too) Ubuntu VM fails because of Chromedriver
I am trying to run integration tests for Web inside gitlab VM.
The VM is running Ubuntu 20.04.3 LTS.
Chromedriver is launched with this command line:

chromedriver -port=4444 --enable-chrome-logs
```
<p>The error from the chromedriver output is:</p>
```[0131/212240.342700:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
[0131/212240.347411:ERROR:command_buffer_proxy_impl.cc(125)] ContextResult::kTransientFailure: Failed to send GpuControl.CreateCommandBuffer.
[0131/212241.926360:INFO:CONSOLE(65)] "Installed new service worker.", source: http://localhost:8080/ (65)
[0131/212242.084358:ERROR:broker_posix.cc(46)] Received unexpected number of handles
```
<p>Using chrome 97 or 97 along with chromedriver 97 or 98 gives the same error.</p>
<p>Flutter integration tests is launch using this command:</p>
<pre class="lang-sh prettyprint-override"><code>flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d web-server --headless
</code>```

InitializeSandbox() called with multiple threads in process is know issue and is fixable using the flag --disable-gpu but until know, i haven't found any solution to disable gpu from within the Flutter CLI or by configuring the FlutterDriver.

Any idea on how to solve this problem?
thanks

答:
the --release flag has to be given to the command line.
So the command should look like:</p>
```<code>flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d web-server --release
</code>```

Body:
I am trying to run integration tests for Web inside gitlab VM.
The VM is running Ubuntu 20.04.3 LTS.
Chromedriver is launched with this command line:

chromedriver -port=4444 --enable-chrome-logs

The error from the chromedriver output is:

[0131/212240.342700:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
[0131/212240.347411:ERROR:command_buffer_proxy_impl.cc(125)] ContextResult::kTransientFailure: Failed to send GpuControl.CreateCommandBuffer.
[0131/212241.926360:INFO:CONSOLE(65)] "Installed new service worker.", source: http://localhost:8080/ (65)
[0131/212242.084358:ERROR:broker_posix.cc(46)] Received unexpected number of handles

Using chrome 97 or 97 along with chromedriver 97 or 98 gives the same error.

Flutter integration tests is launch using this command:

flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d web-server --headless

InitializeSandbox() called with multiple threads in process is know issue and is fixable using the flag --disable-gpu but until know, i haven't found any solution to disable gpu from within the Flutter CLI or by configuring the FlutterDriver.

Any idea on how to solve this problem?
thanks

Body:
the --release flag has to be given to the command line.
So the command should look like:

flutter drive --driver=test_driver/integration_test.dart --target=integration_test/app_test.dart -d web-server --release