问:
Laravel reject function on nested collection
I am trying to iterate my collection, which has nested collections, with the collection reject() function and return the original collection with the updated nested data.

So this is my quiz collection

```<code>{
 "id": 1,
 "title": "quiz 1",
 "questions": [
     {
         "id": 1,
         "quiz_id": 1,
         "question": "q1 - q1",
         "answers": [
             {
                 "id": 1,
                 "question_id": 1,
                 "answer": "answer to question 1"
             },
             {
                 "id": 2,
                 "question_id": 1,
                 "answer": "answer to question 1"
             }
         ]
     },
     {
         "id": 2,
         "quiz_id": 1,
         "question": "q1 - q2",
         "answers": [
             {
                 "id": 3,
                 "question_id": 2,
                 "answer": "answer to question 1"
             }
         ]
     }
 ]
}
</code>```

Now I want to iterate through the questions and reject those that were already answered and exist in the result collection. I do so by using the reject() function

```<code>$quizResults = [
    {
        "id": 1,
        "user_id": 1,
        "quiz_id": 1,
        "question_id": 1,
        "answer_id": 1,
        "correct": 1,
        "created_at": null,
        "updated_at": null
    }
];

$filtered = $quiz->questions->reject(function ($value, $key) use ($quizResult) {
   return $quizResult->contains('question_id', $value->id);
});
</code>```

I want to return the quiz collection with the updated questions (without the rejected questions), but I can't seem to figure out the correct way to accomplish this. (if i return just the $filtered variable i get the correct filtered results, however if i try putting it back in to the $quiz var it won't apply the rejected filter). If I just do

```<code>return $quiz
</code>```

I will get the same original collection with all the questions as if I never ran the reject() function.

How do I make the $quiz->questions = $filtered; ?

答:
I had to unset the $quiz['questions'] first so it was like this

```<code>unset($quiz['questions']);
$quiz['questions'] = $filtered->flatten();
return $quiz;
</code>```

and the result was as intended:

```<code>{
    "id": 1,
    "title": "quiz 1",
    "questions": [
        {
            "id": 2,
            "quiz_id": 1,
            "question": "q1 - q2",
            "answers": [
                {
                    "id": 3,
                    "question_id": 2,
                    "answer": "answer to question 1"
                }
            ]
        }
    ]
}
</code>```

Body:
I am trying to iterate my collection, which has nested collections, with the collection reject() function and return the original collection with the updated nested data.

So this is my quiz collection

{
 "id": 1,
 "title": "quiz 1",
 "questions": [
     {
         "id": 1,
         "quiz_id": 1,
         "question": "q1 - q1",
         "answers": [
             {
                 "id": 1,
                 "question_id": 1,
                 "answer": "answer to question 1"
             },
             {
                 "id": 2,
                 "question_id": 1,
                 "answer": "answer to question 1"
             }
         ]
     },
     {
         "id": 2,
         "quiz_id": 1,
         "question": "q1 - q2",
         "answers": [
             {
                 "id": 3,
                 "question_id": 2,
                 "answer": "answer to question 1"
             }
         ]
     }
 ]
}

Now I want to iterate through the questions and reject those that were already answered and exist in the result collection. I do so by using the reject() function

$quizResults = [
    {
        "id": 1,
        "user_id": 1,
        "quiz_id": 1,
        "question_id": 1,
        "answer_id": 1,
        "correct": 1,
        "created_at": null,
        "updated_at": null
    }
];

$filtered = $quiz->questions->reject(function ($value, $key) use ($quizResult) {
   return $quizResult->contains('question_id', $value->id);
});

I want to return the quiz collection with the updated questions (without the rejected questions), but I can't seem to figure out the correct way to accomplish this. (if i return just the $filtered variable i get the correct filtered results, however if i try putting it back in to the $quiz var it won't apply the rejected filter). If I just do

return $quiz

I will get the same original collection with all the questions as if I never ran the reject() function.

How do I make the $quiz->questions = $filtered; ?

Body:
I had to unset the $quiz['questions'] first so it was like this

unset($quiz['questions']);
$quiz['questions'] = $filtered->flatten();
return $quiz;

and the result was as intended:

{
    "id": 1,
    "title": "quiz 1",
    "questions": [
        {
            "id": 2,
            "quiz_id": 1,
            "question": "q1 - q2",
            "answers": [
                {
                    "id": 3,
                    "question_id": 2,
                    "answer": "answer to question 1"
                }
            ]
        }
    ]
}


来源: stackexchange

问:
Tree implementation in C++: Cannot convert Node to int* Ask Question
I'm currently working on my homework. Below is the program for construction of binary tree which I wrote. I'm getting the error that, "cannot convert 'node' to 'int*' in assignment". Can you please help me out here?**

```<code>#include<iostream>
#include<conio.h>

struct node
{
    char data;
    int *left,*right;
};

int main()
{
    node *T; //ROOT of tree
    node *p,*q; //address of first node in T
    T=new node;
    T->left=NULL;
    T->right=NULL;
    T->data='A';

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='B';
    T->left=&p;

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='C';
    T->right=&p;

    q=new node;
    q->left=NULL;
    q->right=NULL;
    q->data='D';
    p->left=&q;

    return 0;
}```
```

答:
Change your structure as @TarekD suggested, the problem is you are trying to cast a node* into an int* </p>

```<code>T->left=&p;

T->right=&p;

p->left=&q;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently working on my homework. Below is the program for construction of binary tree which I wrote. I'm getting the error that, "cannot convert 'node' to 'int*' in assignment". Can you please help me out here?**

#include<iostream>
#include<conio.h>

struct node
{
    char data;
    int *left,*right;
};

int main()
{
    node *T; //ROOT of tree
    node *p,*q; //address of first node in T
    T=new node;
    T->left=NULL;
    T->right=NULL;
    T->data='A';

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='B';
    T->left=&p;

    p=new node;
    p->left=NULL;
    p->right=NULL;
    p->data='C';
    T->right=&p;

    q=new node;
    q->left=NULL;
    q->right=NULL;
    q->data='D';
    p->left=&q;

    return 0;
}```

Body:
Change your structure as @TarekD suggested, the problem is you are trying to cast a node* into an int*

T->left=&p;

T->right=&p;

p->left=&q;


问:
Set Level for all java.util.logging Loggers programmatically
I work on an application which uses slf4j and log4j2 as the underlying logging framework. The application provides custom logging filters, based on the current user of the application. Some third party libraries use java.util.logging (JUL) internally. I would like those logs to also submit to my user based filter. I.e. while the default log level may be ERROR, I can configure the application to log on level DEBUG when an specific user is using it.

Therefore I integrated the jul-to-slf4j bridge so that JUL logging is redirected to slf4j. I've also created a custom java.util.logging.Filter as described here which implements my user based filter logic.

Now my problem is that the default log level in JUL seems to be INFO and there also is logic which first checks if the message to log has an less fine level than the level of the logger, in which case the message is rejected immediatly without passing through the filter (in this case my custom filter). Because of this I want all JUL Loggers (also the ones used in third party libraries) to by default have the level ALL so that all JUL log statements would pass through my filter where it would be determined wether to log the message or to discard it.

I've tried setting the JULs root logger and it's handlers level to ALL as it is described in multiple posts here on SO, but this didn't seem to make the trick as seen here. It looks like I have to configure the JUL LogManager accordingly and I wonder if I can do so programatically without introducing a new log file?

答:
From code you can reset all loggers using code like the following:

```<code>private static void resetLoggersToRoot() {
    Logger root = Logger.getLogger("");
    LogManager lm = LogManager.getLogManager();
    synchronized (lm) {
        Enumeration<String> e = lm.getLoggerNames();
        while (e.hasMoreElements()) {
            Logger l = lm.getLogger(e.nextElement());
            if (l != null && l != root) {
                l.setLevel(root.getLevel());
                l.setFilter(root.getFilter());
                l.setUseParentHandlers(root.getUseParentHandlers());
                for(Handler h : l.getHandlers()) {
                    l.removeHandler(h);
                }
            }
        }
    }
}
</code>```

However, there is a issue where loggers are created on demand.  Therefore you might have to call LogManager.getLogManager().reset(); to remove any existing configuration from a logging.properties file.

Body:
From code you can reset all loggers using code like the following:

private static void resetLoggersToRoot() {
    Logger root = Logger.getLogger("");
    LogManager lm = LogManager.getLogManager();
    synchronized (lm) {
        Enumeration<String> e = lm.getLoggerNames();
        while (e.hasMoreElements()) {
            Logger l = lm.getLogger(e.nextElement());
            if (l != null && l != root) {
                l.setLevel(root.getLevel());
                l.setFilter(root.getFilter());
                l.setUseParentHandlers(root.getUseParentHandlers());
                for(Handler h : l.getHandlers()) {
                    l.removeHandler(h);
                }
            }
        }
    }
}

However, there is a issue where loggers are created on demand.  Therefore you might have to call LogManager.getLogManager().reset(); to remove any existing configuration from a logging.properties file.


问:
JavaScript passing argument problem
I have following code

```<code>for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }
</code>```

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

答:
The closure answers given are the conventional way to solve your problem, but if you don't care for the self-invoking anonymous functions, you might consider using forEach():

```<code>that.$el.mini.forEach(function (element,i){
            var pag = element.pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }) ;
</code>```

Caveat: forEach() is not implemented in all browsers.  You can see how to shim it, as described under 'Compatibility' at https://developer.mozilla.org/en/JavaScript/Reference/global_objects/array/foreach

ContentLicense: CC BY-SA 3.0

Title: JavaScript passing argument problem

Body:
I have following code

for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

Body:
The closure answers given are the conventional way to solve your problem, but if you don't care for the self-invoking anonymous functions, you might consider using forEach():

that.$el.mini.forEach(function (element,i){
            var pag = element.pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }) ;

Caveat: forEach() is not implemented in all browsers.  You can see how to shim it, as described under 'Compatibility' at https://developer.mozilla.org/en/JavaScript/Reference/global_objects/array/foreach


问:
Overuse of try and except in python code when using regex
I think i am over using try and except in my code. It's pretty much everywhere, where i have regexp matching. If it does not find the regex, it throws an exception, so i use the try and except to capture this to prevent my code from crashing. Example of what i'm talking about.

```<code>try:
    Output = "John Bob Charlie"
    match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash
except:
    print("Darn, no John")
</code>```

Is there a better way of doing this or is this normal?? I'm new to Python and coming from Perl, a simple

```<code>if match{
print('we have found John')
}
</code>```

Was all i needed.

Thanks in advance

答:
You could simply use an if statement to check whether there is any match

```<code>Output = "John Bob Charlie"
match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash

if match:
    # Do Something here
else:
    print("Darn, no John")
</code>```

You could refer the regex documentation here where a simple if statement is used

Body:
I think i am over using try and except in my code. It's pretty much everywhere, where i have regexp matching. If it does not find the regex, it throws an exception, so i use the try and except to capture this to prevent my code from crashing. Example of what i'm talking about.

try:
    Output = "John Bob Charlie"
    match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash
except:
    print("Darn, no John")

Is there a better way of doing this or is this normal?? I'm new to Python and coming from Perl, a simple

if match{
print('we have found John')
}

Was all i needed.

Thanks in advance

Body:
You could simply use an if statement to check whether there is any match

Output = "John Bob Charlie"
match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash

if match:
    # Do Something here
else:
    print("Darn, no John")

You could refer the regex documentation here where a simple if statement is used


问:
Image hyperlink dimensions wrong
I am trying to add a hyperlink to an image and it works fine, but when I hover over the ... node in Chrome Dev Tools, it shows the wrong dimensions.

Dev Tools shows that the dimensions are 512x18 and it also shows the box model is nudged below the image by about 5 pixels or so.

I don't understand why this is happening or what is going on here. If I have a 512x512 pixel image, I want the hyperlink dimensions to be 512x512 pixels.

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

<p>I tried adding <code>WIDTH</code> and <code>HEIGHT</code> attributes to the image, but that didn't work. It seemed like the only way to get it to work was to add a defined CSS size to the surrounding <code><A>...</A></code> hyperlink element.</p>

```STYLE="display: inline-block; width: 512px; height: 512px"
```

Is there any other way of doing this without having to hardcode the dimensions of the image?

答: Making img tag to block and anchor tag to inline-block also makes both height to 512pixels</p>

Title: Image hyperlink dimensions wrong

Body:
I am trying to add a hyperlink to an image and it works fine, but when I hover over the ... node in Chrome Dev Tools, it shows the wrong dimensions.

Dev Tools shows that the dimensions are 512x18 and it also shows the box model is nudged below the image by about 5 pixels or so.

I don't understand why this is happening or what is going on here. If I have a 512x512 pixel image, I want the hyperlink dimensions to be 512x512 pixels.

I tried adding WIDTH and HEIGHT attributes to the image, but that didn't work. It seemed like the only way to get it to work was to add a defined CSS size to the surrounding ... hyperlink element.

STYLE="display: inline-block; width: 512px; height: 512px"

Is there any other way of doing this without having to hardcode the dimensions of the image?


问:
Is it possible to stop a job in Kubernetes without deleting it
Because Kubernetes handles situations where there's a typo in the job spec, and therefore a container image can't be found, by leaving the job in a running state forever, I've got a process that monitors job events to detect cases like this and deletes the job when one occurs.

I'd prefer to just stop the job so there's a record of it. Is there a way to stop a job?

答:
You can suspend cronjobs by using the suspend attribute. From the Kubernetes documentation:

https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/#suspend


问:
How do you access the query string in Flask routes?
How do you access query parameters or the query string in Flask routes? It's not obvious from the Flask documentation.

The example route /data below illustrates the context that I would like to access that data. If someone requests something like example.com/data?abc=123, I would like access to the string ?abc=123 or to be able to retrieve the value of parameters like abc.

```<code>@app.route("/data")
def data():
    # query_string = ???
    return render_template("data.html")
</code>```

答:
If the request if GET and we passed some query parameters then, </p>

```<code>fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)
</code>```

Body:
How do you access query parameters or the query string in Flask routes? It's not obvious from the Flask documentation.

The example route /data below illustrates the context that I would like to access that data. If someone requests something like example.com/data?abc=123, I would like access to the string ?abc=123 or to be able to retrieve the value of parameters like abc.

@app.route("/data")
def data():
    # query_string = ???
    return render_template("data.html")

Body:
If the request if GET and we passed some query parameters then,

fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)


问:
React native Ctrl M or dev tool not showing in my emulator
He thanks in advance,
In react native am not able to right click or open dev mode in emulator.</p>

答:
There is post which says turn off production mode -> it took me time to find in which settings -> I was looking in emulator settings, it was in expo-cli. This post is it clarify it.

Production mode off

In the expo-cli http://localhost:19002/, there is Production Mode (left side bar) -> turn it off

Open AVD Emulator and your application, press ctrl+M

It should work.


问:
Add SAML Authentication to .net WebAPI
I need to add SAML Authentication to my web application (WebAPI Back-End / Angular Front-End) with Azure AD as my Identity Provider.

I plan to use Sustainsys.Saml2 library but I'm not sure how to correctly use the methods that the library provide.

I already added my web app as an the Enterprise Application on Azure AD and performed the necessary SSO SAML configurations.

I have configured sustainsys in the web.config as following:

```<code><sustainsys.saml2 entityId="https://myWebApp/api/saml/login" returnUrl="https://myWebApp/">
  <identityProviders>
    <add
      entityId="https://sts.windows.net/36tg486z-9l1f/"
      signOnUrl="https://login.microsoftonline.com/36tg486z-9l1f/saml2"
      metadataLocation="https://login.microsoftonline.com/36tg486z-9l1f/federationmetadata/2007-06/federationmetadata.xml?appid=82fc2g56-2as2"
      allowUnsolicitedAuthnResponse="true"
      loadMetadata="true"
      binding="HttpPost"
    >
    </add>
  </identityProviders>
    <serviceCertificates>
        <add fileName="~/App_Data/Sustainsys.Saml2.Tests.pfx" />
  </serviceCertificates>
</sustainsys.saml2>
</code>```

My idea is to write two APIs:

1 - API that perform the sign in into Azure AD:

```<code>[HttpGet]
[Route("api/saml/signIn")]
[ResponseType(typeof(void))]
public HttpResponseMessage SignIn()
{
  var context = new HttpContextWrapper(HttpContext.Current);
  HttpRequestBase request = context.Request;

  var opt = Sustainsys.Saml2.Configuration.Options.FromConfiguration;
  var result = CommandFactory.GetCommand(CommandFactory.SignInCommandName).Run(request.ToHttpRequestData(), opt);
  var response = Request.CreateResponse(result.HttpStatusCode);

  if (!string.IsNullOrEmpty(result.SetCookieName))
  {
    var protectedData = HttpRequestData.ConvertBinaryData(MachineKey.Protect(result.GetSerializedRequestState(),HttpRequestBaseExtensions.ProtectionPurpose));

    var cookie = new CookieHeaderValue(result.SetCookieName, protectedData) { HttpOnly = true };
    var cookies = new List<CookieHeaderValue>() { cookie };
    response.Headers.AddCookies(cookies);
  }

  response.Headers.Location = result.Location;
  return response;
}
</code>```

2 - API that receive the response from Azure AD and reads the claims inside the SAML token:

```<code>[HttpPost]
[Route("api/saml/acs")]
[ResponseType(typeof(result))]
public HttpResponseMessage Acs()
{
  var context = new HttpContextWrapper(HttpContext.Current);
  HttpRequestBase request = context.Request;

  var opt = Sustainsys.Saml2.Configuration.Options.FromConfiguration;
  var result = CommandFactory.GetCommand(CommandFactory.AcsCommandName).Run(request.ToHttpRequestData(), opt);

  // ... read claims ...

  // ... build [LoginResult] with claims ...
  var response = Request.CreateResponse(result.HttpStatusCode, [LoginResult]);

  response.Headers.Location = new Uri(result.Location.AbsoluteUri);

  return response;
}
</code>```

Is this the correct way to add SAML authentication using SustainSys ?

答:
Here is a working example of WebApi + Angular Spa using SustainSys stub Idp. It can also be used with Azure AD configuration.

https://github.com/hmacat/Saml2WebAPIAndAngularSpaExample

Title: Add SAML Authentication to .net WebAPI

Body:
I need to add SAML Authentication to my web application (WebAPI Back-End / Angular Front-End) with Azure AD as my Identity Provider.

I plan to use Sustainsys.Saml2 library but I'm not sure how to correctly use the methods that the library provide.

I already added my web app as an the Enterprise Application on Azure AD and performed the necessary SSO SAML configurations.

I have configured sustainsys in the web.config as following:

<sustainsys.saml2 entityId="https://myWebApp/api/saml/login" returnUrl="https://myWebApp/">
  <identityProviders>
    <add
      entityId="https://sts.windows.net/36tg486z-9l1f/"
      signOnUrl="https://login.microsoftonline.com/36tg486z-9l1f/saml2"
      metadataLocation="https://login.microsoftonline.com/36tg486z-9l1f/federationmetadata/2007-06/federationmetadata.xml?appid=82fc2g56-2as2"
      allowUnsolicitedAuthnResponse="true"
      loadMetadata="true"
      binding="HttpPost"
    >
    </add>
  </identityProviders>
    <serviceCertificates>
        <add fileName="~/App_Data/Sustainsys.Saml2.Tests.pfx" />
  </serviceCertificates>
</sustainsys.saml2>

My idea is to write two APIs:

1 - API that perform the sign in into Azure AD:

[HttpGet]
[Route("api/saml/signIn")]
[ResponseType(typeof(void))]
public HttpResponseMessage SignIn()
{
  var context = new HttpContextWrapper(HttpContext.Current);
  HttpRequestBase request = context.Request;

  var opt = Sustainsys.Saml2.Configuration.Options.FromConfiguration;
  var result = CommandFactory.GetCommand(CommandFactory.SignInCommandName).Run(request.ToHttpRequestData(), opt);
  var response = Request.CreateResponse(result.HttpStatusCode);

  if (!string.IsNullOrEmpty(result.SetCookieName))
  {
    var protectedData = HttpRequestData.ConvertBinaryData(MachineKey.Protect(result.GetSerializedRequestState(),HttpRequestBaseExtensions.ProtectionPurpose));

    var cookie = new CookieHeaderValue(result.SetCookieName, protectedData) { HttpOnly = true };
    var cookies = new List<CookieHeaderValue>() { cookie };
    response.Headers.AddCookies(cookies);
  }

  response.Headers.Location = result.Location;
  return response;
}

2 - API that receive the response from Azure AD and reads the claims inside the SAML token:

[HttpPost]
[Route("api/saml/acs")]
[ResponseType(typeof(result))]
public HttpResponseMessage Acs()
{
  var context = new HttpContextWrapper(HttpContext.Current);
  HttpRequestBase request = context.Request;

  var opt = Sustainsys.Saml2.Configuration.Options.FromConfiguration;
  var result = CommandFactory.GetCommand(CommandFactory.AcsCommandName).Run(request.ToHttpRequestData(), opt);

  // ... read claims ...

  // ... build [LoginResult] with claims ...
  var response = Request.CreateResponse(result.HttpStatusCode, [LoginResult]);

  response.Headers.Location = new Uri(result.Location.AbsoluteUri);

  return response;
}

Is this the correct way to add SAML authentication using SustainSys ?


问:
How can i get text from display none Element using java selenium

I need to get text of the element in an image but that element is not displaying on a web page.

答:
You can try something like this, and give id to your element </p>

```<code>JavascriptExecutor executor = (JavascriptExecutor)driver;
 String text= executor.executeScript("document.getElementById('someID').innerHTML");
</code>```

<p>as earlier @Andreas mention be more descriptive. Good luck. Hope it helps </p>

Body:
You can try something like this, and give id to your element

JavascriptExecutor executor = (JavascriptExecutor)driver;
 String text= executor.executeScript("document.getElementById('someID').innerHTML");

as earlier @Andreas mention be more descriptive. Good luck. Hope it helps


问:
Can I import others git repository to my repository?
I find a lot of good sources in Git. Instead of bookmarking the page I like to import others repository into my repository.
Is this allowed?
Is this what people do usually?
Is the other user notified when I import from his repository?
Is he notified for any changes that I make on my imported repository?
When I import, I see that all the commit history and the contributor in my repository.</p>

答:
People just Fork repositories.

A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project.


问:
The view above recyclerview is skipped
I have CardView above RecycleView, but when Page is loaded RecyclerView is  on the top and CardView is skipped. Why can this happen?</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/homeProgress"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:progressTint="@color/colorText"
            android:visibility="visible"/>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/homeMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
            android:padding="10dp"
            android:visibility="gone">

            <androidx.cardview.widget.CardView
                android:id="@+id/firstPlace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorCardView"
                app:cardCornerRadius="10dp"
                android:padding="10dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="10dp">

                        <TextView
                            android:id="@+id/firstPlaceName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="30sp"
                            android:textColor="@color/colorText"/>

                        <TextView
                            android:id="@+id/firstPlaceCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="15sp"
                            android:textColor="@color/colorText"/>

                    </LinearLayout>

                    <ImageView
                        android:id="@+id/firstPlaceImage"
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_alignParentEnd="true"/>

                </RelativeLayout>
            </androidx.cardview.widget.CardView>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/artistsWithImagesRecycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/firstPlace"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:overScrollMode="never"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">

            </androidx.recyclerview.widget.RecyclerView>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</code>```

答: You have set the ConstraintLayout with id homeMainLayout to be "gone". Remove the attribute  android:visibility="gone" from it and the card view will be shown as you expect.</p>

Title: The view above recyclerview is skipped

Body:
I have CardView above RecycleView, but when Page is loaded RecyclerView is  on the top and CardView is skipped. Why can this happen?

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/homeProgress"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:progressTint="@color/colorText"
            android:visibility="visible"/>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/homeMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
            android:padding="10dp"
            android:visibility="gone">

            <androidx.cardview.widget.CardView
                android:id="@+id/firstPlace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorCardView"
                app:cardCornerRadius="10dp"
                android:padding="10dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="10dp">

                        <TextView
                            android:id="@+id/firstPlaceName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="30sp"
                            android:textColor="@color/colorText"/>

                        <TextView
                            android:id="@+id/firstPlaceCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="15sp"
                            android:textColor="@color/colorText"/>

                    </LinearLayout>

                    <ImageView
                        android:id="@+id/firstPlaceImage"
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_alignParentEnd="true"/>

                </RelativeLayout>
            </androidx.cardview.widget.CardView>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/artistsWithImagesRecycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/firstPlace"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:overScrollMode="never"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">

            </androidx.recyclerview.widget.RecyclerView>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>


问:
How to mock the value of a parameter in a service class
How can I test the following service method with Junit test? It's a very simple rebuild of my code and only an example.
I want to test in a JUnit test, what's happening, if the file string is empty or null.
Unfortunately I'm new to testing with JUnit. I read already some examples for rest controller and services and repos to me mocked and the methods for it, but here I have no idea how it could work. May someone can help?

```<code>public class MyService {

    private String fileName = "src/main/resources";
 // or
 // private String fileName = ${modulename.config.filename};
//  @Autowired
//  private RepoService RepoService;

    @EventListener
    public void init(ContextRefreshedEvent event) {
        try {
        myMethod();
        } catch (Exception e) {
            // LOGGING
        };
}

public void myMethod() {

        if(fileName != null && !fileName.isEmpty()) {
            // doSomething with file and IOException
            // save in repo
        } else {
            // LOGGING
        }
    }
}

    public void myMethod() {
        if(fileName != null && !fileName.isEmpty()) {
            // doSomething with IOException
        } else {
            // LOGGING
        }
    }
}
</code>```

The test should look like the following. I tried to set the value somehow in the test, but it does not make sense and it's not set then.

```<code>@SpringBootTest
class DemoApplicationTests {

    @Test
    public void fileNameTest() {
        // GIVEN
        //Mockito.when()

        // WHEN

        // THEN
    }

}
</code>```

答:
To change the value of a private variable Use Field modification using Reflection API.
Here's a nice explanation on how to do this.

Body:
How can I test the following service method with Junit test? It's a very simple rebuild of my code and only an example.
I want to test in a JUnit test, what's happening, if the file string is empty or null.
Unfortunately I'm new to testing with JUnit. I read already some examples for rest controller and services and repos to me mocked and the methods for it, but here I have no idea how it could work. May someone can help?

public class MyService {

    private String fileName = "src/main/resources";
 // or
 // private String fileName = ${modulename.config.filename};
//  @Autowired
//  private RepoService RepoService;

    @EventListener
    public void init(ContextRefreshedEvent event) {
        try {
        myMethod();
        } catch (Exception e) {
            // LOGGING
        };
}

public void myMethod() {

        if(fileName != null && !fileName.isEmpty()) {
            // doSomething with file and IOException
            // save in repo
        } else {
            // LOGGING
        }
    }
}

    public void myMethod() {
        if(fileName != null && !fileName.isEmpty()) {
            // doSomething with IOException
        } else {
            // LOGGING
        }
    }
}

The test should look like the following. I tried to set the value somehow in the test, but it does not make sense and it's not set then.

@SpringBootTest
class DemoApplicationTests {

    @Test
    public void fileNameTest() {
        // GIVEN
        //Mockito.when()

        // WHEN

        // THEN
    }

}


问:
Use SED or AWK to find and replace string across multiple lines
I have an HTML file that contains a string on one line that I would like to move to another line after a string.

The command would need to take into account variations of the first string across the document.

I have tried the following with Sed, but they don't work:

```<code>sed 's/\(aria-describedby="page-[0-9]"\)\(.*<aside \)/\2\1/g'
</code>```

and

```<code> sed 's/\(aria-describedby="page-[0-9]"\)\(.*<aside \)/\2\1/g'
</code>```

The string that I would like to find is aria-describedby="page-foo" and I would like to move this string after strings that begin with <aside before the next instance of aria-describedby="page-foo".

Input:

```<code><h6 aria-describedby="page-1" id="page-1">Page 1</h6>
<h1 id="chapter-1">Chapter 1</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<h2 id="math-content">Math Content</h2>
<p><span class="math display">\[\sqrt{a^{2} + b^{2}}\]</span></p>
<p>This is a paragraph</p>
<aside role="doc-footnote">
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</aside>
<aside role="complementary">
<p>Secondary Text Begin:</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>Secondary Text End</p>
</aside>
<h6 aria-describedby="page-2" id="page-2">Page 2</h6>
<h1 id="chapter-2">Chapter 2</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<h2 id="math-content">Math Content</h2>
<p><span class="math display">\[\sqrt{a^{2} + b^{2}}\]</span></p>
<p>This is a paragraph</p>
<aside role="doc-footnote">
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</aside>
<aside role="complementary">
<p>Secondary Text Begin:</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>Secondary Text End</p>
</aside>
</code>```

Desired Output:

```<code><h6 id="page-1">Page 1</h6>
<h1 id="chapter-1">Chapter 1</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<h2 id="math-content">Math Content</h2>
<p><span class="math display">\[\sqrt{a^{2} + b^{2}}\]</span></p>
<p>This is a paragraph</p>
<aside aria-describedby="page-1" role="doc-footnote">
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</aside>
<aside aria-describedby="page-1" role="complementary">
<p>Secondary Text Begin:</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>Secondary Text End</p>
</aside>
<h6 id="page-2">Page 2</h6>
<h1 id="chapter-2">Chapter 2</h1>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<h2 id="math-content">Math Content</h2>
<p><span class="math display">\[\sqrt{a^{2} + b^{2}}\]</span></p>
<p>This is a paragraph</p>
<aside aria-describedby="page-2" role="doc-footnote">
<p>This is a paragraph</p>
<p>This is a paragraph</p>
</aside>
<aside aria-describedby="page-2" role="complementary">
<p>Secondary Text Begin:</p>
<p>This is a paragraph</p>
<p>This is a paragraph</p>
<p>Secondary Text End</p>
</aside>
</code>```

答:
The following works according to your description:

```<code>sed '
/aria-describedby="page-/{
h
s/.*\( aria-describedby="page-[0-9]*"\).*/\1/
x
s/ aria-describedby="page-[0-9]*"//
}
/aside role="\(doc-footnote\|complementary\)"/{
G
s/aside\(.*\)\n\(.*\)/aside\2\1/
}' yourfile
</code>```

How it works:

for each line matching aria-describedby="page- it does what is in {…}:

h "saves" the line as it is now by copying it in the hold space (overwriting whatever is in the hold space)

s deletes what is before and after aria-describedby="page-n" (n is the number; the leading space is left!)

x swaps hold and pattern spaces: the hold space contains the edited line, the pattern space the original line that we saved with h

s now deletes aria-describedby="page-n

when a line matching either aside role="doc-footnote" or aside role="complementary" is hit, the following is done:

G appends the content of the pattern space to the current line, with a \n in between

s reorder the pieces while removing the \n

Body:
I have an HTML file that contains a string on one line that I would like to move to another line after a string.

The command would need to take into account variations of the first string across the document.

I have tried the following with Sed, but they don't work:

sed 's/\(aria-describedby="page-[0-9]"\)\(.*<aside \)/\2\1/g'

and

 sed 's/\(aria-describedby="page-[0-9]"\)\(.*<aside \)/\2\1/g'

The string that I would like to find is aria-describedby="page-foo" and I would like to move this string after strings that begin with <aside before the next instance of aria-describedby="page-foo".

Input:

Page 1

Chapter 1

This is a paragraph

This is a paragraph

Math Content

\[\sqrt{a^{2} + b^{2}}\]

This is a paragraph

This is a paragraph

This is a paragraph

Secondary Text Begin:

This is a paragraph

This is a paragraph

Secondary Text End

Page 2

Chapter 2

This is a paragraph

This is a paragraph

Math Content

\[\sqrt{a^{2} + b^{2}}\]

This is a paragraph

This is a paragraph

This is a paragraph

Secondary Text Begin:

This is a paragraph

This is a paragraph

Secondary Text End

Desired Output:

Page 1

Chapter 1

This is a paragraph

This is a paragraph

Math Content

\[\sqrt{a^{2} + b^{2}}\]

This is a paragraph

This is a paragraph

This is a paragraph

Secondary Text Begin:

This is a paragraph

This is a paragraph

Secondary Text End

Page 2

Chapter 2

This is a paragraph

This is a paragraph

Math Content

\[\sqrt{a^{2} + b^{2}}\]

This is a paragraph

This is a paragraph

This is a paragraph

Secondary Text Begin:

This is a paragraph

This is a paragraph

Secondary Text End

Body:
The following works according to your description:

sed '
/aria-describedby="page-/{
h
s/.*\( aria-describedby="page-[0-9]*"\).*/\1/
x
s/ aria-describedby="page-[0-9]*"//
}
/aside role="\(doc-footnote\|complementary\)"/{
G
s/aside\(.*\)\n\(.*\)/aside\2\1/
}' yourfile

How it works:

for each line matching aria-describedby="page- it does what is in {…}:

h "saves" the line as it is now by copying it in the hold space (overwriting whatever is in the hold space)

s deletes what is before and after aria-describedby="page-n" (n is the number; the leading space is left!)

x swaps hold and pattern spaces: the hold space contains the edited line, the pattern space the original line that we saved with h

s now deletes aria-describedby="page-n

when a line matching either aside role="doc-footnote" or aside role="complementary" is hit, the following is done:

G appends the content of the pattern space to the current line, with a \n in between

s reorder the pieces while removing the \n


问:
CodingBat starOut, why using substring won't work correctly
I am solving coding challenge on CodingBat.com. Here is the question:

Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

```<code>plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
</code>```

Here is my attempted solution:

```<code>public String plusOut(String str, String word)
{
  String ret = "";
  for (int i = 0; i < str.length() - word.length() + 1; ++i) {
    if (str.substring(i, i + word.length()).equals(word))
      ret += word;
    else
      ret += "+";
  }
  return ret;
}
</code>```

But is giving wrong outputs: giving too many plus signs. I don't understand why this shouldn't work. I suspect that the substring method is not returning enough matches, so the plus sign is appended. But I don't see why this maybe so.

答:
You were doing a few things wrong. I've corrected your code although there is probably a cleaner way to do this. I will explain what's changed below.

```<code>public static String plusOut(String str, String word)
{
    String ret = "";
    for (int i = 0; i < str.length(); ++i) {
        int endIndex = i + word.length();
        if (endIndex < str.length() + 1
                && str.substring(i, i + word.length()).equals(word)) {
            ret += word;
            i = i + word.length() - 1;
        } else
            ret += "+";
    }
    return ret;
}
</code>```

First mistake is that you are not looping over the whole content of str and therefore never reach the last character of str.

Another problem is that once you find a word, you don't "jump" to the correct next index in the loop, but still continue looping over characters of the found word, which results in additional + characters in your result string.

```<code>i = i + word.length() - 1;
</code>```

In your solution, the above will put you to the next index of a character inside str that you should be looking at. Example:

In string 12xy34xyabcxy looking for xy.

You will find that word xy starts at index 2 and ends at 3.
At that point you have result string ++xy after adding the found word to it.

Now, the problem begins. You still end up going over index 3 and adding an additional + because the next couple of characters do not add up to your word.

The 2 characters after the found xy also add + and you now have ++xy+++ which is incorrect.

```<code>endIndex < str.length() + 1
</code>```

endIndex is named after what it is - end index of your substring.

This check prevents us from checking for xy when there aren't enough characters left in the string from current index to the last in order to make up xy, so we end up adding + for each remaining character instead.

Body:
I am solving coding challenge on CodingBat.com. Here is the question:

Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

Here is my attempted solution:

public String plusOut(String str, String word)
{
  String ret = "";
  for (int i = 0; i < str.length() - word.length() + 1; ++i) {
    if (str.substring(i, i + word.length()).equals(word))
      ret += word;
    else
      ret += "+";
  }
  return ret;
}

But is giving wrong outputs: giving too many plus signs. I don't understand why this shouldn't work. I suspect that the substring method is not returning enough matches, so the plus sign is appended. But I don't see why this maybe so.

Body:
You were doing a few things wrong. I've corrected your code although there is probably a cleaner way to do this. I will explain what's changed below.

public static String plusOut(String str, String word)
{
    String ret = "";
    for (int i = 0; i < str.length(); ++i) {
        int endIndex = i + word.length();
        if (endIndex < str.length() + 1
                && str.substring(i, i + word.length()).equals(word)) {
            ret += word;
            i = i + word.length() - 1;
        } else
            ret += "+";
    }
    return ret;
}

First mistake is that you are not looping over the whole content of str and therefore never reach the last character of str.

Another problem is that once you find a word, you don't "jump" to the correct next index in the loop, but still continue looping over characters of the found word, which results in additional + characters in your result string.

i = i + word.length() - 1;

In your solution, the above will put you to the next index of a character inside str that you should be looking at. Example:

In string 12xy34xyabcxy looking for xy.

You will find that word xy starts at index 2 and ends at 3.
At that point you have result string ++xy after adding the found word to it.

Now, the problem begins. You still end up going over index 3 and adding an additional + because the next couple of characters do not add up to your word.

The 2 characters after the found xy also add + and you now have ++xy+++ which is incorrect.

endIndex < str.length() + 1

endIndex is named after what it is - end index of your substring.

This check prevents us from checking for xy when there aren't enough characters left in the string from current index to the last in order to make up xy, so we end up adding + for each remaining character instead.


问:
help with rle command
I'm having some trouble with an rle command that is designed to find the point at which participants reach 8 contiguous ones in a row.

For example, if:

```<code>x <- c(0,1,0,1,1,1,1,1,1,1,1,1)
</code>```

i want to return a value of 11.

Thanks to DWin to I've been using this piece of code:

```<code>which( rle(x2)$values==1 & rle(x2)$lengths >= 8)
sum(rle(x)$lengths[ 1:(min(which(rle(x)$lengths >= 8))-1) ]) + 8
</code>```

I've been using this code successfully to process my data. However, i noticed that it made a mistake when processing one of my data files.

For example, if

```<code> x <- c(1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
</code>```

the code returns 19, which is the point at which eight contiguous zeros in a row is reached. i'm not sure what is going wrong or how it fix it.

thanks in advance for your help.

Will

答:
My advice would be to break the code up into simpler pieces. As suggested by @Nick, you want to write code which can be easily debugged and modular coding allows you to do that.</p>

```<code># find runs of 0s and 1s
run_01 = rle(x)

# find run of 1's with length >=8
run_1 = with(run_01, which(values == 1 & lengths >=8))

# find starting position of run_1
start_pos = sum(run_01$lengths[1:(run_1 - 1)])

# add 8 to it
end_pos  = start_pos + 8
</code>```

Title: help with rle command

Body:
I'm having some trouble with an rle command that is designed to find the point at which participants reach 8 contiguous ones in a row.

For example, if:

x <- c(0,1,0,1,1,1,1,1,1,1,1,1)

i want to return a value of 11.

Thanks to DWin to I've been using this piece of code:

which( rle(x2)$values==1 & rle(x2)$lengths >= 8)
sum(rle(x)$lengths[ 1:(min(which(rle(x)$lengths >= 8))-1) ]) + 8

I've been using this code successfully to process my data. However, i noticed that it made a mistake when processing one of my data files.

For example, if

 x <- c(1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)

the code returns 19, which is the point at which eight contiguous zeros in a row is reached. i'm not sure what is going wrong or how it fix it.

thanks in advance for your help.

Will

Body:
My advice would be to break the code up into simpler pieces. As suggested by @Nick, you want to write code which can be easily debugged and modular coding allows you to do that.

# find runs of 0s and 1s
run_01 = rle(x)

# find run of 1's with length >=8
run_1 = with(run_01, which(values == 1 & lengths >=8))

# find starting position of run_1
start_pos = sum(run_01$lengths[1:(run_1 - 1)])

# add 8 to it
end_pos  = start_pos + 8


问:
How can I determine the variable value in this CSS?
I inspected the Google User Icon and found this code:

```<code>img.yt-img-shadow {
    display: block;
    margin-left: var(--yt-img-margin-left, auto);
    margin-right: var(--yt-img-margin-right, auto);
    max-height: var(--yt-img-max-height, none);
    max-width: var(--yt-img-max-width, 100%);
    border-radius: var(--yt-img-border-radius, none);
}
</code>```

How can I determine how this is interpreted particularly the var()?

Thanks.

答:
CSS has been developing at a rapid rate so that now you can declare variables with out having to use a library like LESS.

See the Mozilla Docs for CSS "custom properties" which is just another name for variables.

Here is the simplicity of it:

Define:

```<code>element {
  --main-bg-color: brown;
}
</code>```

Use:

```<code>element {
  background-color: var(--main-bg-color);
}
</code>```

Body:
I inspected the Google User Icon and found this code:

img.yt-img-shadow {
    display: block;
    margin-left: var(--yt-img-margin-left, auto);
    margin-right: var(--yt-img-margin-right, auto);
    max-height: var(--yt-img-max-height, none);
    max-width: var(--yt-img-max-width, 100%);
    border-radius: var(--yt-img-border-radius, none);
}

How can I determine how this is interpreted particularly the var()?

Thanks.

Body:
CSS has been developing at a rapid rate so that now you can declare variables with out having to use a library like LESS.

See the Mozilla Docs for CSS "custom properties" which is just another name for variables.

Here is the simplicity of it:

Define:

element {
  --main-bg-color: brown;
}

Use:

element {
  background-color: var(--main-bg-color);
}


问:
Aspect ratio on Mozilla Firefox
In one of my website pages, I would like to add a picture with a dynamic size.
To do this, I follow the excellent tutorial of W3school : link

This method works perfectly on Safari and Chrome; but gives me an error on firefox..

Doing the analysis of the containers sizes, I thought the calculation seems to be different..

First, here is the Chrome and Safari method:

Red block has a width of 50% (respect to the blue one)

Red block has a height of 40% (because we also use the width of the blue one as basis for % calculation)

Then, in firefox it gives me this result :

Red block has a width of 50% (respect to the blue one)

Red block has a height of 40% of the height of the blue one, and not 40% of his parent width !

body {
  background-color: blue;
}

.home_box {
  margin: auto;
  margin-bottom: 40px;
  width: 90%;
  display: -webkit-box;
  /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;
  /* OLD - Firefox 19 */
  display: -ms-flexbox;
  /* TWEENER - IE 10 */
  display: -webkit-flex;
  /* NEW - Chrome */
  display: flex;
  flex-direction: row;
}

#home_picture {
  width: 32%;
  height: 0px;
  padding-top: 18.1%;
  background-color: red;
  /*background: url('../Img/picture.jpg') no-repeat;
  background-size: contain;*/
}

.home_box p {
  width: 68%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home_box">
  <div id="home_picture"></div>
  <p>Lorem ipsum</p>
</div></code>```

Could you help fixed this issue please ?

答:
Perhaps it's a problem with your Firefox version. When I run this code (slightly tweaked from yours and shown below) on Firefox 72 I get an output shown in the image below, same as what I get in old Microsoft Edge, Chromium-based Edge and Safari. Is the output correct?

body{
  background-color: blue;
}
.home_box
{
    margin: auto;
    margin-bottom: 40px;
    width: 90%;
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19 */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;
    flex-direction: row;
}

#home_picture
{
    width: 32%;
    height: 0px;
    padding-top: 18.1%;
    background-color: red;
    background-size: contain;
}

.home_box p
{
    width: 68%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="home_box">
    <div id="home_picture"></div>
</div></code>```

Title: Aspect ratio on Mozilla Firefox

Body:
In one of my website pages, I would like to add a picture with a dynamic size.
To do this, I follow the excellent tutorial of W3school : link

This method works perfectly on Safari and Chrome; but gives me an error on firefox..

Doing the analysis of the containers sizes, I thought the calculation seems to be different..

First, here is the Chrome and Safari method:

Red block has a width of 50% (respect to the blue one)

Red block has a height of 40% (because we also use the width of the blue one as basis for % calculation)

Then, in firefox it gives me this result :

Red block has a width of 50% (respect to the blue one)

Red block has a height of 40% of the height of the blue one, and not 40% of his parent width !

body {
  background-color: blue;
}

.home_box {
  margin: auto;
  margin-bottom: 40px;
  width: 90%;
  display: -webkit-box;
  /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;
  /* OLD - Firefox 19 */
  display: -ms-flexbox;
  /* TWEENER - IE 10 */
  display: -webkit-flex;
  /* NEW - Chrome */
  display: flex;
  flex-direction: row;
}

#home_picture {
  width: 32%;
  height: 0px;
  padding-top: 18.1%;
  background-color: red;
  /*background: url('../Img/picture.jpg') no-repeat;
  background-size: contain;*/
}

.home_box p {
  width: 68%;
}

Lorem ipsum

Could you help fixed this issue please ?

Body:
Perhaps it's a problem with your Firefox version. When I run this code (slightly tweaked from yours and shown below) on Firefox 72 I get an output shown in the image below, same as what I get in old Microsoft Edge, Chromium-based Edge and Safari. Is the output correct?

body{
  background-color: blue;
}
.home_box
{
    margin: auto;
    margin-bottom: 40px;
    width: 90%;
    display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;         /* OLD - Firefox 19 */
    display: -ms-flexbox;      /* TWEENER - IE 10 */
    display: -webkit-flex;     /* NEW - Chrome */
    display: flex;
    flex-direction: row;
}

#home_picture
{
    width: 32%;
    height: 0px;
    padding-top: 18.1%;
    background-color: red;
    background-size: contain;
}

.home_box p
{
    width: 68%;
}

<div class="home_box">
    <div id="home_picture"></div>
</div>


问:
Order files via powershell
I have a main folder where other folders reside with .mkg files . These folders have a certain format.

Folder = NameSerie.SxEy.Randomstuf

Item in folder = NameSerie.SxEy.Randomstuf.mkv

Where x is the season number and y is the episode number.

What i want to do is automaticly create a folder if the nameSerie isnt already created and put the .mkv files in this folder.

So, if we have folders named NameSerie.SxEy.Randomstuf we check if folder NameSerie exists, if not we create one. Then we enter folder NameSerie.SxEy.Randomstuf and copy the NameSerie.SxEy.Randomstuf.mkv file in the NameSerie folder.

the file name needs to change from NameSerie.SxEy.Ra.n[dom}stuf.mkv to NameSerie.SxEy.mkv but I cant seem to figure out how to remove the random stuf after the NameSerie.SxEy.<   >.mkv

This is the code that i have managed to create but im still stuck. I have managed to create a folder if one does not exists but this only works if the .mkv file is not in a folder.

```<code>$Location = "\\<ip>\Share\Media\Series"

#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Replace(" [480p]","") }

#make folder for serie if it does not exist
Get-ChildItem "$Location\*.mkv" |
Foreach-Object {

    $FullName = $_.Name
    $pos = $FullName.IndexOf(" - ")
    $Name = $FullName.Substring(0, $pos)

    Write-Host $_.FullName

    $TARGETDIR = "$Location\$Name"

    if( -Not (Test-Path -Path $TARGETDIR ) )
    {
        New-Item -ItemType directory -Path $TARGETDIR
    }

    Move-Item -Path $_.FullName -Destination $TARGETDIR

}
</code>```

答:
You could use the parameter -Recurse when you list files from the path like this:

Get-ChildItem "$Location\*.mkv" -Recurse

instead of:

Get-ChildItem "$Location\*.mkv"

With the -Recurse parameter, the script will list files in the current directory and for each directory in the current directory, it will do the same recursively. So the .mkv inside other folders won't hide any longer.

Title: Order files via powershell

Body:
I have a main folder where other folders reside with .mkg files . These folders have a certain format.

Folder = NameSerie.SxEy.Randomstuf

Item in folder = NameSerie.SxEy.Randomstuf.mkv

Where x is the season number and y is the episode number.

What i want to do is automaticly create a folder if the nameSerie isnt already created and put the .mkv files in this folder.

So, if we have folders named NameSerie.SxEy.Randomstuf we check if folder NameSerie exists, if not we create one. Then we enter folder NameSerie.SxEy.Randomstuf and copy the NameSerie.SxEy.Randomstuf.mkv file in the NameSerie folder.

the file name needs to change from NameSerie.SxEy.Ra.n[dom}stuf.mkv to NameSerie.SxEy.mkv but I cant seem to figure out how to remove the random stuf after the NameSerie.SxEy.<   >.mkv

This is the code that i have managed to create but im still stuck. I have managed to create a folder if one does not exists but this only works if the .mkv file is not in a folder.

$Location = "\\<ip>\Share\Media\Series"

#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Replace(" [480p]","") }

#make folder for serie if it does not exist
Get-ChildItem "$Location\*.mkv" |
Foreach-Object {

    $FullName = $_.Name
    $pos = $FullName.IndexOf(" - ")
    $Name = $FullName.Substring(0, $pos)

    Write-Host $_.FullName

    $TARGETDIR = "$Location\$Name"

    if( -Not (Test-Path -Path $TARGETDIR ) )
    {
        New-Item -ItemType directory -Path $TARGETDIR
    }

    Move-Item -Path $_.FullName -Destination $TARGETDIR

}


问:
Split single column with irregular sampling into multiple columns with same timestamps in pandas
I have an export from a system which I cannot change and I need to modify my data for analysis. My dataframe has following format:

```<code>Timestamp  |  Name | Value
===========================
'14:00:00' | Var A | 0
'14:00:01' | Var A | 1
'14:00:02' | Var A | 2
...
'15:00:00' | Var A | 3600
'14:00:00' | Var B | 0
'14:10:00' | Var B | 600
..
'15:00:00' | Var B | 3600
'14:00:00' | Var C | 1000
...
</code>```

So it is basically a union of logs of multiple variables with each having a different sampling frequency. What I need is to have a single sampling frequency (e.g 1 second) and each variable in independent column. So what I need to achieve is this:

```<code>Timestamp  |Var A  | Var B| Var C|.....
'14:00:01' | 0     | 0    | 1000 | ...
'14:00:02' | 1     | 1    |  ... |
'14:00:03' | 2     | 2    |      |
    ...    | ...   | ...  |      |
'15:00:00' | 3600  | 3600 |      |
</code>```

Note that B originally had period of readings 10 minutes, but now has 1 second and the values are interpolated. I'm fairly new to pandas, so any help will be greatly appreciated

Body:
I have an export from a system which I cannot change and I need to modify my data for analysis. My dataframe has following format:

Timestamp  |  Name | Value
===========================
'14:00:00' | Var A | 0
'14:00:01' | Var A | 1
'14:00:02' | Var A | 2
...
'15:00:00' | Var A | 3600
'14:00:00' | Var B | 0
'14:10:00' | Var B | 600
..
'15:00:00' | Var B | 3600
'14:00:00' | Var C | 1000
...

So it is basically a union of logs of multiple variables with each having a different sampling frequency. What I need is to have a single sampling frequency (e.g 1 second) and each variable in independent column. So what I need to achieve is this:

Timestamp  |Var A  | Var B| Var C|.....
'14:00:01' | 0     | 0    | 1000 | ...
'14:00:02' | 1     | 1    |  ... |
'14:00:03' | 2     | 2    |      |
    ...    | ...   | ...  |      |
'15:00:00' | 3600  | 3600 |      |

Note that B originally had period of readings 10 minutes, but now has 1 second and the values are interpolated. I'm fairly new to pandas, so any help will be greatly appreciated

Body:
Use:

#if neccessary
#df['Timestamp']= df['Timestamp'].apply(eval)
new_df = (df.assign(Timestamp = pd.to_datetime(df['Timestamp'].astype(str)))
            .pivot(*df)
            .asfreq('s')
            .reset_index()
            .assign(Timestamp = lambda x: x['Timestamp'].dt.time)
            .interpolate()
            .rename_axis(columns = None)
         )
print(new_df)

     Timestamp   Var A   Var B   Var C
0     14:00:00     0.0     0.0  1000.0
1     14:00:01     1.0     1.0  1000.0
2     14:00:02     2.0     2.0  1000.0
3     14:00:03     3.0     3.0  1000.0
4     14:00:04     4.0     4.0  1000.0
...        ...     ...     ...     ...
3596  14:59:56  3596.0  3596.0  1000.0
3597  14:59:57  3597.0  3597.0  1000.0
3598  14:59:58  3598.0  3598.0  1000.0
3599  14:59:59  3599.0  3599.0  1000.0
3600  15:00:00  3600.0  3600.0  1000.0

[3601 rows x 4 columns]


问:
C thread pool efficiency

Possible Duplicate:

  How many threads is too many?

I have a large for loop, in which I want each item to be passed to a function on a thread. I have a thread pool of a certain size, and I want to reuse the threads. What is the most efficient way to do this?

What would be the most efficient size for the thread pool? Or at least what is the best way to figure it out?

```<code>pthread_t thread_id[10];

int i;
for(i = 0; i < 10000000; i++) {
   pthread_create(thread_id[?], NULL, threadFunc, params[i]);
}
</code>```

答: Too few threads means wasted performance opportunity and too many threads wastes resources consumed by each thread and can reduce performance due to contention among threads. I would use measurements and see what number works the best. Just curious, is there are reason why you want each iteration to be a new thread? </p>

Title: C thread pool efficiency

Body:
Possible Duplicate:

  How many threads is too many?

I have a large for loop, in which I want each item to be passed to a function on a thread. I have a thread pool of a certain size, and I want to reuse the threads. What is the most efficient way to do this?

What would be the most efficient size for the thread pool? Or at least what is the best way to figure it out?

pthread_t thread_id[10];

int i;
for(i = 0; i < 10000000; i++) {
   pthread_create(thread_id[?], NULL, threadFunc, params[i]);
}


问:
why does the loop not jump index on if clause condition in python?
```<code>r = [1,2,3,4,5,6,7,8,9,10,11,12,13]
for i in range(len(r)):
    print(i)
    if r[i] %2 == 0:
        print('found even')
        i+=3
</code>```

It still goes through all i's and not jumps over by 3. Why is that? Is the i somehow losing its scope?

答:
for is not the correct loop, use while:

```<code>r = [1,2,3,4,5,6,7,8,9,10,11,12,13]
i = 0
while i < len(r):
    print(i)
    if r[i] % 2 == 0:
        print('found even')
        i += 3
    else:
        i += 1
</code>```

Body:
r = [1,2,3,4,5,6,7,8,9,10,11,12,13]
for i in range(len(r)):
    print(i)
    if r[i] %2 == 0:
        print('found even')
        i+=3

It still goes through all i's and not jumps over by 3. Why is that? Is the i somehow losing its scope?

Body:
for is not the correct loop, use while:

r = [1,2,3,4,5,6,7,8,9,10,11,12,13]
i = 0
while i < len(r):
    print(i)
    if r[i] % 2 == 0:
        print('found even')
        i += 3
    else:
        i += 1


问:
Peatio [error]: wrong number of arguments (2 for 3)
I had a problem with my withdrawal and it showed on log/peatio:amqp:withdraw_coin.output :

```<code>peatio:amqp:withdraw_coin: process with pid 20690 started.
I, [2019-10-07T20:36:02.789768 #20690] INFO -- : Connected to AMQP broker (prefetch: default)
I, [2019-10-07T20:38:24.291531 #20690] INFO -- : Received: Worker::WithdrawCoin {"id":14,"locale":"en"}
I, [2019-10-07T20:38:24.468275 #20690] INFO -- : [Withdraw]: coin
I, [2019-10-07T20:38:24.468464 #20690] INFO -- : Making class WOA_BTC(coin)
I, [2019-10-07T20:38:24.468735 #20690] INFO -- : WOA_BTC {"method":"getbalance","params":[],"id":"jsonrpc"}
I, [2019-10-07T20:38:24.620932 #20690] INFO -- : {"result"=>59901.1999808, "error"=>nil, "id"=>"jsonrpc"}
I, [2019-10-07T20:38:24.621430 #20690] INFO -- : Making class WOA_BTC(coin)
I, [2019-10-07T20:38:24.621795 #20690] INFO -- : [error]: wrong number of arguments (2 for 3)
</code>```

Please help me solve this problem.

Ruby 2.2.7
Bundle 1.9.2
Rails 4.0.12

Best Regards

答:
Try to make this change to your files.
In my case, it solved this problem.

app/models/worker/withdraw_coin.rb:
https://gist.github.com/DigitalCoin1/471796cb0bdc929d678ab61a8abe326a

Body:
I had a problem with my withdrawal and it showed on log/peatio:amqp:withdraw_coin.output :

peatio:amqp:withdraw_coin: process with pid 20690 started.
I, [2019-10-07T20:36:02.789768 #20690] INFO -- : Connected to AMQP broker (prefetch: default)
I, [2019-10-07T20:38:24.291531 #20690] INFO -- : Received: Worker::WithdrawCoin {"id":14,"locale":"en"}
I, [2019-10-07T20:38:24.468275 #20690] INFO -- : [Withdraw]: coin
I, [2019-10-07T20:38:24.468464 #20690] INFO -- : Making class WOA_BTC(coin)
I, [2019-10-07T20:38:24.468735 #20690] INFO -- : WOA_BTC {"method":"getbalance","params":[],"id":"jsonrpc"}
I, [2019-10-07T20:38:24.620932 #20690] INFO -- : {"result"=>59901.1999808, "error"=>nil, "id"=>"jsonrpc"}
I, [2019-10-07T20:38:24.621430 #20690] INFO -- : Making class WOA_BTC(coin)
I, [2019-10-07T20:38:24.621795 #20690] INFO -- : [error]: wrong number of arguments (2 for 3)

Please help me solve this problem.

Ruby 2.2.7
Bundle 1.9.2
Rails 4.0.12

Best Regards


问:
Displaying the content of an input for several divs
I want to give all .firstname-show the content from the input but I don't know how to do it. Here's code:</p>

```<code>    <input type="text" id="firstname" name="firstname" placeholder="First name">
    <button id="firstname-btn" onclick="show()">SHOW</button>
    <div class="firstname-show"></div>
    <div class="firstname-show"></div>
</code>```

```<code>    function show() {
       var name = document.getElementById('firstname').value;
       document.querySelectorAll('.firstname-show').textContent = name;
    }
</code>```

答:
Since the querySelectorAll returns a collection, you can use the forEach method on the collection to browse each element and apply the processing you want

const show = () => {
     let value = document.getElementById('firstname').value;
     document.querySelectorAll('.firstname-show')
     .forEach(div => div.textContent = value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="firstname" name="firstname" placeholder="First name">
<button id="firstname-btn" onclick="show()">SHOW</button>
<div class="firstname-show"></div>
<div class="firstname-show"></div></code>```

Body:
I want to give all .firstname-show the content from the input but I don't know how to do it. Here's code:

    <input type="text" id="firstname" name="firstname" placeholder="First name">
    <button id="firstname-btn" onclick="show()">SHOW</button>

    function show() {
       var name = document.getElementById('firstname').value;
       document.querySelectorAll('.firstname-show').textContent = name;
    }

Body:
Since the querySelectorAll returns a collection, you can use the forEach method on the collection to browse each element and apply the processing you want

const show = () => {
     let value = document.getElementById('firstname').value;
     document.querySelectorAll('.firstname-show')
     .forEach(div => div.textContent = value);
}

<input type="text" id="firstname" name="firstname" placeholder="First name">
<button id="firstname-btn" onclick="show()">SHOW</button>
<div class="firstname-show"></div>
<div class="firstname-show"></div>


问:
Using AJAX to send data from jquery to php file and back
on my webpage, when the user clicks on a word it should show the definition of the word. When the user clicks on the word, it would send the word variable to the php file that connects to the oxford dictionary api and queries the word for its definition, then returns that definition to the webpage. The problem is when I tried to pass the word variable to the php file through ajax, it doesn't seem to be working. I am using a php wrapper to use the api and there's no problem when I set the word query manually. I am able to connect to the api and retrieve the definitions and all, so I think the problem is the ajax part. I've never used jquery, ajax or php before this assignment. I'm not sure what I did wrong. Please help!

My JS file

```<code>function getSelectedText(){
    var selectedText = '';
        if (window.getSelection)
               selectedText = window.getSelection();
return selectedText;
}

// Retrieve definition
$(document).ready(function()
{
var selected_text = getSelectedText();
$('#selectable').on("dblclick", function () {
$('.selection').text(selected_text);
$('.is-selected').text(getSelectedText() !== '');
    });

$.ajax({
    url: "dictionary.php", // php file path
    method: "POST", // send data method
    data: {"selected_text": selected_text}, // data to send {name: value}
    success: function(data){
        alert(data);
    } // response of ajax
  });

});
</code>```

My PHP file

```<code>$selected_text = $_POST['selected_text'];
echo $selected_text;

$dictionary->queryWord($selected_text);

$dictionary->setResult(0);

/* Get results from dictionary class */
echo "<h1>Dictionary Class Results - ".$dictionary->getWord()."</h1>";
echo "<b>Word:</b> ".$dictionary->getWord();
echo "<br><b>Definition:</b> ".$dictionary->getDefinition();
echo "<br><b>Short Definition:</b> ".$dictionary->getShortDefinition();
echo "<br><b>Example:</b> ".$dictionary->getExample();

/* Displays the current result set */
echo "<br></br>Using result set: <b>".$dictionary->selected_result."</b>";

?>
</code>```

答:
First of all the getSelectedText function should actually return the selected text as such

```<code>function getSelectedText(){
    var selectedText = '';
    if (window.getSelection) selectedText = window.getSelection().toString();
    return selectedText;
    // Or even better using ternary operator: return window.getSelection ? window.getSelection().toString() : '';
}
</code>```

Then, as IncredibleHat said, you should correct the way you handle the event probably as below cause I usually use Fetch API for this kind of purpose:-

```<code>// Only fire the ajax when user double click any text/selectables
$('#selectable').on("dblclick", function () {
    // Marked contants since it won't change
    const selected_text = getSelectedText();
    // Make sure you check if the string is not empty before you do the request too
    if(selected_text.trim().length > 0)
    // Then do the request and process the output
    $.ajax({
        url: "dictionary.php", // php file path
        method: "POST", // send data method
        data: {"selected_text": selected_text}, // data to send {name: value}
        success: function(data){
            alert(data);
        }
    });
});
</code>```

Body:
on my webpage, when the user clicks on a word it should show the definition of the word. When the user clicks on the word, it would send the word variable to the php file that connects to the oxford dictionary api and queries the word for its definition, then returns that definition to the webpage. The problem is when I tried to pass the word variable to the php file through ajax, it doesn't seem to be working. I am using a php wrapper to use the api and there's no problem when I set the word query manually. I am able to connect to the api and retrieve the definitions and all, so I think the problem is the ajax part. I've never used jquery, ajax or php before this assignment. I'm not sure what I did wrong. Please help!

My JS file

function getSelectedText(){
    var selectedText = '';
        if (window.getSelection)
               selectedText = window.getSelection();
return selectedText;
}

// Retrieve definition
$(document).ready(function()
{
var selected_text = getSelectedText();
$('#selectable').on("dblclick", function () {
$('.selection').text(selected_text);
$('.is-selected').text(getSelectedText() !== '');
    });

$.ajax({
    url: "dictionary.php", // php file path
    method: "POST", // send data method
    data: {"selected_text": selected_text}, // data to send {name: value}
    success: function(data){
        alert(data);
    } // response of ajax
  });

});

My PHP file

$selected_text = $_POST['selected_text'];
echo $selected_text;

$dictionary->queryWord($selected_text);

$dictionary->setResult(0);

/* Get results from dictionary class */
echo "
Dictionary Class Results - ".$dictionary->getWord()."
";
echo "Word: ".$dictionary->getWord();
echo "
Definition: ".$dictionary->getDefinition();
echo "
Short Definition: ".$dictionary->getShortDefinition();
echo "
Example: ".$dictionary->getExample();

/* Displays the current result set */
echo "

Using result set: ".$dictionary->selected_result."";

?>

Body:
First of all the getSelectedText function should actually return the selected text as such

function getSelectedText(){
    var selectedText = '';
    if (window.getSelection) selectedText = window.getSelection().toString();
    return selectedText;
    // Or even better using ternary operator: return window.getSelection ? window.getSelection().toString() : '';
}

Then, as IncredibleHat said, you should correct the way you handle the event probably as below cause I usually use Fetch API for this kind of purpose:-

// Only fire the ajax when user double click any text/selectables
$('#selectable').on("dblclick", function () {
    // Marked contants since it won't change
    const selected_text = getSelectedText();
    // Make sure you check if the string is not empty before you do the request too
    if(selected_text.trim().length > 0)
    // Then do the request and process the output
    $.ajax({
        url: "dictionary.php", // php file path
        method: "POST", // send data method
        data: {"selected_text": selected_text}, // data to send {name: value}
        success: function(data){
            alert(data);
        }
    });
});


问:
Return an array that is randomly filled with string variables
We have three string variables and we want a function to return an array that is randomly filled with those variables.

The desired result should be something like this:

```<code>['first string', 'third string', 'second string']; // each variable as a single element
</code>```

function generateArray(){

    let a = 'first string';
    let b = 'second string';
    let c = 'third string';

    let ourArray = [];

    // return ourArray randomly filled with 'a' 'b' and 'c'

}```

答:
First, you need to put all your variables into an array then shuffles (randomly reorders) elements of that array:</p>

```<code>  function generateArray(){

        function shuffle(array) {
            return array.sort(() => Math.random() - 0.5);
        }

        let a = 'first string';
        let b = 'second string';
        let c = 'third string';

        var localArray = new Array(a, b, c);
        return shuffle(localArray);

    }
</code>```

Body:
We have three string variables and we want a function to return an array that is randomly filled with those variables.

The desired result should be something like this:

['first string', 'third string', 'second string']; // each variable as a single element

function generateArray(){

    let a = 'first string';
    let b = 'second string';
    let c = 'third string';

    let ourArray = [];

    // return ourArray randomly filled with 'a' 'b' and 'c'

}

Body:
First, you need to put all your variables into an array then shuffles (randomly reorders) elements of that array:

  function generateArray(){

        function shuffle(array) {
            return array.sort(() => Math.random() - 0.5);
        }

        let a = 'first string';
        let b = 'second string';
        let c = 'third string';

        var localArray = new Array(a, b, c);
        return shuffle(localArray);

    }


答:
what other scripts do you use on your site? look at those because those could be injecting this.
maybe your webhost is shady, try to change. Or it could be a web analytics  code</p>

Title: What does this script do?

Body:
Would anybody be able to tell me what the below script does? It keeps injecting itself into our site about every two weeks (always between Sundays and Mondays). We've reloaded our "clean" site dozens of times but it just keeps happening. We've installed and made every security recommendation that we've read but it just keeps getting into all of our index.html files and a few of our php files.

Anybody have any idea of what it does or where it comes from? We could really use some help!


问:
Tkinter error: Couldn't recognize data in image file
I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn't recognize data in image file

I use the code from the documentation:

```<code>canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)
</code>```

Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?

I am using Python 3 on Mac. Python file and image are in the same folder.

答:
Another alternative solution:

filename = ImageTk.PhotoImage(Image.open('imagename.jpeg' ))
background_label = tk.Label(self.root, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
```

Body:
I'm trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn't recognize data in image file

I use the code from the documentation:

canv = Canvas(root, width=80, height=80, bg='white')
canv.grid(row=2, column=3)

img = PhotoImage(file="bll.jpg")
canv.create_image(20,20, anchor=NW, image=img)

Same thing with png images. Even tried to put an image into a label widget, but got the same error. What's wrong?

I am using Python 3 on Mac. Python file and image are in the same folder.


问:
custom tableviewcell dynamic height not updating as per constraints (with programmatically autolayout)
I have a custom uitableviewcell in app, I am trying to update its length dynamically based on its subviews (labels) contents.

but it's not working.

find related code as below.

```<code>class TransactionTableViewCell: UITableViewCell{

    private lazy var dateLabel: UILabel = {
        let datelabel = UILabel()
        datelabel.textColor = .label
        datelabel.backgroundColor = .red
        datelabel.lineBreakMode = .byTruncatingTail
        datelabel.numberOfLines = 0
        datelabel.translatesAutoresizingMaskIntoConstraints = false
        return datelabel
    }()

another method in same class:

 func setupDefaultUI(){
        self.contentView.addSubview(dateLabel)
}

 override func awakeFromNib() {
        super.awakeFromNib()
        setupDefaultUI()
        buildConstraints()
    }

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupDefaultUI()
        buildConstraints()
    }

 func buildConstraints(){

        let marginGuide = self.contentView

        NSLayoutConstraint.activate([
            dateLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor)
            ,
            dateLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
            dateLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor),
            dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
            ,

            dateLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor)
  ])
    }

</code>```

and inside viewcontroller file:

```<code> private lazy var transactionTableView: UITableView = {
        let tableview = UITableView.init()
        tableview.backgroundView = nil
        tableview.backgroundColor = .clear
        tableview.rowHeight = UITableView.automaticDimension
        tableview.estimatedRowHeight = 300
        return tableview
    }()

</code>```

and in viewdidload:

```<code>    transactionTableView.dataSource = Objdatasource
        transactionTableView.delegate = Objdelegate

        transactionTableView.register(TransactionTableViewCell.self, forCellReuseIdentifier: CellIdentifiers.transactionCell)

</code>```

答:
In this tutorial (which I recently followed and worked for me), there is a function you are missing there:</p>

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return UITableView.automaticDimension
}
</code>```

Body:
I have a custom uitableviewcell in app, I am trying to update its length dynamically based on its subviews (labels) contents.

but it's not working.

find related code as below.

class TransactionTableViewCell: UITableViewCell{

    private lazy var dateLabel: UILabel = {
        let datelabel = UILabel()
        datelabel.textColor = .label
        datelabel.backgroundColor = .red
        datelabel.lineBreakMode = .byTruncatingTail
        datelabel.numberOfLines = 0
        datelabel.translatesAutoresizingMaskIntoConstraints = false
        return datelabel
    }()

another method in same class:

 func setupDefaultUI(){
        self.contentView.addSubview(dateLabel)
}

 override func awakeFromNib() {
        super.awakeFromNib()
        setupDefaultUI()
        buildConstraints()
    }

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupDefaultUI()
        buildConstraints()
    }

 func buildConstraints(){

        let marginGuide = self.contentView

        NSLayoutConstraint.activate([
            dateLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor)
            ,
            dateLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
            dateLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor),
            dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
            ,

            dateLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor)
  ])
    }

and inside viewcontroller file:

 private lazy var transactionTableView: UITableView = {
        let tableview = UITableView.init()
        tableview.backgroundView = nil
        tableview.backgroundColor = .clear
        tableview.rowHeight = UITableView.automaticDimension
        tableview.estimatedRowHeight = 300
        return tableview
    }()

and in viewdidload:

    transactionTableView.dataSource = Objdatasource
        transactionTableView.delegate = Objdelegate

        transactionTableView.register(TransactionTableViewCell.self, forCellReuseIdentifier: CellIdentifiers.transactionCell)

Body:
In this tutorial (which I recently followed and worked for me), there is a function you are missing there:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return UITableView.automaticDimension
}


问:
passing string around question
I have a member function like

```<code>setResult(const std::string &s)
{
         this->m_result = s;
}
</code>```

After checking, I found this->m_result's address is the same as s. Will m_result disappear (or become garbage) when s goes out of scope if s is a stack object?

答:
Probably not; if m_result is a std::string, it will deep-copy the data contents.

Anyway, in places like assignment operators, you'd normally check against this kind of self-assignment.  The idiom is:

```<code>obj& operator=(const obj& o) {
    if ( this != &o ) // ...
}
</code>```

The same goes for your case, where you could potentially check it &m_result is different from the passed in string.  But std::string are usually implemented so that self-copying is OK.

Title: passing string around question

Body:
I have a member function like

setResult(const std::string &s)
{
         this->m_result = s;
}

After checking, I found this->m_result's address is the same as s. Will m_result disappear (or become garbage) when s goes out of scope if s is a stack object?

Body:
Probably not; if m_result is a std::string, it will deep-copy the data contents.

Anyway, in places like assignment operators, you'd normally check against this kind of self-assignment.  The idiom is:

obj& operator=(const obj& o) {
    if ( this != &o ) // ...
}

The same goes for your case, where you could potentially check it &m_result is different from the passed in string.  But std::string are usually implemented so that self-copying is OK.


问:
Accurate cut of mp4 file using FFmpeg
I want to cut mp4 video to seperate videos by seconds
in the example:

```<code>00:00:00 - 00:00:01
00:00:01 - 00:00:02
00:00:02 - 00:00:10.01
</code>```

This is the commands I used:

```<code>ffmpeg.exe -i 10sec.mp4 -ss 00:00:00 -t 00:00:01 -async 1 -strict -2 -c copy 0002.mp4
ffmpeg.exe -i 10sec.mp4 -ss 00:00:01 -t 00:00:02 -async 1 -strict -2 -c copy 0003.mp4
ffmpeg.exe -i 10sec.mp4 -ss 00:00:02 -t 00:00:10.01 -async 1 -strict -2 -c copy 0004.mp4
</code>```

And the files I got are:
1.3 second long
2.6 second long
8.5 second long

So obviously the cutting it's not accurate...

I understand it's hes something to do with the key frame, so I want to decompress the original file (mpeg with very high quality) to be not compress at all (so every frame will be key frame) and then do the cutting on it (so now the cutting will be accurate)

The reason accuracy is so important to me is because after the cutting I must rejoin the slices to the single movie, and currently I just have replication in the movie I create from the slices.

I tried the .avi version:

```<code>..\ffmpeg.exe -i 10sec.mp4 -vcodec rawvideo -acodec copy uncompressed.mp4
</code>```

it's obviously failed duo to :

```<code> [mp4 @ 091f1300] Could not find tag for codec rawvideo in stream #0, codec not currently supported in container
 Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
 Error initializing output stream 0:0 --
</code>```

So my q. is, how can I accurate slice a file using ffmpeg (I have the pkt_pts as well as the time I want to slice at, so if it's possible to accurate cut by pkt_pts it also will helkp me)?

答:
The error says MP4 doesn't support uncompressed video. So you better use AVI container and specify the pixel format:

..\ffmpeg.exe -i 10sec.mp4 -vcodec rawvideo -pix_fmt bgr24 -acodec
copy uncompressed.avi

Then you can frame/time accurately cut the uncompressed.avi file.

This is how it works for me:

Cut video-only parts from original video (Imagine.mp4) using loss-less transcoding

ffmpeg -i Imagine.mp4 -ss 00:00:00.00 -t 00:00:05 -c:v libx264 -crf 0 -preset ultrafast -an Imagine_part0.mp4

ffmpeg -i Imagine.mp4 -ss 00:00:05.00 -t 00:00:05 -c:v libx264 -crf 0 -preset ultrafast -an Imagine_part1.mp4

ffmpeg -i Imagine.mp4 -ss 00:00:10.00 -c:v libx264 -crf 0 -preset ultrafast -an Imagine_part2.mp4

Join parts without re-encoding

ffmpeg -f concat -safe 0 -i files.txt -an -c:v copy -fflags +genpts Imagine_joined.mp4

Add only audio from original file to joined video and create final output (video + audio)

ffmpeg -i Imagine_joined.mp4 -i Imagine.mp4 -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 -shortest -fflags +genpts Imagine_final.mp4

Between step #1 and #2 you would usually do your encoding into the target quality but I've left this out for simplicity.

Title: Accurate cut of mp4 file using FFmpeg

Body:
I want to cut mp4 video to seperate videos by seconds
in the example:

00:00:00 - 00:00:01
00:00:01 - 00:00:02
00:00:02 - 00:00:10.01

This is the commands I used:

ffmpeg.exe -i 10sec.mp4 -ss 00:00:00 -t 00:00:01 -async 1 -strict -2 -c copy 0002.mp4
ffmpeg.exe -i 10sec.mp4 -ss 00:00:01 -t 00:00:02 -async 1 -strict -2 -c copy 0003.mp4
ffmpeg.exe -i 10sec.mp4 -ss 00:00:02 -t 00:00:10.01 -async 1 -strict -2 -c copy 0004.mp4

And the files I got are:
1.3 second long
2.6 second long
8.5 second long

So obviously the cutting it's not accurate...

I understand it's hes something to do with the key frame, so I want to decompress the original file (mpeg with very high quality) to be not compress at all (so every frame will be key frame) and then do the cutting on it (so now the cutting will be accurate)

The reason accuracy is so important to me is because after the cutting I must rejoin the slices to the single movie, and currently I just have replication in the movie I create from the slices.

I tried the .avi version:

..\ffmpeg.exe -i 10sec.mp4 -vcodec rawvideo -acodec copy uncompressed.mp4

it's obviously failed duo to :

 [mp4 @ 091f1300] Could not find tag for codec rawvideo in stream #0, codec not currently supported in container
 Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
 Error initializing output stream 0:0 --

So my q. is, how can I accurate slice a file using ffmpeg (I have the pkt_pts as well as the time I want to slice at, so if it's possible to accurate cut by pkt_pts it also will helkp me)?