问:
'Error: TypeError: ProtractorImageComparison is not a constructor' with the protractor-image-comparison v2.0.1
I'm trying to write some visual tests and running into the mentioned error with the protractor-image-comparison of version 2.0.1. Even though there is an update of the library I decided to stick to the older version since I experience some issues with the newest one as well.
My setup is:</p>

<p>//protractor.conf.js: </p>

```<code>const { SpecReporter } = require('jasmine-spec-reporter');
const { join } = require('path');
const { ProtractorImageComparison } = require('protractor-image-comparison');

exports.config = {
  allScriptsTimeout: 11000,
  specs: ['./src/**/*-spec.ts'],
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: [
        // '--headless',
        '--disable-gpu', '--window-size=1600,950', '--no-sandbox'],
    },
  },
  SELENIUM_PROMISE_MANAGER: false,
  directConnect: true,
  framework: 'jasmine2',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {
    },
  },
  onPrepare() {
    require('ts-node').register({
      project: join(__dirname, './tsconfig.e2e.json'),
    });

    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));

    browser.protractorImageComparison = new ProtractorImageComparison({
      baselineFolder: join(__dirname, '/src/resources/baseline/'),
      screenshotPath: join(__dirname, '/src/tmp/'),
      formatImageName: '{tag}',
      autoSaveBaseline: false
    });
  },
};
</code>```

答:
I came across this issue today and apparently from version 3.0.1 this package now functions as a plugin and not a class which needs to be instantiated.

I managed to get it working adding the following code to my conf.js:

```<code>plugins: [
    {
        inline: require('protractor-image-comparison'),
        // package: 'protractor-image-comparison' //protractor is installed globally so it is checking for plugin globally also
        options: {
            baselineFolder: './testArtifacts/screen-compare/baselines/',
            screenshotPath: './testArtifacts/screen-compare/screenshots/',
            formatImageName: `{tag}-{logName}-{width}x{height}`,
            savePerInstance: true,
        },
    },
],
</code>```

Note: For me protractor was installed globally so I needed this workaround using inline instead of package to get it searching for the plugin module locally.

Body:
I'm trying to write some visual tests and running into the mentioned error with the protractor-image-comparison of version 2.0.1. Even though there is an update of the library I decided to stick to the older version since I experience some issues with the newest one as well.
My setup is:

//protractor.conf.js:

const { SpecReporter } = require('jasmine-spec-reporter');
const { join } = require('path');
const { ProtractorImageComparison } = require('protractor-image-comparison');

exports.config = {
  allScriptsTimeout: 11000,
  specs: ['./src/**/*-spec.ts'],
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: [
        // '--headless',
        '--disable-gpu', '--window-size=1600,950', '--no-sandbox'],
    },
  },
  SELENIUM_PROMISE_MANAGER: false,
  directConnect: true,
  framework: 'jasmine2',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {
    },
  },
  onPrepare() {
    require('ts-node').register({
      project: join(__dirname, './tsconfig.e2e.json'),
    });

    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));

    browser.protractorImageComparison = new ProtractorImageComparison({
      baselineFolder: join(__dirname, '/src/resources/baseline/'),
      screenshotPath: join(__dirname, '/src/tmp/'),
      formatImageName: '{tag}',
      autoSaveBaseline: false
    });
  },
};

Body:
I came across this issue today and apparently from version 3.0.1 this package now functions as a plugin and not a class which needs to be instantiated.

I managed to get it working adding the following code to my conf.js:

plugins: [
    {
        inline: require('protractor-image-comparison'),
        // package: 'protractor-image-comparison' //protractor is installed globally so it is checking for plugin globally also
        options: {
            baselineFolder: './testArtifacts/screen-compare/baselines/',
            screenshotPath: './testArtifacts/screen-compare/screenshots/',
            formatImageName: `{tag}-{logName}-{width}x{height}`,
            savePerInstance: true,
        },
    },
],

Note: For me protractor was installed globally so I needed this workaround using inline instead of package to get it searching for the plugin module locally.


来源: stackexchange

问:
Call terminal input at start of bash script
I downloaded Yara from Git. When I run yara from terminal, it works as I would expect.  I want to know if it's possible to create a bash script that would let me call yara and then execute my command.

Any help would be greatly appreciated!

yara -w /path/path/path works in terminal

yara -w in a shell script does not execute as I would want.

答:
When you run it from shell, your environment is set.

For e.g., if your default shell is bash, then ~/.bashrc or ~/.profile sets them (/etc/profile is sourced as well).

Via Xcode, this doesn't happen automatically. So, $PATH doesn't have the location for yara.

You may:

Use the complete path for yara from Xcode

OR Source ~/.bashrc or ~/.profile in Xcode (if there's such an option)) before using yara

OR Configure the $PATH settings in Xcode to point to the location where yara is installed. You can find it by running which yara in the shell.

ContentLicense: CC BY-SA 4.0


问:
I want to take only particular value from returned JSON result
I want to take message value, which is under message array and parameter name equal to documentId.(which is bold in bellow code)
bellow code which i have tried but not working as described above.
dynamic obj = JsonConvert.DeserializeObject(JsonDATA);
var recid = obj.messages.message;

JSON Data

```<code>{
  "message": "Success",
  "messages": [
    {
      "parameter": "documentId",
      "message": "8111ffb4-dddc-4d94-b050-bf8fa050181f"
    },
    {
      "parameter": "refNo",
      "message": "INNT19/75254854"
    }
  ]
}
</code>```

Please Help me to take the particular value only in C#.

答:
You need to get the message at the correct index in the messages-array:</p>

```<code>dynamic obj = JsonConvert.DeserializeObject(JsonDATA);
var recid = obj.messages[0].message;
</code>```

Body:
I want to take message value, which is under message array and parameter name equal to documentId.(which is bold in bellow code)
bellow code which i have tried but not working as described above.
dynamic obj = JsonConvert.DeserializeObject(JsonDATA);
var recid = obj.messages.message;

JSON Data

{
  "message": "Success",
  "messages": [
    {
      "parameter": "documentId",
      "message": "8111ffb4-dddc-4d94-b050-bf8fa050181f"
    },
    {
      "parameter": "refNo",
      "message": "INNT19/75254854"
    }
  ]
}

Please Help me to take the particular value only in C#.

Body:
You need to get the message at the correct index in the messages-array:

dynamic obj = JsonConvert.DeserializeObject(JsonDATA);
var recid = obj.messages[0].message;


问:
How can I force a child to have square dimensions in Xamarin?
Let's say I have a button in a stack layout that fills the parent horizontally. How do I make it so that it's vertical height is the same as the horizontal length? Preferably entirely in xaml, but in c# if it must.</p>

答:
You can do this in code like this in code:</p>

```<code>button.SetBinding(VisualElement.HeightRequestProperty, new Binding() { Source = button, Path = "Width" });
</code>```

Body:
You can do this in code like this in code:

button.SetBinding(VisualElement.HeightRequestProperty, new Binding() { Source = button, Path = "Width" });


问:
CORS implementation showing method not allowed for POST request
I am trying to call a WCF service Method using Http POST Request from another Project , it allows GET request but when I try for  POST request it is showing "Method not allowed".

When i tried it shows this error in my Console:

Access to XMLHttpRequest at 'http://localhost:7280/api/values/24' from origin 'http://localhost:6538' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Web API:
Method:

```<code>[WebInvoke(UriTemplate = "/values", Method = "POST", ResponseFormat = WebMessageFormat.Json), CorsEnabled]
        void AddValue(string value);
</code>```

Method Implementation

```<code>public void AddValue(string value)
        {
            string id = nextId.ToString();
            nextId++;
            allValues.Add(id, value);
            string location = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + "/" + id;
            WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(new Uri(location));
        }
</code>```

Client Application:

```<code>$("#post").click(function () {
            var data = "\"" + $("#value").val() + "\"";
            $.ajax({
                url: valuesAddress,
                type: "POST",
                contentType: "application/json",
                data: data,
                success: function (result) {
                    $("#result").text(result);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#result").text(textStatus);
                }
            });
        });
</code>```

I followed
https://code.msdn.microsoft.com/Implementing-CORS-support-c1f9cd4b/view/SourceCode#content
I created web API and client Application as different projects.
Please help to solve this issue.

答:
You have enabled the Cors attribute, when you look into the documentation MSDN provides you'll see that you have to provide the attribute above a class or method.
The code below allows all methods in the class to be called cross domain.

```<code>[EnableCors(origins: "*", headers: "*", methods: "*")]
public class Service1 : IService1
{
  // Details omitted
}
</code>```

The code below enables cors for the GetAllStudents method.

```<code>public class Service1 : IService1
{
  [EnableCors(origins: "*", headers: "*", methods: "*")]
  List<string> GetAllStudents()
  {
    // Details omitted
  }
}
</code>```

Body:
I am trying to call a WCF service Method using Http POST Request from another Project , it allows GET request but when I try for  POST request it is showing "Method not allowed".

When i tried it shows this error in my Console:

Access to XMLHttpRequest at 'http://localhost:7280/api/values/24' from origin 'http://localhost:6538' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Web API:
Method:

[WebInvoke(UriTemplate = "/values", Method = "POST", ResponseFormat = WebMessageFormat.Json), CorsEnabled]
        void AddValue(string value);

Method Implementation

public void AddValue(string value)
        {
            string id = nextId.ToString();
            nextId++;
            allValues.Add(id, value);
            string location = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString() + "/" + id;
            WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(new Uri(location));
        }

Client Application:

$("#post").click(function () {
            var data = "\"" + $("#value").val() + "\"";
            $.ajax({
                url: valuesAddress,
                type: "POST",
                contentType: "application/json",
                data: data,
                success: function (result) {
                    $("#result").text(result);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $("#result").text(textStatus);
                }
            });
        });

I followed
https://code.msdn.microsoft.com/Implementing-CORS-support-c1f9cd4b/view/SourceCode#content
I created web API and client Application as different projects.
Please help to solve this issue.

Body:
You have enabled the Cors attribute, when you look into the documentation MSDN provides you'll see that you have to provide the attribute above a class or method.
The code below allows all methods in the class to be called cross domain.

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class Service1 : IService1
{
  // Details omitted
}

The code below enables cors for the GetAllStudents method.

public class Service1 : IService1
{
  [EnableCors(origins: "*", headers: "*", methods: "*")]
  List<string> GetAllStudents()
  {
    // Details omitted
  }
}


问:
Bash script behaves unexpected / Strange
First I want to apologize for being an absolute noob at programming, writing scripts, etc.
I'm running a FreeNAS Server and a Raspberry Pi which I'd like to include a sh-Script which should check if 8 clients (IP addresses) are online. If yes they should stop but if all IP's are offline, it should perform another task / script.

Here's my problem: On the internet (src: https://www.tech-blogger.net/freenas-automatisch-bei-nicht-benutzung-abschalten/) I found a script which checks specific IP's and if they're offline it should shutdown automatically. When I ping those addresses I get 100% package lost which indicates that they are offline. But the script echos me that at least one client is offline. Because I'm not THAT dumb I assume that it has something to do with my code. Does anyone know what goes wrong with my Script?:

```<code>HOST1=192.168.1.32
HOST2=192.168.1.33
HOST3=192.168.1.34
HOST4=192.168.1.35
HOST5=192.168.1.36

_exit () {
case $1 in
1) echo „No Shutdown – At least one PC is online“ ;;
2) echo „No PC is online – Shutdown“ ; shutdown -p now ;;
esac
exit $1;
}

#Check if IPs are online
if [ `ping -c 1 -i 1 $HOST1 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST2 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST3 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST4 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST5 | grep -wc 100.0%` -eq 0 ] ; then _exit 1;

#All Clients are offline, shutdown
else
_exit 2
fi
fi
</code>```

答:
I am not 100 % sure if I get your Problem right. But I think you should try to replace || with && in your if statement.

|| = or
&& = and

Thus it will only go into the shutdown parts, when all Clients are off.

edit:

```<code>ping -c 1 -i 1 192.168.1.36
PING 192.168.1.36 (192.168.1.36) 56(84) bytes of data.
From 62.155.241.85 icmp_seq=1 Destination Host Unreachable

--- 192.168.1.36 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms
</code>```

It's 100% packet loss not 100.0%. Thus you check for something that does not occur.

```<code>#!/bin/bash

HOST1=192.168.1.32
HOST2=192.168.1.33
HOST3=192.168.1.34
HOST4=192.168.1.35
HOST5=192.168.1.36

_exit () {
case $1 in
1) echo „No Shutdown – At least one PC is online“ ;;
2) echo „No PC is online – Shutdown“ ;; # shutdown -p now ;;
esac
exit $1;
}

#Check if IPs are online
if [ `ping -c 1 -i 1 $HOST1 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST2 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST3 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST4 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST5 | grep -wc 100%` -eq 0 ] ; then _exit 1;

#All Clients are offline, shutdown
else
_exit 2
fi
</code>```

This works as expected ( on my machine ). :-)

Body:
First I want to apologize for being an absolute noob at programming, writing scripts, etc.
I'm running a FreeNAS Server and a Raspberry Pi which I'd like to include a sh-Script which should check if 8 clients (IP addresses) are online. If yes they should stop but if all IP's are offline, it should perform another task / script.

Here's my problem: On the internet (src: https://www.tech-blogger.net/freenas-automatisch-bei-nicht-benutzung-abschalten/) I found a script which checks specific IP's and if they're offline it should shutdown automatically. When I ping those addresses I get 100% package lost which indicates that they are offline. But the script echos me that at least one client is offline. Because I'm not THAT dumb I assume that it has something to do with my code. Does anyone know what goes wrong with my Script?:

HOST1=192.168.1.32
HOST2=192.168.1.33
HOST3=192.168.1.34
HOST4=192.168.1.35
HOST5=192.168.1.36

_exit () {
case $1 in
1) echo „No Shutdown – At least one PC is online“ ;;
2) echo „No PC is online – Shutdown“ ; shutdown -p now ;;
esac
exit $1;
}

#Check if IPs are online
if [ `ping -c 1 -i 1 $HOST1 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST2 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST3 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST4 | grep -wc 100.0%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST5 | grep -wc 100.0%` -eq 0 ] ; then _exit 1;

#All Clients are offline, shutdown
else
_exit 2
fi
fi

Body:
I am not 100 % sure if I get your Problem right. But I think you should try to replace || with && in your if statement.

|| = or
&& = and

Thus it will only go into the shutdown parts, when all Clients are off.

edit:

ping -c 1 -i 1 192.168.1.36
PING 192.168.1.36 (192.168.1.36) 56(84) bytes of data.
From 62.155.241.85 icmp_seq=1 Destination Host Unreachable

--- 192.168.1.36 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms

It's 100% packet loss not 100.0%. Thus you check for something that does not occur.

#!/bin/bash

HOST1=192.168.1.32
HOST2=192.168.1.33
HOST3=192.168.1.34
HOST4=192.168.1.35
HOST5=192.168.1.36

_exit () {
case $1 in
1) echo „No Shutdown – At least one PC is online“ ;;
2) echo „No PC is online – Shutdown“ ;; # shutdown -p now ;;
esac
exit $1;
}

#Check if IPs are online
if [ `ping -c 1 -i 1 $HOST1 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST2 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST3 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST4 | grep -wc 100%` -eq 0 ] || [ `ping -c 1 -i 1 $HOST5 | grep -wc 100%` -eq 0 ] ; then _exit 1;

#All Clients are offline, shutdown
else
_exit 2
fi

This works as expected ( on my machine ). :-)


问:
Convert list of tuple-1 of float to set of int
After querying a database, I get a result r of the following format:

```<code>r = [(123.0,), (456.0,), (789.0,)]
</code>```

That is a list of tuples, each with one item which is a float (that is actually an int).

I would like to convert that to a set of ints:

```<code>s = {123, 456, 789}
</code>```

I expected this to be a trivial map(), but I can't seem to write it. How do I tell map() I want to take the first element of the tuple?

I know that int(r[0][0]) gives me the first element of my set, int(r[1][0]) the second, int(r[2][0]) the third and so on, but how do I "industrialize" this?

答:
Using map:

```<code>set(map(lambda x: int(x[0]), r))
</code>```

Body:
After querying a database, I get a result r of the following format:

r = [(123.0,), (456.0,), (789.0,)]

That is a list of tuples, each with one item which is a float (that is actually an int).

I would like to convert that to a set of ints:

s = {123, 456, 789}

I expected this to be a trivial map(), but I can't seem to write it. How do I tell map() I want to take the first element of the tuple?

I know that int(r[0][0]) gives me the first element of my set, int(r[1][0]) the second, int(r[2][0]) the third and so on, but how do I "industrialize" this?

Body:
Using map:

set(map(lambda x: int(x[0]), r))


问:
linked list the head always is set to NULL
I'm trying to add domino tales into a linked list but each time I make a call to the function add_domino(struct Domino *list, int a ,int b) the head always stays NULL:

```<code>void add_domino(struct Domino *list, int a ,int b) {
    struct Domino *D = malloc(sizeof(struct Domino));
    D->a = a;
    D->b = b;
    D->next = NULL;

    if(list == NULL) {
        list = D;
    } else {
        struct Domino *p;
        p = list;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = D;
    }
}
</code>```

答:
Either return the updated head-pointer, and use it like:

```<code>struct Domino* list = NULL;
list = add_domino(list, 1, 2);
</code>```

Or pass a pointer to pointer, and use it like:

```<code>struct Domino* list = NULL;
add_domino(&list, 1, 2);
</code>```

In addition, your function does not handle insufficient memory.

Next, prefer sizeof *pointer over sizeof(TYPE), as repetition is error-prone, especially where the compiler does not check for mismatches.

And finally, consider adding at the head instead of tail, to avoid repeatedly traversing the whole list. Reversing the list at the end if needed is an O(n) constant space operation.

Body:
I'm trying to add domino tales into a linked list but each time I make a call to the function add_domino(struct Domino *list, int a ,int b) the head always stays NULL:

void add_domino(struct Domino *list, int a ,int b) {
    struct Domino *D = malloc(sizeof(struct Domino));
    D->a = a;
    D->b = b;
    D->next = NULL;

    if(list == NULL) {
        list = D;
    } else {
        struct Domino *p;
        p = list;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = D;
    }
}

Body:
Either return the updated head-pointer, and use it like:

struct Domino* list = NULL;
list = add_domino(list, 1, 2);

Or pass a pointer to pointer, and use it like:

struct Domino* list = NULL;
add_domino(&list, 1, 2);

In addition, your function does not handle insufficient memory.

Next, prefer sizeof *pointer over sizeof(TYPE), as repetition is error-prone, especially where the compiler does not check for mismatches.

And finally, consider adding at the head instead of tail, to avoid repeatedly traversing the whole list. Reversing the list at the end if needed is an O(n) constant space operation.


问:
How to write operator= (with move semantic) and shrink_to_fit functions in my vector implementation?
I have my own vector class:

```<code>#include<iterator>
#include<memory>
#include<iostream>
#include<exception>

using std::cout;
using std::endl;
using std::size_t;

template <class T> class vector
{
public:
    typedef T* iterator;
    typedef const iterator const_iterator;
    typedef size_t size_type;
    typedef T value_type;
    //------------------------------------------
    vector() { create(); }
    explicit vector(size_type n, const T& value = T{}) { create(n, value); }
    vector(const vector& a) { create(a.begin(), a.end()); }
</code>```

And operators:

```<code>    vector& operator=(const vector& a)
    {
        if (&a == this)  return *this;
        uncreate();
        create(a.begin(), a.end());
        return *this;
    }

vector& operator=(const vector&& a)
    {
        if (&a == this)  return *this;
        uncreate();

        //NEED TO WRITE SOME CODE HERE

    }
    ~vector() { uncreate(); } //destructor
    size_type size() const { return avail - data; }
    size_type capacity() const { return limit - data; }
</code>```

And private class members:

```<code>  private:
  iterator data;
  iterator avail;
  iterator limit;

  std::allocator<T> alloc;
//--------------------------------
  void create()
  {
      data = avail = limit = nullptr;
  }
</code>```

And I should write operator = with the move (which I do not know how to write) and copy (which I have done) semantics. Can you help me?

答:
vector& operator=(vector&& a) noexcept
{
    a.swap(*this);
    return *this;
}

void swap(vector& otherVector) noexcept
{
   //swap all member variables here (I took some names that might not be the same, that you use)
   std::swap(otherVector.capacity, capacity);
   std::swap(otherVector.size,   size);
   std::swap(otherVector.buffer,   buffer);
}
```

thats how I would write it (deleting is not needed,because it's swapped and so it will be deleted when the other vector goes out of scope)

obviously when you do not want a swap function you could aswell just put everything the swap function does into the move assignment operator ;)

Body:
I have my own vector class:

#include<iterator>
#include<memory>
#include<iostream>
#include<exception>

using std::cout;
using std::endl;
using std::size_t;

template <class T> class vector
{
public:
    typedef T* iterator;
    typedef const iterator const_iterator;
    typedef size_t size_type;
    typedef T value_type;
    //------------------------------------------
    vector() { create(); }
    explicit vector(size_type n, const T& value = T{}) { create(n, value); }
    vector(const vector& a) { create(a.begin(), a.end()); }

And operators:

    vector& operator=(const vector& a)
    {
        if (&a == this)  return *this;
        uncreate();
        create(a.begin(), a.end());
        return *this;
    }

vector& operator=(const vector&& a)
    {
        if (&a == this)  return *this;
        uncreate();

        //NEED TO WRITE SOME CODE HERE

    }
    ~vector() { uncreate(); } //destructor
    size_type size() const { return avail - data; }
    size_type capacity() const { return limit - data; }

And private class members:

  private:
  iterator data;
  iterator avail;
  iterator limit;

  std::allocator<T> alloc;
//--------------------------------
  void create()
  {
      data = avail = limit = nullptr;
  }

And I should write operator = with the move (which I do not know how to write) and copy (which I have done) semantics. Can you help me?

Body:
vector& operator=(vector&& a) noexcept
{
    a.swap(*this);
    return *this;
}

void swap(vector& otherVector) noexcept
{
   //swap all member variables here (I took some names that might not be the same, that you use)
   std::swap(otherVector.capacity, capacity);
   std::swap(otherVector.size,   size);
   std::swap(otherVector.buffer,   buffer);
}

thats how I would write it (deleting is not needed,because it's swapped and so it will be deleted when the other vector goes out of scope)

obviously when you do not want a swap function you could aswell just put everything the swap function does into the move assignment operator ;)


问:
Different asp:menu on a user basis
I have a oracle database which stores menu and user data, for a local Intranet.

The data includes which usesr have access to which pages.

Originally I created a class which extened the StaticSiteMapProvider class, however when this went in to the testing environment, i found that this was cached for the whole site (and not on a user basis).  After reading up on line on various forums, it was suggested that I should inherit from SiteMapProvider as this would enable me to have a seperated instance of thet SiteMapProvider and ASP:MENU item on a user basis, however this still hasn't solved the problem.

Currently I have a user control, which conrains the asp:menu, and uses my custom site map provider as its data source.

Could anyone suggest how I can display the menu on a user basis, driven from database authorisation?

Also the whole menu should still appear to all users, it only after thy click on a menu node that they will find out whether they have access to that page/node.

Thanks

答:
There are two things here. If you have static collection of nodes and then you want to show/hide them based on user accessibility then you should override IsAccessibleToUser
method to tell if the given node if applicable for the current user (accessible from given HttpContext).

In case, your nodes collection/hierarchy changes per user basis then try overriding BuildSiteMap to load different nodes for current user. However, I am a bit doubtful if StaticSiteMapProvider is the correct base class in this case. Probably you need to override from SiteMapProvider.

ContentLicense: CC BY-SA 3.0

Title: Different asp:menu on a user basis


答:
As messages is an array in your JSON, If you need to read any property of perticular element of an array then you need to use index. Something like

```<code>var recid = obj.messages[0].message;
</code>```

Title: I want to take only particular value from returned JSON result

Body:
As messages is an array in your JSON, If you need to read any property of perticular element of an array then you need to use index. Something like

var recid = obj.messages[0].message;


问:
Create both Async and Sync version of Dapper methods without duplicating the code?
Let's say I have a simple class which contains DB access methods. DB access goes over Dapper. What is the easiest way of creating async and sync versions of those methods without duplicating code? Let't take as an example there 2 methods: GetUsers() and GetUsersAsync(). In this case both methods would have the same logic. The only difference would be that, one would call sync and other async version of Dapper method, e.g. Query vs QueryAsync.

Just calling GetUsersAsync().Result is a bad idea. Has anyone solved this problem elegantly enough?

答:
I have done something similar to your problem but with nHibernate.
Check this (part of my file):

These are most important functions that unfortunately must be somehow duplicated.
These functions do the whole repeatable code. Action parameter is what they really need to do (for example: insert) Context is mainly nHibernate session. In nHibernate every operation must be inside a session. GetContextForStatement returns just new session or previously opened valid one.

```<code>    //sync version
    T GeneralExecuteAction<T>(Func<ISession, T> action)
    {
        lastDbError = DbError.Ok;
        using (var ctx = GetContextForStatement())
        {
            try
            {
                T result = action(ctx.session);
                ctx.CommitTransactionIfExists();
                return result;
            }
            catch (Exception ex)
            {
                ctx.RollbackTransactionIfExists();
                lastDbError = new DbError(ex);
                return default(T);
            }
        }
    }

    //async version
    async Task<T> GeneralExecuteAction<T>(Func<ISession, Task<T>> action)
    {
        lastDbError = DbError.Ok;

        using (var ctx = GetContextForStatement())
        {
            try
            {
                T result = await action(ctx.session);
                await ctx.CommitTransactionIfExistsAsync();
                return result;
            }
            catch (Exception ex)
            {
                await ctx.RollbackTransactionIfExistsAsync();
                lastDbError = new DbError(ex);
                return default(T);
            }
        }
    }
</code>```

Now you can just use above functions in your public methods:
For example, sync version of save:

```<code>    public DbError Save<T>(T obj) where T : class
    {
        GeneralExecuteAction((s) =>
        {
            s.Save(obj); //s is nHibernate session
            return true;
        });

        return lastDbError;
    }
</code>```

And async version of save

```<code>    public async Task<DbError> SaveAsync<T>(T obj) where T : class
    {
        await GeneralExecuteAction((s) =>
        {
            s.Save(obj);
            return Task.FromResult(true);
        });

        return lastDbError;
    }
</code>```

Body:
I have done something similar to your problem but with nHibernate.
Check this (part of my file):

These are most important functions that unfortunately must be somehow duplicated.
These functions do the whole repeatable code. Action parameter is what they really need to do (for example: insert) Context is mainly nHibernate session. In nHibernate every operation must be inside a session. GetContextForStatement returns just new session or previously opened valid one.

    //sync version
    T GeneralExecuteAction<T>(Func<ISession, T> action)
    {
        lastDbError = DbError.Ok;
        using (var ctx = GetContextForStatement())
        {
            try
            {
                T result = action(ctx.session);
                ctx.CommitTransactionIfExists();
                return result;
            }
            catch (Exception ex)
            {
                ctx.RollbackTransactionIfExists();
                lastDbError = new DbError(ex);
                return default(T);
            }
        }
    }

    //async version
    async Task<T> GeneralExecuteAction<T>(Func<ISession, Task<T>> action)
    {
        lastDbError = DbError.Ok;

        using (var ctx = GetContextForStatement())
        {
            try
            {
                T result = await action(ctx.session);
                await ctx.CommitTransactionIfExistsAsync();
                return result;
            }
            catch (Exception ex)
            {
                await ctx.RollbackTransactionIfExistsAsync();
                lastDbError = new DbError(ex);
                return default(T);
            }
        }
    }

Now you can just use above functions in your public methods:
For example, sync version of save:

    public DbError Save<T>(T obj) where T : class
    {
        GeneralExecuteAction((s) =>
        {
            s.Save(obj); //s is nHibernate session
            return true;
        });

        return lastDbError;
    }

And async version of save

    public async Task<DbError> SaveAsync<T>(T obj) where T : class
    {
        await GeneralExecuteAction((s) =>
        {
            s.Save(obj);
            return Task.FromResult(true);
        });

        return lastDbError;
    }


问:
How to extract storage account name and blob name from storage uri
I have below  url for azure
https://restoreprojectdb.blob.core.windows.net/bacpacfiles/TestDB.bacpac

I want to extract "restoreprojectdb" and  "bacpacfiles" from the url using regex.

what is the best regex for this?

答:
```<code>https://(?<account>[a-z0-9]{3,24}).blob.core.windows.net/(?<container>[a-z0-9\-]{3,63})/
</code>```

Minds naming rules: https://blogs.msdn.microsoft.com/jmstall/2014/06/12/azure-storage-naming-rules/

Body:
https://(?<account>[a-z0-9]{3,24}).blob.core.windows.net/(?<container>[a-z0-9\-]{3,63})/

Minds naming rules: https://blogs.msdn.microsoft.com/jmstall/2014/06/12/azure-storage-naming-rules/


问:
How to test jquery script in laravel dusk
I am trying to test in Laravel dusk a link that is clicked which calls AJAX JS script which writes to the database and changes the text of the link. The link is a social media Like link and when clicked will change the text to You like this.

Test Code

```<code>$user = factory(User::class)->create();
        factory(Post::class)->create();

        $this->browse(function ($browser) use ($user) {
            $browser->loginAs($user)
                ->visit('/dashboard')
                ->clickLink('Like', 'a');

            $test = $browser->script('return $(".like").text();');
            $broswer->assertSee('You like this');```

JS code executed

$('.like').on('click', function(event) {
        event.preventDefault();
        // Get the parent article node
        var parent = getClosest(event.target, 'article');
        var postId = parseInt(parent.dataset['postid']);
        var parentLike = event.target.parentNode;

        // console.log(event.target.parentNode.classList);
        if (typeof postId == 'number' && postId > 0) {
            $.ajax({
                    method: 'POST',
                    url: route('like'),
                    dataType: "json",
                    data: {
                        postId: postId,
                        _token: $('meta[name="csrf-token"]').attr('content')
                    }
                })
                .done(function(data) {
                    var likeText = updateLikeText(data.message, data.numLikes, parentLike);
                    event.target.text = likeText;
                });
        }
    });

The link text should change to You Like this but in the test code, the text doesn't change. Accessing the site through the browser and clicking on the link manually works file.  How do I tell dusk to execute the JS script
```

答:
Your test doesn't consider the execution time of the AJAX request.

jQuery has a property that indicates whether an AJAX request is active.

You can use it to wait until the request is finished before testing the link text:

$browser->loginAs($user)
    ->visit('/dashboard')
    ->clickLink('Like', 'a');

$browser->waitUntil('!$.active');

$browser->assertSeeIn('.like', 'You like this');
```

Body:
I am trying to test in Laravel dusk a link that is clicked which calls AJAX JS script which writes to the database and changes the text of the link. The link is a social media Like link and when clicked will change the text to You like this.

Test Code

$user = factory(User::class)->create();
        factory(Post::class)->create();

        $this->browse(function ($browser) use ($user) {
            $browser->loginAs($user)
                ->visit('/dashboard')
                ->clickLink('Like', 'a');

            $test = $browser->script('return $(".like").text();');
            $broswer->assertSee('You like this');```

JS code executed

$('.like').on('click', function(event) {
        event.preventDefault();
        // Get the parent article node
        var parent = getClosest(event.target, 'article');
        var postId = parseInt(parent.dataset['postid']);
        var parentLike = event.target.parentNode;

        // console.log(event.target.parentNode.classList);
        if (typeof postId == 'number' && postId > 0) {
            $.ajax({
                    method: 'POST',
                    url: route('like'),
                    dataType: "json",
                    data: {
                        postId: postId,
                        _token: $('meta[name="csrf-token"]').attr('content')
                    }
                })
                .done(function(data) {
                    var likeText = updateLikeText(data.message, data.numLikes, parentLike);
                    event.target.text = likeText;
                });
        }
    });

The link text should change to You Like this but in the test code, the text doesn't change. Accessing the site through the browser and clicking on the link manually works file.  How do I tell dusk to execute the JS script


问:
padding a fieldset, trouble with IE
What is going on with rendering the padding of a fieldset. It behaves as expected in FF and Chrome but fails in IE. This is the code im talking about:

```<code><html>
    <head>
    </head>
    <body>
        <fieldset>
            <legend>Hello world!</legend>
            <div>Lorem ipsum</div>
        </fieldset>
    </body>
</html>
</code>```

And this is the css

```<code>fieldset {
    border: 1px solid black;
    padding: 30px;
    }
    fieldset legend {
        background-color: silver;
    }
    fieldset div {
        border: 1px dotted silver;
    }
</code>```

Can also be seen here:
http://jsfiddle.net/nRAGM/6/

So my question is: how to get the above html to display as intended in IE?

答:
or the really naughty hack (or put it in a conditional [lte IE 8] CSS) version.

```<code>fieldset {
    border: 1px solid black;
    padding: 30px;
}
fieldset legend {
    background-color: silver;
    margin-bottom: 30px\9; /* IE7/8 needs this - same value as top padding on fieldset */
}
fieldset div {
    border: 1px dotted silver;
}
</code>```

margining the bottom of the label the same as the fieldset's top padding does the trick too. obviously no other browser should get both

PS: I think this works for IE6 too

Title: padding a fieldset, trouble with IE

Body:
What is going on with rendering the padding of a fieldset. It behaves as expected in FF and Chrome but fails in IE. This is the code im talking about:

        <fieldset>
            <legend>Hello world!</legend>

Lorem ipsum

        </fieldset>

And this is the css

fieldset {
    border: 1px solid black;
    padding: 30px;
    }
    fieldset legend {
        background-color: silver;
    }
    fieldset div {
        border: 1px dotted silver;
    }

Can also be seen here:
http://jsfiddle.net/nRAGM/6/

So my question is: how to get the above html to display as intended in IE?

Body:
or the really naughty hack (or put it in a conditional [lte IE 8] CSS) version.

fieldset {
    border: 1px solid black;
    padding: 30px;
}
fieldset legend {
    background-color: silver;
    margin-bottom: 30px\9; /* IE7/8 needs this - same value as top padding on fieldset */
}
fieldset div {
    border: 1px dotted silver;
}

margining the bottom of the label the same as the fieldset's top padding does the trick too. obviously no other browser should get both

PS: I think this works for IE6 too


问:
Count columns and sum
I am very new to the SQL, and I have a table with id (question id) and risk areas (risk1, risk2, and risk3).

```<code>+----+-------+------+------+
| id | risk1 | risk2| risk3|
+----+-------+------+------+
| 0  |   h   |   l  |   h  |
| 1  |   m   |   l  |   l  |
| 2  |   h   |   h  |   h  |
| 3  |   l   |   l  |   h  |
+----+-------+------+------+
</code>```

My aim is to calculate the sum of 'h' for individual ids. For example the query should return '2' for id=0, '0' for id=1, '3' for id=2, and '1' for id=3. Any suggestion will be appreciated.

答:
A simple [verbose] query is:</p>

```<code>select
  id,
  case when risk1 = 'h' then 1 end +
  case when risk2 = 'h' then 1 end +
  case when risk3 = 'h' then 1 end as sum_h
from t
</code>```

Title: Count columns and sum

Body:
I am very new to the SQL, and I have a table with id (question id) and risk areas (risk1, risk2, and risk3).

+----+-------+------+------+
| id | risk1 | risk2| risk3|
+----+-------+------+------+
| 0  |   h   |   l  |   h  |
| 1  |   m   |   l  |   l  |
| 2  |   h   |   h  |   h  |
| 3  |   l   |   l  |   h  |
+----+-------+------+------+

My aim is to calculate the sum of 'h' for individual ids. For example the query should return '2' for id=0, '0' for id=1, '3' for id=2, and '1' for id=3. Any suggestion will be appreciated.

Body:
A simple [verbose] query is:

select
  id,
  case when risk1 = 'h' then 1 end +
  case when risk2 = 'h' then 1 end +
  case when risk3 = 'h' then 1 end as sum_h
from t


问:
how to pass an array values to html?
I have an array create in javascript page:

```<code>for (let i=0; i<12; i++){
  var M = Month[M].valueOf();
  TodayMonth.push(M);
}
</code>```

How to pass the "TodayMonth" to HTML ?
which become TodayMonth

I tried {{TodayMonth}}	 --> fail

答:
Considering the above logic works,

Since TodayMonth is an array, you can use a ngFor to display the array value

for example

```<code><p *ngFor = 'let month of TodayMonth'>
{{month}}</p>
</code>```

Title: how to pass an array values to html?

Body:
I have an array create in javascript page:

for (let i=0; i<12; i++){
  var M = Month[M].valueOf();
  TodayMonth.push(M);
}

How to pass the "TodayMonth" to HTML ?
which become TodayMonth

I tried {{TodayMonth}}	 --> fail

Body:
Considering the above logic works,

Since TodayMonth is an array, you can use a ngFor to display the array value

for example

<p *ngFor = 'let month of TodayMonth'>
{{month}}</p>


问:
write OMNET++ output to a text file
Greeting All,

I have two questions regarding OMNET++ output results

1- I have a simulation that uses AODV routing protocol in VANET network, but
when I record pcap for this simulation, it's shown as corrupted or damage even when I spill it to multi pcap file. How can I solve that? is the Inet pcap support AODV?

2-Is there a way to write this output (in below pic) to a text file or exported as excel format (I highlighted with red color).
I need all the information (event #, time, Relevant hop, name, info). I can copy it but it takes a time when I have around 10000 events?

Thanks in advance

答:
If I am not wrong, you should be able to record the information you want with the  statistics methods provided by OMNeT++. You should refer to cOutVector for real-time data recording. Statistical Collection are well explained in Part. 5 of the OMNeT++ TicToc Tutorial 1.

Once you have recorded your data, you can export them from the Browse Data interface (select the vectors you previously recorded in the browse data tab, right click and select Export Data).

Title: write OMNET++ output to a text file


问:
Safari 12.1 unload not firing javascript
I have javascript in  that is not firing in Safari but works on all other browsers (iOS Safari, Chrome, Firefox, Opera, IE).

I've tested this on all other browsers (iOS Safari, Chrome, Firefox, Opera, IE), and this worked on Safari 11.1.

HTML:

body onload="showdiv('Citizenship');"

Javascript:

```<code>    var pages = document.getElementsByClassName("page");

    function showdiv(id_page)
    {
        for(var count_page=0; count_page<pages.length; count_page++)
        {
            str_id = pages.item(count_page).id;
            if (id_page == str_id)
            {
                document.getElementById(str_id).style.display = 'block';
                document.getElementById(str_id).focus();
            } // if (id_page == str_id)
            else
            {
                document.getElementById(str_id).style.display = 'none';
            } // if (id_page == str_id) else
        } // for(var count_page=0; count_page<pages.length; count_page++)
    } // function showdiv(id_page)
</code>```

I get no console error messages.

The page can be found at http://www.ocetacea.net/MAT/EDLT6616/DigitalCitizenship/index.html

My goal is to have only the "What is Digital Citizenship?" after the page loads.

答:
In Safari it seems that the body onload event triggers after all the content of the page has downloaded.

In your case, you have about 40mb of videos that need to finish loading before Safari triggers body onload action. To fix this, you can trigger your showdiv() function another way, for example:

```<code>document.addEventListener('readystatechange', function() {
  if(document.readyState === 'interactive'){
  showdiv('Citizenship');
  }
});
</code>```

Note: This works for me in Safari but I haven't tried other browsers.

Also, you might want to prevent auto-download the videos to save on data transfer costs.

Body:
I have javascript in  that is not firing in Safari but works on all other browsers (iOS Safari, Chrome, Firefox, Opera, IE).

I've tested this on all other browsers (iOS Safari, Chrome, Firefox, Opera, IE), and this worked on Safari 11.1.

HTML:

body onload="showdiv('Citizenship');"

Javascript:

    var pages = document.getElementsByClassName("page");

    function showdiv(id_page)
    {
        for(var count_page=0; count_page<pages.length; count_page++)
        {
            str_id = pages.item(count_page).id;
            if (id_page == str_id)
            {
                document.getElementById(str_id).style.display = 'block';
                document.getElementById(str_id).focus();
            } // if (id_page == str_id)
            else
            {
                document.getElementById(str_id).style.display = 'none';
            } // if (id_page == str_id) else
        } // for(var count_page=0; count_page<pages.length; count_page++)
    } // function showdiv(id_page)

I get no console error messages.

The page can be found at http://www.ocetacea.net/MAT/EDLT6616/DigitalCitizenship/index.html

My goal is to have only the "What is Digital Citizenship?" after the page loads.

Body:
In Safari it seems that the body onload event triggers after all the content of the page has downloaded.

In your case, you have about 40mb of videos that need to finish loading before Safari triggers body onload action. To fix this, you can trigger your showdiv() function another way, for example:

document.addEventListener('readystatechange', function() {
  if(document.readyState === 'interactive'){
  showdiv('Citizenship');
  }
});

Note: This works for me in Safari but I haven't tried other browsers.

Also, you might want to prevent auto-download the videos to save on data transfer costs.


问:
Custom Query with spring CrudRepository
I am learning the JPA framework but I cannot do a custom query.

I already did this tutorial :
https://spring.io/guides/gs/accessing-data-jpa/
And now I want to do a custom query for example "SELECT firstName,lastName FROM Customer"

I tried with :

```<code>public interface CustomerRepository extends CrudRepository<Customer, Long> {

    @Query("SELECT firstName,lastName FROM Customer")
    Iterable<Customer> findAll();

    List<Customer> findByLastName(String lastName);
}
</code>```

But I get java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to hello.Customer

My code is the same as in the tutorial except that on 33 row of Application I call

```<code>for (Customer customer : repository.findAll()) {
                log.info(customer.toString());
            }
</code>```

To test my custom query

I expect to log me the data for every customer but it throw me an exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to hello.Customer

答:
You could use
@Query("SELECT new your.package.Customer(firstName,lastName) FROM Customer")

to obtain the object you want. If you want an object with only firstname and lastname, I would use another object.

Title: Custom Query with spring CrudRepository

Body:
I am learning the JPA framework but I cannot do a custom query.

I already did this tutorial :
https://spring.io/guides/gs/accessing-data-jpa/
And now I want to do a custom query for example "SELECT firstName,lastName FROM Customer"

I tried with :

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    @Query("SELECT firstName,lastName FROM Customer")
    Iterable<Customer> findAll();

    List<Customer> findByLastName(String lastName);
}

But I get java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to hello.Customer

My code is the same as in the tutorial except that on 33 row of Application I call

for (Customer customer : repository.findAll()) {
                log.info(customer.toString());
            }

To test my custom query

I expect to log me the data for every customer but it throw me an exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to hello.Customer


问:
Why updated props are not reflecting in .then function?
I am calling a handleClick function on which call fetchApi action, which  stores response in redux and return a promise to which, I have attached a .then to that in which I should get updated values from redux store, which I am getting outside .then on rerender but not inside .then
you can check this code sandbox https://codesandbox.io/s/what-is-the-reason-z6qt6</p>

```<code>function App(props) {
  console.log(props.fetchApiRes, "outside handleclick");
  const getProps = () => props;

  function handleClick() {
    props.fetchApi().then(() => {
      console.log(props.fetchApiRes, "inside then");
      console.log(getProps().fetchApiRes, "still not getting ....");
    });
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={handleClick}>click</button>
    </div>
  );
}

const mapDisptach = {
  fetchApi
};
const mapProps = ({ fetchReducer }) => {
  return {
    fetchApiRes: fetchReducer.fetchApi
  };
};
</code>```

答:
What I would first advise is transforming your functional App component into class-based one (since this component is not pure functional by its composition).
In that way you would be allowed to have instance methods (like handleClick), have access to lifecycle methods, use props via this, etc. More info here: https://stackoverflow.com/a/37719217/7956790

What the next flow would be is to utilize the power of lifecycle methods like componentDidUpdate which exposes prevProps as the first argument that you can use to compare it with the current props, and execute whatever logic you need accordingly. However, be aware of state manipulation in this method (https://reactjs.org/docs/react-component.html#componentdidupdate)!

Body:
I am calling a handleClick function on which call fetchApi action, which  stores response in redux and return a promise to which, I have attached a .then to that in which I should get updated values from redux store, which I am getting outside .then on rerender but not inside .then
you can check this code sandbox https://codesandbox.io/s/what-is-the-reason-z6qt6

function App(props) {
  console.log(props.fetchApiRes, "outside handleclick");
  const getProps = () => props;

  function handleClick() {
    props.fetchApi().then(() => {
      console.log(props.fetchApiRes, "inside then");
      console.log(getProps().fetchApiRes, "still not getting ....");
    });
  }

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <button onClick={handleClick}>click</button>

  );
}

const mapDisptach = {
  fetchApi
};
const mapProps = ({ fetchReducer }) => {
  return {
    fetchApiRes: fetchReducer.fetchApi
  };
};


答:
This should display each month.

   {{month}}

```

Title: how to pass an array values to html?

Body:
This should display each month.

<div *ngFor="let month of TodayMonth">
   {{month}}
</div>


问:
Element web-app must be declared error in Intellij
I work in a project that I have a logback-test.xml file and the file shows error. It's a multi-module maven project and the file mentioned is provided below,

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
         version="2.5">

  <configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
        <pattern>%d [%t] %-5p %c:%L - %m%n</pattern>
      </encoder>
    </appender>

    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.ratepay" level="ERROR"/>

    <root level="ERROR">
      <appender-ref ref="CONSOLE"/>
    </root>
  </configuration>
</web-app>
</code>```

When I hold the cursor atop of the web-app tag, I get the error as Element web-app must be declared. My colleague use the Eclipse and he doesn't have the same error.

I have seen a few answers for the issue, but, can anyone clearly explain why does it see this?

答:
Remove the following portion for logback.xml from the beginning.

```<code><web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
         version="2.5">
</code>```

Remove the following portion from the last.

```<code></web-app>
</code>```

It is not a web.xml which is deployment descriptor. logback.xml and web.xml are aparently different.

In case of logback.xml, the final structure should be like this given below.

```<code><?xml version="1.0" encoding="UTF-8"?>

  <configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
        <pattern>%d [%t] %-5p %c:%L - %m%n</pattern>
      </encoder>
    </appender>

    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.ratepay" level="ERROR"/>

    <root level="ERROR">
      <appender-ref ref="CONSOLE"/>
    </root>
  </configuration>
</code>```

Body:
I work in a project that I have a logback-test.xml file and the file shows error. It's a multi-module maven project and the file mentioned is provided below,

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
         version="2.5">

  <configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
        <pattern>%d [%t] %-5p %c:%L - %m%n</pattern>
      </encoder>
    </appender>

    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.ratepay" level="ERROR"/>

    <root level="ERROR">
      <appender-ref ref="CONSOLE"/>
    </root>
  </configuration>
</web-app>

When I hold the cursor atop of the web-app tag, I get the error as Element web-app must be declared. My colleague use the Eclipse and he doesn't have the same error.

I have seen a few answers for the issue, but, can anyone clearly explain why does it see this?

Body:
Remove the following portion for logback.xml from the beginning.

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
         version="2.5">

Remove the following portion from the last.

</web-app>

It is not a web.xml which is deployment descriptor. logback.xml and web.xml are aparently different.

In case of logback.xml, the final structure should be like this given below.

<?xml version="1.0" encoding="UTF-8"?>

  <configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
      <encoder>
        <pattern>%d [%t] %-5p %c:%L - %m%n</pattern>
      </encoder>
    </appender>

    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.ratepay" level="ERROR"/>

    <root level="ERROR">
      <appender-ref ref="CONSOLE"/>
    </root>
  </configuration>


问:
Unload MovieClip before Removing?
Is it better to Unload a MovieClip before Removing it off the Stage, in order for its contents to get cleared from RAM and therefore free up RAM better?

Adobe Flash AS2 Documentation:

removeMovieClip() - Removes a movie clip instance.

unloadMovie() - Removes the contents of a movie clip instance.

答:
No. According to the Live Docs:

unloadMovieClip removes the contents
  of a movie clip instance. The
  instance properties and clip handlers
  remain.

To remove the instance, including
  its properties and clip handlers,
  use MovieClip.removeMovieClip().

This means removeMovieClip() will remove all traces of a MovieClip instance, while unloadMovieClip() will only remove the contents of it. It also means unloadMovie() is not necessary to call before calling removeMovieClip().

OwnerDisplayName: Jeremy Rudd

ContentLicense: CC BY-SA 2.5

Title: Unload MovieClip before Removing?

LastEditorDisplayName: Jeremy Rudd

OwnerDisplayName: bzlm


问:
C# foreach iterating rule for collections
How .NET decides for order of items when iterating through collections ?

For example:

```<code>list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}
</code>```

I need this order (accessing collection members):

```<code>for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}
</code>```

Can I safely use foreach with List? What about other types of collections?

答: foreach is fine . You should only look into the internals of how a loop works if you are looking for perfomance ( eg a number cruncher ) . </p>

Body:
How .NET decides for order of items when iterating through collections ?

For example:

list<string> myList = new List<string>();

myList.Add("a");
myList.Add("b");
myList.Add("c");

foreach (string item in myList)
{
    // What's the order of items? a -> b -> c ?
}

I need this order (accessing collection members):

for (int i = 1; i < myList.Count; i++)
{
    string item = myList[i - 1]; // This is the order I need
}

Can I safely use foreach with List? What about other types of collections?


问:
ld: framework not found FBSDKCoreKit clang
I am building an iOS messaging application with Layer+Parse. I have copied the files from the sample project into my exisiting application. At first I had over 40 errors upon building but I have worked it down to one. I have just added the Facebook SKD and I am left with this error:

ld: framework not found FBSDKCoreKit
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help with getting this to go away would help greatly. I have already tried these steps:

Add the -ObjC flag to your project's Other Linker Flags build setting.

"Allow Non-modular Includes in Framework modules" setting to YES in Build settings

Set "Enable Modules" (c and Objective-C) to No

答: If you've switched from adding frameworks manually to using cocoapods, make sure you've removed any reference to FBSDKCoreKit (or any other FBSDK kit) from any existing project which is not the Pods project (look at "Link Binary With Libraries" under "Build Phases").</p>


问:
How to use mat-calendar with reactive forms?
I want to use a calendar component without an input in a reactive form.

I found the component mat-calendar and tried this:

<mat-calendar formControlName="appointment"></mat-calendar>
```

<p>The corresponding TypeScript file has this:</p>

<pre class="lang-js prettyprint-override"><code>this.form = this.formBuilder.group({ appointment: [''] });
</code>```

But an error was shown:

```<code>ERROR Error: No value accessor for form control with name: 'appointment'
</code>```

答:
If you want to use this as a datepicker for a form, then using the Material datepicker is a better option, and it supports reactive form controls out of the box.

However, if you want a static calendar (i.e always visible), and just need to update your form when a user selects a value, then you can listen to it's change event, and set your form value yourself.

<mat-calendar [selected]="form.get('appointment').value" (selectedChange)="updateFormDate($event)"></mat-calendar>

```<code>updateFormDate(value: any) {
    this.form.get('appointment').setValue(value);
}
</code>```

Body:
I want to use a calendar component without an input in a reactive form.

I found the component mat-calendar and tried this:

<mat-calendar formControlName="appointment"></mat-calendar>

The corresponding TypeScript file has this:

this.form = this.formBuilder.group({ appointment: [''] });

But an error was shown:

ERROR Error: No value accessor for form control with name: 'appointment'

Body:
If you want to use this as a datepicker for a form, then using the Material datepicker is a better option, and it supports reactive form controls out of the box.

However, if you want a static calendar (i.e always visible), and just need to update your form when a user selects a value, then you can listen to it's change event, and set your form value yourself.

<mat-calendar [selected]="form.get('appointment').value" (selectedChange)="updateFormDate($event)"></mat-calendar>

updateFormDate(value: any) {
    this.form.get('appointment').setValue(value);
}


问:
Named argument not found VBA compile error
I want to write a code to sort data in an Excel sheet that has 14 columns and every column I am considering as a Key.

When I try to run the following VBA code, I am getting Compile error: Named argument not found.

```<code>Range("O2", Range("O2").End(xlDown).End(xlToRight))
    .Sort Key1:=Range("O2"), Order1:=xlAscending, Key2:=Range("P2"), Order2:=xlAscending, Key3:=Range("Q2"), Order3:=xlAscending,
    Key4:=Range("R2"), Order4:=xlAscending, Key5:=Range("S2"), Order5:=xlAscending, Key6:=Range("T2"), Order6:=xlAscending,
    Key7:=Range("U2"), Order7:=xlAscending, Key8:=Range("V2"), Order8:=xlAscending, Key9:=Range("W2"), Order9:=xlAscending,
    Key10:=Range("X2"), Order10:=xlAscending, Key11:=Range("Y2"), Order11:=xlAscending, Key12:=Range("Z2"), Order12:=xlAscending,
    Key13:=Range("AA2"), Order13:=xlAscending, Key14:=Range("AB2"), Order14:=xlAscending, Header:=xlNo
</code>```

答:
According to the documentation of the Range.Sort method there do only exist 3 Key, Order and DataOption parameter not 14.

```<code>.Sort (Key1, Order1, Key2, Type, Order2, Key3, Order3, Header, OrderCustom, MatchCase, Orientation, SortMethod, DataOption1, DataOption2, DataOption3)
</code>```

You need to change it to use .SortFields

```<code>With Range("O2", Range("O2").End(xlDown).End(xlToRight)).Sort
    .SortFields.Clear
    .SortFields.Add2 Key:=Range("O2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    .SortFields.Add2 Key:=Range("P2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    'and so on … add your other fields here
    .Header = xlNo
    .Apply
End With
</code>```

Body:
I want to write a code to sort data in an Excel sheet that has 14 columns and every column I am considering as a Key.

When I try to run the following VBA code, I am getting Compile error: Named argument not found.

Range("O2", Range("O2").End(xlDown).End(xlToRight))
    .Sort Key1:=Range("O2"), Order1:=xlAscending, Key2:=Range("P2"), Order2:=xlAscending, Key3:=Range("Q2"), Order3:=xlAscending,
    Key4:=Range("R2"), Order4:=xlAscending, Key5:=Range("S2"), Order5:=xlAscending, Key6:=Range("T2"), Order6:=xlAscending,
    Key7:=Range("U2"), Order7:=xlAscending, Key8:=Range("V2"), Order8:=xlAscending, Key9:=Range("W2"), Order9:=xlAscending,
    Key10:=Range("X2"), Order10:=xlAscending, Key11:=Range("Y2"), Order11:=xlAscending, Key12:=Range("Z2"), Order12:=xlAscending,
    Key13:=Range("AA2"), Order13:=xlAscending, Key14:=Range("AB2"), Order14:=xlAscending, Header:=xlNo

Body:
According to the documentation of the Range.Sort method there do only exist 3 Key, Order and DataOption parameter not 14.

.Sort (Key1, Order1, Key2, Type, Order2, Key3, Order3, Header, OrderCustom, MatchCase, Orientation, SortMethod, DataOption1, DataOption2, DataOption3)

You need to change it to use .SortFields

With Range("O2", Range("O2").End(xlDown).End(xlToRight)).Sort
    .SortFields.Clear
    .SortFields.Add2 Key:=Range("O2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    .SortFields.Add2 Key:=Range("P2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    'and so on … add your other fields here
    .Header = xlNo
    .Apply
End With


问:
How to change className?
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the  code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get

"TypeError: Cannot assign to read only property 'className' of object '#'".

So I wonder is there any other way to do it?

```<code>    import React, { Component } from "react";
    import "./styles/style.css";

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          myDiv: [
            <div
              id="firstDiv"
              key={1}
              className={"first"}
              onClick={this.changeClass}
            />
          ]
        };
      }

  changeClass = () => {
    this.setState(prevState => {
      return { myDiv: (prevState.myDiv[0].props.className = "second") };
    });
  };

      render() {
        return <div>{this.state.myDiv.map(div => div)}</div>;
      }
    }

    export default App;
</code>```

答:
You can use Hooks if you use a React version upper than 16.8 </p>

```<code>import React, { useState } from "react"
import "./styles/style.css"

const App = () => {
  const [myClass, setMyClass] = useState("first")

  const changeClass = () => {
    setMyClass("second")
  }

  render() {
    return <div
             id="firstDiv"
             className={myClass}
             onClick={changeClass}>
           </div>;
   }
}

export default App
</code>```

Title: How to change className?

Body:
So I keep div element in my state. I want to change it's className in response to onClick event. I know I could do it with event.target.className but the  code below is only the sample of a biggest application and it's not possible to use it there. As a resultant from changeClass function I get

"TypeError: Cannot assign to read only property 'className' of object '#'".

So I wonder is there any other way to do it?

    import React, { Component } from "react";
    import "./styles/style.css";

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          myDiv: [

          ]
        };
      }

  changeClass = () => {
    this.setState(prevState => {
      return { myDiv: (prevState.myDiv[0].props.className = "second") };
    });
  };

      render() {
        return
{this.state.myDiv.map(div => div)}
;
      }
    }

    export default App;

Body:
You can use Hooks if you use a React version upper than 16.8

import React, { useState } from "react"
import "./styles/style.css"

const App = () => {
  const [myClass, setMyClass] = useState("first")

  const changeClass = () => {
    setMyClass("second")
  }

  render() {
    return <div
             id="firstDiv"
             className={myClass}
             onClick={changeClass}>
           </div>;
   }
}

export default App


问:
I can't import java.util.date in activity
In my project I need to to use current date and time. For this I'm importing java.util.Date.
This import is working fine few hours ago. But I have an error in R file ( r cannot resolve ) and this error is because of some xml mistake. When I resolved that issue and sync project again that error is gone. But after that I cannot able to import (java.util.Date , java.util.Calendar) in any of my project.

I tried to import this in my newly created project. But still not found java.util.Date.
Even in my old projects where this import is working fine few days ago. Currently it is not working and showing red.

```<code>import java.util.Calendar;

import java.util.Date;
</code>```

Date and Calendar are showing in red.

```<code>Date d=new Date();

SimpleDateFormat sdf=new SimpleDateFormat("hh:mm");
</code>```

Above Date and SimpleDateFormat are showing in red.
And when I hover over there and press (control+alt) IDE will give option to import java.sql.Date not java.util.Date.

答:
Sometimes Android studio goes crazy, and it's good to do a Clean project, so I recommend you to do this. I know you did it, but after that, you can Rebuild the project and then close completely Android Studio.

If it does not work just type here on Invalidate cache /restart as shown on the screenshot.

Doing this, it should work, if it does not, make sure your SDK is imported correctly.

Body:
In my project I need to to use current date and time. For this I'm importing java.util.Date.
This import is working fine few hours ago. But I have an error in R file ( r cannot resolve ) and this error is because of some xml mistake. When I resolved that issue and sync project again that error is gone. But after that I cannot able to import (java.util.Date , java.util.Calendar) in any of my project.

I tried to import this in my newly created project. But still not found java.util.Date.
Even in my old projects where this import is working fine few days ago. Currently it is not working and showing red.

import java.util.Calendar;

import java.util.Date;

Date and Calendar are showing in red.

Date d=new Date();

SimpleDateFormat sdf=new SimpleDateFormat("hh:mm");

Above Date and SimpleDateFormat are showing in red.
And when I hover over there and press (control+alt) IDE will give option to import java.sql.Date not java.util.Date.


问:
CoreImage CIColorClamp adjusting to wrong values
I'm trying CIColorClamp on an image which should just keep pixels within a specified range (https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW42) , but when I print before and after results on a black pixel, it gives different numbers from what I did set in parameters. Here is the code:

```<code>let ciImage = CIImage.init(cgImage: image.cgImage!)
let filter = CIFilter("CIColorClamp")!
filter.setDefaults()
filter.setValue(ciImage, forKey: kCIInputImageKey)
filter.setValue(CIVector(x: 0.8, y: 0.8, z: 0.8, w: 0), forKey: "inputMinComponents")
filter.setValue(CIVector(x: 1, y: 1, z: 1, w: 1), forKey: "inputMaxComponents")

let outputCIImage = filter.outputImage!
let context = CIContext.init()
let outputCGImage = context.createCGImage(outputCIImage, from: outputCIImage.extent)
let outputImage = UIImage(cgImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)

</code>```

This should give (0.8, 0.8, 0.8, 1) on a black pixel (0, 0, 0, 1), but when I print it it gives the following:

```<code><CIColorClamp: inputImage=<CIImage: 0x28165d590 extent [0 0 800 160]>
inputMinComponents=[0.8 0.8 0.8 0] inputMaxComponents=[1 1 1 1]>
BEFORE 0.0, 0.0, 0.0, 1.0
AFTER 0.9058823529411765, 0.9058823529411765, 0.9058823529411765, 1.0
</code>```

Is CoreImage doing something else then just min/max? Or I don't know what else can be wrong here.

答:
I guess it's a color matching issue. Core Image performs color matching from input to working to output color space by default. If the color space of your input image differs from the output color space, you might get different pixel values.

Try setting up your CIContext in a way that is doesn't do any color matching at all:

```<code>let context = CIContext(options: [.workingColorSpace: NSNull(), .outputColorSpace: NSNull()])
</code>```

For the color clamp filter this might work since it's simply clamping the values. I'm not sure if the color matrix filter requires some specific color space, though.

You can also perform a Quick Look on the  outputCIImage in the debugger to see a graph of operations that Core Image is actually performing on the image.

Body:
I'm trying CIColorClamp on an image which should just keep pixels within a specified range (https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP30000136-SW42) , but when I print before and after results on a black pixel, it gives different numbers from what I did set in parameters. Here is the code:

let ciImage = CIImage.init(cgImage: image.cgImage!)
let filter = CIFilter("CIColorClamp")!
filter.setDefaults()
filter.setValue(ciImage, forKey: kCIInputImageKey)
filter.setValue(CIVector(x: 0.8, y: 0.8, z: 0.8, w: 0), forKey: "inputMinComponents")
filter.setValue(CIVector(x: 1, y: 1, z: 1, w: 1), forKey: "inputMaxComponents")

let outputCIImage = filter.outputImage!
let context = CIContext.init()
let outputCGImage = context.createCGImage(outputCIImage, from: outputCIImage.extent)
let outputImage = UIImage(cgImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)

This should give (0.8, 0.8, 0.8, 1) on a black pixel (0, 0, 0, 1), but when I print it it gives the following:

<CIColorClamp: inputImage=<CIImage: 0x28165d590 extent [0 0 800 160]>
inputMinComponents=[0.8 0.8 0.8 0] inputMaxComponents=[1 1 1 1]>
BEFORE 0.0, 0.0, 0.0, 1.0
AFTER 0.9058823529411765, 0.9058823529411765, 0.9058823529411765, 1.0

Is CoreImage doing something else then just min/max? Or I don't know what else can be wrong here.

Body:
I guess it's a color matching issue. Core Image performs color matching from input to working to output color space by default. If the color space of your input image differs from the output color space, you might get different pixel values.

Try setting up your CIContext in a way that is doesn't do any color matching at all:

let context = CIContext(options: [.workingColorSpace: NSNull(), .outputColorSpace: NSNull()])

For the color clamp filter this might work since it's simply clamping the values. I'm not sure if the color matrix filter requires some specific color space, though.

You can also perform a Quick Look on the  outputCIImage in the debugger to see a graph of operations that Core Image is actually performing on the image.


问:
I am trying to use datepicker from mdbootstrap but date shows as 0000-00-00 in database
I am using a form to submit date, subject, content text and an image to mysql using php. I see that all the data get inserted into the DB properly except date which shows up as 0000-00-00 in the table row.

I have unable to figure out how to change date format to be sent to DB.

<form action="#" enctype="multipart/form-data" method="post">

           Event Date :
          <input type="date" name='news_event_date' id="date-picker-example" class="form-control datepicker"/>

            Update Header:
            <textarea id="form7" class="md-textarea form-control" rows="1" type="text" name="news_header" ></textarea>

          Update Body:
          <textarea type="text" id="form8" class="md-textarea form-control" name="news_body" rows="2" ></textarea>

          Password :
          <input id="form9" type="password" name="news_password" class="md-textarea form-control" autocomplete="new-password"/>

                  Choose files
                  <input type="file" accept="image/*" name="news_single_file">

              <input  class="file-path validate" type="text" placeholder="Upload one or more files">

          <button class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect" type="submit" name="news_submit" value="Subm"/>

  </form>
```

All values are updated as required apart from date.

答:
Try formatSubmit parameter:

$('.datepicker').pickadate({

formatSubmit: 'yyyy-mm-dd',

})

Body:
I am using a form to submit date, subject, content text and an image to mysql using php. I see that all the data get inserted into the DB properly except date which shows up as 0000-00-00 in the table row.

I have unable to figure out how to change date format to be sent to DB.

<form action="#" enctype="multipart/form-data" method="post">

           Event Date :
          <input type="date" name='news_event_date' id="date-picker-example" class="form-control datepicker"/>

            Update Header:
            <textarea id="form7" class="md-textarea form-control" rows="1" type="text" name="news_header" ></textarea>

          Update Body:
          <textarea type="text" id="form8" class="md-textarea form-control" name="news_body" rows="2" ></textarea>

          Password :
          <input id="form9" type="password" name="news_password" class="md-textarea form-control" autocomplete="new-password"/>

                  Choose files
                  <input type="file" accept="image/*" name="news_single_file">

              <input  class="file-path validate" type="text" placeholder="Upload one or more files">

          <button class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect" type="submit" name="news_submit" value="Subm"/>

  </form>

All values are updated as required apart from date.


问:
How to efficiently find the latest partition from a S3 dataset using Spark
I have dataset that has data added almost everyday, and needs to be processed everyday in a part of a larger ETL.
When I select the partition directly, the query is really fast:

```<code>SELECT * FROM JSON.`s3://datalake/partitoned_table/?partition=2019-05-20`
</code>```

Yet, the issue is that the event type does not generate data on some Sundays, resulting in a non-existing partition on that particular day. Because of this, I cannot use the previous statement to run my daily job.

Another attempt led me to try to have spark find the latest partition of that dataset, in order to be sure the bigger query wouldn't fail:

```<code>SELECT * FROM JSON.`s3://datalake/partitoned_table/`
WHERE partition = (SELECT MAX(partition) FROM JSON.`s3://datalake/partitoned_table/`)
</code>```

This works every time, but it is unbelievably slow.

I found numerous articles and reference on how to build and maintain partitions, yet nothing about how to read them correctly.

Any idea how to have this done properly?

答:
(SELECT MAX(partition) FROM JSON.s3://datalake/partitoned_table/)

This query will be executed as a subquery in Spark.

Reason for slowness

1. Subquery needs to be executed completely before the actual query execution starts.

2. The Above query will list all the S3 files to retrieve the partition information. If the folder has a large number of files, this process will take a long time. Time taken for listing is directly proportional to the number of files.

We could create a table on top of s3://datalake/partitoned_table/ with the partitioning scheme, let's say the name of the table is tbl

You could perform an

ALTER TABLE tbl RECOVER PARTITIONS

which stores the partition information in metastore. This also involves a listing, but it is a one-time operation and spark spawns multiple threads to perform the listing to make it faster.

Then we could fire

```<code>SELECT * FROM tbl WHERE partition = (SELECT MAX(partition) FROM tbl`)
</code>```

Which will get the partition information only from metastore, without having to list the object store which I believe is an expensive operation.

The cost incurred in this approach is that of recovering partitions.

After which all queries will be faster(when data for new partition comes, we need to recover partitions again)

Body:
I have dataset that has data added almost everyday, and needs to be processed everyday in a part of a larger ETL.
When I select the partition directly, the query is really fast:

SELECT * FROM JSON.`s3://datalake/partitoned_table/?partition=2019-05-20`

Yet, the issue is that the event type does not generate data on some Sundays, resulting in a non-existing partition on that particular day. Because of this, I cannot use the previous statement to run my daily job.

Another attempt led me to try to have spark find the latest partition of that dataset, in order to be sure the bigger query wouldn't fail:

SELECT * FROM JSON.`s3://datalake/partitoned_table/`
WHERE partition = (SELECT MAX(partition) FROM JSON.`s3://datalake/partitoned_table/`)

This works every time, but it is unbelievably slow.

I found numerous articles and reference on how to build and maintain partitions, yet nothing about how to read them correctly.

Any idea how to have this done properly?

Body:
(SELECT MAX(partition) FROM JSON.s3://datalake/partitoned_table/)

This query will be executed as a subquery in Spark.

Reason for slowness

1. Subquery needs to be executed completely before the actual query execution starts.

2. The Above query will list all the S3 files to retrieve the partition information. If the folder has a large number of files, this process will take a long time. Time taken for listing is directly proportional to the number of files.

We could create a table on top of s3://datalake/partitoned_table/ with the partitioning scheme, let's say the name of the table is tbl

You could perform an

ALTER TABLE tbl RECOVER PARTITIONS

which stores the partition information in metastore. This also involves a listing, but it is a one-time operation and spark spawns multiple threads to perform the listing to make it faster.

Then we could fire

SELECT * FROM tbl WHERE partition = (SELECT MAX(partition) FROM tbl`)

Which will get the partition information only from metastore, without having to list the object store which I believe is an expensive operation.

The cost incurred in this approach is that of recovering partitions.

After which all queries will be faster(when data for new partition comes, we need to recover partitions again)


问:
How to write a variable into a file made in python 3.7
I'm saving a file of scores from python but it comes up with an error
when I'm trying to save a variable that is a user created and one that changes throughout the program

i tried to change it but it dosent work

def CreateFile():
   global CreateFile
   CreateFile = open("Score.txt", "w")
   CreateFile.write(p1,"Had",p1sc," points")
   CreateFile.write(p2,"Had",p2sc," points")
   if p1sc > p2sc:
      CreateFile.write(p1," won with",p1sc," points")
      CreateFile.write(p2," lost with",p2sc," points")
   elif p2sc > p1sc:
      CreateFile.write(p2," won with",p2sc," points")
      CreateFile.write(p1," lost with",p1sc," points")

print("The score's have been saved in a file called 'Score.txt' ")
CreateFile()
```

<p>p1 and p2 are input variables
p1sc and p2sc are variables that can change</p>

<p>the error message i get is:</p>

<pre class="lang-py prettyprint-override"><code>  Exception has occurred: TypeError
write() takes exactly one argument (4 given)
  File "/Users/joshua/Desktop/aaHomeProjects/Programming/PythonProjects/DiceGame2ElecticBoogaloo.py", line 248, in CreateFile
    CreateFile.write(p1,"Had",p1sc," points")
  File "/Users/joshua/Desktop/aaHomeProjects/Programming/PythonProjects/DiceGame2ElecticBoogaloo.py", line 261, in <module>
    CreateFile()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
</code>```

答:
The specific error you're getting is due to using file.write() incorrectly. Unlike print(), which takes an arbitrary number of positional arguments and automatically concatenates them with spaces, file.write() requires a single string argument.

In your case, you should replace all the calls like write(p1,"Had",p1sc," points") with a format string like write(f"{p1} Had {p1sc} points") (Python 3.6+) or write("{p1} Had {p1sc} points".format(p1=p1, p1sc=p1sc)) (Python 3.5 and older).

Aside from that:

see the comment on global names. As a general rule, avoid declaring global variables if at all possible (for example, you should pass the variables p1, p1sc, p2, p2sc as arguments), and be aware that functions and variables share the same namespace. If you assign a value to CreateFile, you'll overwrite the CreateFile() function and no longer be able to call CreateFile() in the same scope.

It is also common practice in Python to use a with block when opening files, which implicitly closes them after you're done:

--

```<code>def CreateFile(p1, p1sc, p2, p2sc):
   with open("Score.txt", "w") as file:
       file.write(f"{p1} Had {p1sc} points")
       # etc
</code>```

Body:
I'm saving a file of scores from python but it comes up with an error
when I'm trying to save a variable that is a user created and one that changes throughout the program

i tried to change it but it dosent work

def CreateFile():
   global CreateFile
   CreateFile = open("Score.txt", "w")
   CreateFile.write(p1,"Had",p1sc," points")
   CreateFile.write(p2,"Had",p2sc," points")
   if p1sc > p2sc:
      CreateFile.write(p1," won with",p1sc," points")
      CreateFile.write(p2," lost with",p2sc," points")
   elif p2sc > p1sc:
      CreateFile.write(p2," won with",p2sc," points")
      CreateFile.write(p1," lost with",p1sc," points")

print("The score's have been saved in a file called 'Score.txt' ")
CreateFile()

p1 and p2 are input variables
p1sc and p2sc are variables that can change

the error message i get is:

  Exception has occurred: TypeError
write() takes exactly one argument (4 given)
  File "/Users/joshua/Desktop/aaHomeProjects/Programming/PythonProjects/DiceGame2ElecticBoogaloo.py", line 248, in CreateFile
    CreateFile.write(p1,"Had",p1sc," points")
  File "/Users/joshua/Desktop/aaHomeProjects/Programming/PythonProjects/DiceGame2ElecticBoogaloo.py", line 261, in <module>
    CreateFile()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)

Body:
The specific error you're getting is due to using file.write() incorrectly. Unlike print(), which takes an arbitrary number of positional arguments and automatically concatenates them with spaces, file.write() requires a single string argument.

In your case, you should replace all the calls like write(p1,"Had",p1sc," points") with a format string like write(f"{p1} Had {p1sc} points") (Python 3.6+) or write("{p1} Had {p1sc} points".format(p1=p1, p1sc=p1sc)) (Python 3.5 and older).

Aside from that:

see the comment on global names. As a general rule, avoid declaring global variables if at all possible (for example, you should pass the variables p1, p1sc, p2, p2sc as arguments), and be aware that functions and variables share the same namespace. If you assign a value to CreateFile, you'll overwrite the CreateFile() function and no longer be able to call CreateFile() in the same scope.

It is also common practice in Python to use a with block when opening files, which implicitly closes them after you're done:

--

def CreateFile(p1, p1sc, p2, p2sc):
   with open("Score.txt", "w") as file:
       file.write(f"{p1} Had {p1sc} points")
       # etc


问:
How to import Firebase only on client in Sapper?

I'm importing Firebase into my Sapper application, I do not want the imports to be evaluated on the server. How do I make sure imports are only on the client-side?

I am using Sapper to run sapper export which generates the static files. I have tried:

Creating the firebase instance in it's own file and exported the firebase.auth() and firebase.firestore() modules.

Trying to adjust the rollup.config.js to resolve the dependencies differently, as suggested from the error message below. This brings more headaches.

Creating the Firebase instance in client.js. Unsuccessful.

Creating the instance in stores.js. Unsuccessful.

Declaring the variable and assigning it in onMount(). This causes me to have to work in different block scopes. And feels a bit hacky.

The initialization of the app, works fine:

```<code>import firebase from 'firebase/app'

const config = {...}

firebase.initializeApp(config);
</code>```

I have also discovered that if I change the import to just import firebase from 'firebase' I do not get this server error:

 @firebase/app:
Warning: This is a browser-targeted Firebase bundle but it appears it is being run in a Node environment.  If running in a Node environment, make sure you are using the bundle specified by the "main" field in package.json.

If you are using Webpack, you can specify "main" as the first item in
"resolve.mainFields": https://webpack.js.org/configuration/resolve/#resolvemainfields

If using Rollup, use the rollup-plugin-node-resolve plugin and set "module" to false and "main" to true: https://github.com/rollup/rollup-plugin-node-resolve
```

<p>I expected to just export these firebase functionalities from a file and import them into my components like:</p>

<pre class="lang-html prettyprint-override"><code><script>
  import { auth } from "../firebase";
</script>
</code>```

But as soon as that import is include, the dev server crashes. I don't want to use it on the server, since I'm just generating the static files.

Does anyone have some ideas on how to achieve importing only on client side?

答:
So I have spent too much time on this. There isn't really a more elegant solution than onMOunt.

However, I did realize that sapper really should be used for it's SSR capabilities. And I wrote an article about how to get set up on Firebase with Sapper SSR and Cloud Functions:

https://dev.to/eckhardtd/how-to-host-a-sapper-js-ssr-app-on-firebase-hmb

Another solution to original question is to put the Firebase CDN's in the global scope via the src/template.html file.

%sapper.html%

```

<p>and in the component:</p>

<pre class="lang-html prettyprint-override"><code><script>
import { onMount } from 'svelte';
let database, authentication;

onMount(() => {
  database = firebase.firestore();
  authentication = firebase.auth();
});

const authHandler = () => {
  if (process.browser) {
    authentication
    .createUserWithEmailAndPassword()
    .catch(e => console.error(e));
  }
}
</script>

<button on:click={authHandler}>Sign up</button>
</code>```

Body:
I'm importing Firebase into my Sapper application, I do not want the imports to be evaluated on the server. How do I make sure imports are only on the client-side?

I am using Sapper to run sapper export which generates the static files. I have tried:

Creating the firebase instance in it's own file and exported the firebase.auth() and firebase.firestore() modules.

Trying to adjust the rollup.config.js to resolve the dependencies differently, as suggested from the error message below. This brings more headaches.

Creating the Firebase instance in client.js. Unsuccessful.

Creating the instance in stores.js. Unsuccessful.

Declaring the variable and assigning it in onMount(). This causes me to have to work in different block scopes. And feels a bit hacky.

The initialization of the app, works fine:

import firebase from 'firebase/app'

const config = {...}

firebase.initializeApp(config);

I have also discovered that if I change the import to just import firebase from 'firebase' I do not get this server error:

 @firebase/app:
Warning: This is a browser-targeted Firebase bundle but it appears it is being run in a Node environment.  If running in a Node environment, make sure you are using the bundle specified by the "main" field in package.json.

If you are using Webpack, you can specify "main" as the first item in
"resolve.mainFields": https://webpack.js.org/configuration/resolve/#resolvemainfields

If using Rollup, use the rollup-plugin-node-resolve plugin and set "module" to false and "main" to true: https://github.com/rollup/rollup-plugin-node-resolve

I expected to just export these firebase functionalities from a file and import them into my components like:

But as soon as that import is include, the dev server crashes. I don't want to use it on the server, since I'm just generating the static files.

Does anyone have some ideas on how to achieve importing only on client side?

Body:
So I have spent too much time on this. There isn't really a more elegant solution than onMOunt.

However, I did realize that sapper really should be used for it's SSR capabilities. And I wrote an article about how to get set up on Firebase with Sapper SSR and Cloud Functions:

https://dev.to/eckhardtd/how-to-host-a-sapper-js-ssr-app-on-firebase-hmb

Another solution to original question is to put the Firebase CDN's in the global scope via the src/template.html file.

<body>
    <!-- The application will be rendered inside this element,
         because `app/client.js` references it -->
    <div id='sapper'>%sapper.html%</div>

    <!-- Sapper creates a <script> tag containing `app/client.js`
         and anything else it needs to hydrate the app and
         initialise the router -->
    %sapper.scripts%
      <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/6.0.4/firebase-firestore.js"></script>
</body>
</html>

and in the component:

<script>
import { onMount } from 'svelte';
let database, authentication;

onMount(() => {
  database = firebase.firestore();
  authentication = firebase.auth();
});

const authHandler = () => {
  if (process.browser) {
    authentication
    .createUserWithEmailAndPassword()
    .catch(e => console.error(e));
  }
}
</script>

<button on:click={authHandler}>Sign up</button>


问:
Create a waiting page with PHP and twig
I post data to a page and make some checks that take 5-6 seconds. I would like to insert a waiting page to improve the user experience.
My code is like this:

```<code>....functions that take time

echo $twig->render('template.html.twig',[ variables ....]);
</code>```

Because PHP calls the twig template at the end after processing the data I cannot use a javascript solution.

I tried rendering a waiting template first, then process the data and store the output in a session variable then after that send a location header to the results page but I found PHP does not echo the waiting template untill it finishes the whole script even if i call it in the beginning.

```<code>echo $twig->render('waiting.html.twig',[ variables ....]);
....functions that take time
store output as session variable.
send location header to another page that renders the template from the session variable
</code>```

How can I achieve a waiting page?

答:
Simplest solution is to add 'waiting page' inside first page but hide it. When user presses button browser will send request, but will still wait for response showing old page. Here you can show it using JS.
In short - user presses button, you show template (which was already there but hidden) and then browser just waits for response with your template in front.

But best way would be to use AJAX like Patriot suggested.

Title: Create a waiting page with PHP and twig

Body:
I post data to a page and make some checks that take 5-6 seconds. I would like to insert a waiting page to improve the user experience.
My code is like this:

....functions that take time

echo $twig->render('template.html.twig',[ variables ....]);

Because PHP calls the twig template at the end after processing the data I cannot use a javascript solution.

I tried rendering a waiting template first, then process the data and store the output in a session variable then after that send a location header to the results page but I found PHP does not echo the waiting template untill it finishes the whole script even if i call it in the beginning.

echo $twig->render('waiting.html.twig',[ variables ....]);
....functions that take time
store output as session variable.
send location header to another page that renders the template from the session variable

How can I achieve a waiting page?


问:
How to change a file input's FileList programmatically?
I have this input of type "file", and I want to change its files list.  Example:

```<code><input type = "file" id = "fileinput" />
<script type = "text/javascript">
  document.getElementById("fileinput").files = [10];
</script>
</code>```

The problem is that the fileinput element's files list is not set. How do I do it?

答: What you want is using the multiple attribute on the input element. That way, in newer browsers user will be able to select multiple files to upload.

Body:
I have this input of type "file", and I want to change its files list.  Example:

<input type = "file" id = "fileinput" />

The problem is that the fileinput element's files list is not set. How do I do it?