问:
Nuxt application taking more than 4 minutes to compile
I'm building a Nuxt application. I've done some research but found no definitive solution.

I've found a GitHub issue with something similar (https://github.com/nuxt/nuxt.js/issues/3486) but wasn't able to find a definitive solution:

It was compiling "normally", not taking more than 1 minute. I've just added around 300 lines of html to a Vue component. Suddenly went extremely low.

There are no explicit errors, alerts or warning messages, only the performance went extremely low. How to track this performance decrease?

So this is the nuxt.config.js file

```<code>const pkg = require('./package')
const webpack = require("webpack")

module.exports = {
  mode: 'universal',
  debug: true,
  prettify: false,
  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    script: [
      { src: "https://cdn.jsdelivr.net/npm/sweetalert2@8" },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },

  buildDir: '../functions/nuxt',

  build:{
    publicPath: '/',
    vendor: ['axios','firebase', "jquery", 'popper', "bootstrap", 'bootbox'],
    extractCSS: true,
    babel: {
      presets: [
        'es2015',
        'stage-0'
      ],
      plugins: [

        [
          "transform-runtime",
          {
           "polyfill":true,
           "regenerator":true
          },
          "~/plugins/firebase.js",
          "~/plugins/bootboxPlugin.js"
        ],
        new webpack.ProvidePlugin({
          jQuery: 'jquery',
          $: 'jquery',
          jquery: 'jquery'
        })
      ]

    },
    prettify: false
  },
  /*
  ** Global CSS
  */
  css: [
    'bootstrap/dist/css/bootstrap.css'
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [

  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt',
    '@nuxtjs/pwa',
  ],

  /*
  ** Build configuration
  */

  build: {
    prettify: false,
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'
      prettify = false
    }
  }
}
</code>```

I'm not sure where the prettify : false directive should go, so I've tried in many places, because I'm not sure where the vueLoader is happening.

Also in the Nuxt documentation says

Note: This config has been removed since Nuxt 2.0, please use build.loaders.vue instead.

So this made me more confused. Where this build.loaders.vue is happening?

答:
Its not nuxt fault. Blame the prettier. Here is issue that is causing this: https://github.com/prettier/prettier/issues/4784

Solutions:

1) Dont use large nested template, split it into several components -> thats a best solution from terms of code quality

2) Set prettify: false in the loaders options

https://nuxtjs.org/api/configuration-build/#loaders

https://github.com/vuejs/component-compiler-utils/blob/master/lib/compileTemplate.ts#L173

example nuxt config

```<code>export default {
  build: {
    loaders:  {
      vue: {
         prettify: false
      }
    }

  }
}
</code>```

Body:
I'm building a Nuxt application. I've done some research but found no definitive solution.

I've found a GitHub issue with something similar (https://github.com/nuxt/nuxt.js/issues/3486) but wasn't able to find a definitive solution:

It was compiling "normally", not taking more than 1 minute. I've just added around 300 lines of html to a Vue component. Suddenly went extremely low.

There are no explicit errors, alerts or warning messages, only the performance went extremely low. How to track this performance decrease?

So this is the nuxt.config.js file

const pkg = require('./package')
const webpack = require("webpack")

module.exports = {
  mode: 'universal',
  debug: true,
  prettify: false,
  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    script: [
      { src: "https://cdn.jsdelivr.net/npm/sweetalert2@8" },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },

  buildDir: '../functions/nuxt',

  build:{
    publicPath: '/',
    vendor: ['axios','firebase', "jquery", 'popper', "bootstrap", 'bootbox'],
    extractCSS: true,
    babel: {
      presets: [
        'es2015',
        'stage-0'
      ],
      plugins: [

        [
          "transform-runtime",
          {
           "polyfill":true,
           "regenerator":true
          },
          "~/plugins/firebase.js",
          "~/plugins/bootboxPlugin.js"
        ],
        new webpack.ProvidePlugin({
          jQuery: 'jquery',
          $: 'jquery',
          jquery: 'jquery'
        })
      ]

    },
    prettify: false
  },
  /*
  ** Global CSS
  */
  css: [
    'bootstrap/dist/css/bootstrap.css'
  ],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [

  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://bootstrap-vue.js.org/docs/
    'bootstrap-vue/nuxt',
    '@nuxtjs/pwa',
  ],

  /*
  ** Build configuration
  */

  build: {
    prettify: false,
    /*
    ** You can extend webpack config here
    */
    extend(config, ctx) {
      config.devtool = ctx.isClient ? 'eval-source-map' : 'inline-source-map'
      prettify = false
    }
  }
}

I'm not sure where the prettify : false directive should go, so I've tried in many places, because I'm not sure where the vueLoader is happening.

Also in the Nuxt documentation says

Note: This config has been removed since Nuxt 2.0, please use build.loaders.vue instead.

So this made me more confused. Where this build.loaders.vue is happening?

Body:
Its not nuxt fault. Blame the prettier. Here is issue that is causing this: https://github.com/prettier/prettier/issues/4784

Solutions:

1) Dont use large nested template, split it into several components -> thats a best solution from terms of code quality

2) Set prettify: false in the loaders options

https://nuxtjs.org/api/configuration-build/#loaders

https://github.com/vuejs/component-compiler-utils/blob/master/lib/compileTemplate.ts#L173

example nuxt config

export default {
  build: {
    loaders:  {
      vue: {
         prettify: false
      }
    }

  }
}


来源: stackexchange

问:
UISearchBar searchBarCancelButtonClicked not being called using Swift 3
For some reason when I click the circle x cancel button in a UISearchBar the searchBarCancelButtonClicked event is not firing, it worked in a swift 2 project but not in this swift 3 one.

I am now extending my view controller instead of the inline class way but I believe that is working as the searchBarSearchButtonClicked event does work. Here is what I have so far:

```<code>extension MyViewController: UISearchBarDelegate {
   func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
      print("here?")
      searchBar.resignFirstResponder()
      handleCancelSearch()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        if let searchText = searchBar.text {
            performSearchUsing(term:searchText)
        }

    }
}
</code>```

The print is not logged and the function not called. Am I missing something silly?

答:
Maybe you are missing something silly as I did, the "circle x" is not actually the cancel button, and I thought that too, the cancel button comes disabled by default, you can activate it via storyboard on the attributes of the searchBar or you can do it programmatically with:

```<code>searchBar.showsCancelButton = true

</code>```

After that, the method should work.

ContentLicense: CC BY-SA 3.0

Body:
For some reason when I click the circle x cancel button in a UISearchBar the searchBarCancelButtonClicked event is not firing, it worked in a swift 2 project but not in this swift 3 one.

I am now extending my view controller instead of the inline class way but I believe that is working as the searchBarSearchButtonClicked event does work. Here is what I have so far:

extension MyViewController: UISearchBarDelegate {
   func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
      print("here?")
      searchBar.resignFirstResponder()
      handleCancelSearch()
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        if let searchText = searchBar.text {
            performSearchUsing(term:searchText)
        }

    }
}

The print is not logged and the function not called. Am I missing something silly?

Body:
Maybe you are missing something silly as I did, the "circle x" is not actually the cancel button, and I thought that too, the cancel button comes disabled by default, you can activate it via storyboard on the attributes of the searchBar or you can do it programmatically with:

searchBar.showsCancelButton = true

After that, the method should work.

ContentLicense: CC BY-SA 4.0


问:
Make The 3rd row as Header of Dataframe
I have a data in a csv as below, the first row is blank and the second row is filled for only the 4 columns as below,

```<code>        201901                201902           201903       201904
A   X   1           0       1       1
B   Y   0           0       1       1
A   Z   1           0       1       1
B   X   1           0       1       1
A   Y   0           0       0       1
B   Z   1           0       0       1
A   X   0           1       0       1
B   Y   1           1       0       0
A   Z   1           1       0       0
B   X   0           1       1       0
</code>```

If I read the data into csv i will get the data as below

```<code>_c1     _c2     _c3         _c4     _c5     _c6
null           null        null            null       null  null
null           null       201901                201902          201903  201904
A       X       1           0       1       1
B       Y       0           0       1       1
A       Z       1           0       1       1
B       X       1           0       1       1
A       Y       0           0       0       1
B       Z       1           0       0       1
A       X       0           1       0       1
B       Y       1           1       0       0
A       Z       1           1       0       0
B       X       0           1       1       0
</code>```

I have read the datafile without header and removed the not required headers. Now I want to convert the files to have header

```<code>df=spark.read.csv("s3://abc/def/file.csv",header=False)
df=df.where(col("_c3").isNotNull())
</code>```

```<code>Type         Source         201901                 201902           201903  201904
A       X       1           0       1       1
B       Y       0           0       1       1
A       Z       1           0       1       1
B       X       1           0       1       1
A       Y       0           0       0       1
B       Z       1           0       0       1
A       X       0           1       0       1
B       Y       1           1       0       0
A       Z       1           1       0       0
B       X       0           1       1       0
</code>```

答:
you can create a custom schema by defining it something like this

```<code>val customSchema = StructType(Array(
    StructField("yourcolumnheader", StringType, true),
    StructField("yourcolumnheader2", StringType, true),
    StructField("yourcolumnheader3", IntegerType, true),
    StructField("yourcolumnheader4", DoubleType, true)))
</code>```

then use that schema when you read your formatted  ie 3 rows removed CSV file

```<code>df=spark.read.csv("s3://abc/def/file.csv",header=False)
.schema(customeSchema)
</code>```

hope that answers your question.

Title: Make The 3rd row as Header of Dataframe

Body:
I have a data in a csv as below, the first row is blank and the second row is filled for only the 4 columns as below,

        201901                201902           201903       201904
A   X   1           0       1       1
B   Y   0           0       1       1
A   Z   1           0       1       1
B   X   1           0       1       1
A   Y   0           0       0       1
B   Z   1           0       0       1
A   X   0           1       0       1
B   Y   1           1       0       0
A   Z   1           1       0       0
B   X   0           1       1       0

If I read the data into csv i will get the data as below

_c1     _c2     _c3         _c4     _c5     _c6
null           null        null            null       null  null
null           null       201901                201902          201903  201904
A       X       1           0       1       1
B       Y       0           0       1       1
A       Z       1           0       1       1
B       X       1           0       1       1
A       Y       0           0       0       1
B       Z       1           0       0       1
A       X       0           1       0       1
B       Y       1           1       0       0
A       Z       1           1       0       0
B       X       0           1       1       0

I have read the datafile without header and removed the not required headers. Now I want to convert the files to have header

df=spark.read.csv("s3://abc/def/file.csv",header=False)
df=df.where(col("_c3").isNotNull())

Type         Source         201901                 201902           201903  201904
A       X       1           0       1       1
B       Y       0           0       1       1
A       Z       1           0       1       1
B       X       1           0       1       1
A       Y       0           0       0       1
B       Z       1           0       0       1
A       X       0           1       0       1
B       Y       1           1       0       0
A       Z       1           1       0       0
B       X       0           1       1       0

Body:
you can create a custom schema by defining it something like this

val customSchema = StructType(Array(
    StructField("yourcolumnheader", StringType, true),
    StructField("yourcolumnheader2", StringType, true),
    StructField("yourcolumnheader3", IntegerType, true),
    StructField("yourcolumnheader4", DoubleType, true)))

then use that schema when you read your formatted  ie 3 rows removed CSV file

df=spark.read.csv("s3://abc/def/file.csv",header=False)
.schema(customeSchema)

hope that answers your question.


问:
Clang and Gcc disagree on explicit specialization after instantiation
In some code I am reviewing I ran into a case where Clang and Gcc disagree. After looking around awhile I cant seem to figure out who is right.

Disclaimer:  I know there is a better Singleton pattern, but this is the one used in the code.

Notes:

gcc 7.4.0 on Ubuntu (No error)

clang 6.0.0 on Ubuntu (Throws error)

Difference appears to exist for all post C++11 ISO versions, but I did not try earlier.

foo.hh

```<code>#include "sing.hh"

class Foo {
    public:
    Foo();
    ~Foo();
    static Foo *getSingleton(){
        return singleton<Foo>::instance();
    }
};
</code>```

foo.cc

```<code>include "foo.hh"
//removing this line results in the error for clang disappearing
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
int main(){};
</code>```

sing.hh

```<code>template<typename T>
class singleton{
    typedef T *(*GetInstance)(void);
public:

  static GetInstance instance;

};
</code>```

Results:

```<code>$ clang++  foo.cc
foo.cc:3:56: error: explicit specialization of 'instance' after instantiation
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
                                                       ^
./foo.hh:10:32: note: implicit instantiation first required here
        return singleton<Foo>::instance();
                               ^
1 error generated.

$ g++  foo.cc <- No Errors
</code>```

答:
From this answer here and the cpp-reference here.

Explicit specialization may be declared in any scope where its primary
  template may be defined [...].

Explicit specialization has to appear after the non-specialized
  template declaration.

Specialization must be declared before the first use that would cause
  implicit instantiation, in every translation unit where such use
  occurs

If the explicit specialization was in the sing.cpp file, then neither compiler would complain. Alternatively, you can use forward declaration to do the following and both clang and gcc would be happy.

```<code>#include <iostream>

template<typename T>
struct singleton
{
    typedef T *(*GetInstance)(void);

    static GetInstance instance;
};

template<>
singleton<struct Foo>::GetInstance singleton<struct Foo>::instance = nullptr;

struct Foo
{
    static Foo *getSingleton()
    {
        return singleton<Foo>::instance();
    }
};

int main()
{

}
</code>```

Online code example: https://rextester.com/SPZLS83155

Body:
In some code I am reviewing I ran into a case where Clang and Gcc disagree. After looking around awhile I cant seem to figure out who is right.

Disclaimer:  I know there is a better Singleton pattern, but this is the one used in the code.

Notes:

gcc 7.4.0 on Ubuntu (No error)

clang 6.0.0 on Ubuntu (Throws error)

Difference appears to exist for all post C++11 ISO versions, but I did not try earlier.

foo.hh

#include "sing.hh"

class Foo {
    public:
    Foo();
    ~Foo();
    static Foo *getSingleton(){
        return singleton<Foo>::instance();
    }
};

foo.cc

include "foo.hh"
//removing this line results in the error for clang disappearing
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
int main(){};

sing.hh

template<typename T>
class singleton{
    typedef T *(*GetInstance)(void);
public:

  static GetInstance instance;

};

Results:

$ clang++  foo.cc
foo.cc:3:56: error: explicit specialization of 'instance' after instantiation
template<> singleton<Foo>::GetInstance singleton<Foo>::instance = nullptr;
                                                       ^
./foo.hh:10:32: note: implicit instantiation first required here
        return singleton<Foo>::instance();
                               ^
1 error generated.

$ g++  foo.cc <- No Errors

Body:
From this answer here and the cpp-reference here.

Explicit specialization may be declared in any scope where its primary
  template may be defined [...].

Explicit specialization has to appear after the non-specialized
  template declaration.

Specialization must be declared before the first use that would cause
  implicit instantiation, in every translation unit where such use
  occurs

If the explicit specialization was in the sing.cpp file, then neither compiler would complain. Alternatively, you can use forward declaration to do the following and both clang and gcc would be happy.

#include <iostream>

template<typename T>
struct singleton
{
    typedef T *(*GetInstance)(void);

    static GetInstance instance;
};

template<>
singleton<struct Foo>::GetInstance singleton<struct Foo>::instance = nullptr;

struct Foo
{
    static Foo *getSingleton()
    {
        return singleton<Foo>::instance();
    }
};

int main()
{

}

Online code example: https://rextester.com/SPZLS83155


问:
cURL request with HttpClient - how to set the timeout on the server connection (WinInet)
I am sending cURL request using HttpClient through the method described here under.

The parameter used for this method are:

SelectedProxy = a custom class that stores my proxy's parameters

Parameters.WcTimeout = the timeout

url, header, content = the cURL request (based on this tool to convert to C# https://curl.olsh.me/).

```<code>        const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
        const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
        ServicePointManager.SecurityProtocol = Tls12;
        string source = "";

        using (var handler = new HttpClientHandler())
        {
            handler.UseCookies = usecookies;
            WebProxy wp = new WebProxy(SelectedProxy.Address);
            handler.Proxy = wp;

            using (var httpClient = new HttpClient(handler))
            {
                httpClient.Timeout = Parameters.WcTimeout;

                using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), url))
                {
                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
                        }
                    }
                    if (content != "")
                    {
                        request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
                    }

                    HttpResponseMessage response = new HttpResponseMessage();
                    try
                    {
                        response = await httpClient.SendAsync(request);
                    }
                    catch (Exception e)
                    {
                        //Here the exception happens
                    }
                    source = await response.Content.ReadAsStringAsync();
                }
            }
        }
        return source;
</code>```

If I am running this without proxy, it works like a charm.
When I send a request using a proxy which I tested first from Chrome, I have the following error on my try {} catch {}. Here is the error tree

```<code>{"An error occurred while sending the request."}
    InnerException {"Unable to connect to the remote server"}
        InnerException {"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ProxyAdress]"}
        SocketErrorCode: TimedOut
</code>```

By using a Stopwatch I see that the TimedOut occurred after around 30 sec.

I tried a few different handler based on the following links What's the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?, HttpClient Timeout confusion or with the WinHttpHandler.

It's worth noting that WinHttpHandler allow for a different error code, i.e. Error 12002 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'The operation timed out'. The underlying reason is the same though it helped to target where it bugs (i.e. WinInet) which confirms also what @DavidWright was saying regarding that timeouts from HttpClient manages a different part of the request sending.

Hence my issue is coming from the time it takes to establish a connection to the server, which triggers the 30sec timeout from WinInet.

My question is then How to change those timeout?

On a side note, it's worth noting that Chrome, which uses WinInet, does not seem to suffer from this timeout, nor Cefsharp on which a big part of my app is based, and through which the same proxies can properly send requests.

答:
I have had the same problem with HttpClient. Two things need to happen for SendAsync to return: first, setting up the TCP channel over which the communication occurs (the SYN, SYN/ACK, ACK handshake, if you're familiar with that) and second getting back the data that constitutes the HTTP response over that TCP channel. HttpClient's timeout only applies to the second part. The timeout for the first part is governed by the OS's network subsystem, and it's quite difficult to change that timeout in .NET code.

(Here's how you can reproduce this effect. Set up a working client/server connection between two machines, so you know that name resolution, port access, listening, and client and server logic all works. Then unplug the network cable on the server and re-run the client request. It will time out with the OS's default network timeout, regardless of what timeout you set on your HttpClient.)

The only way I know around this is to start your own delay timer on a different thread and cancel the SendAsync task if the timer finishes first. You can do this using Task.Delay and Task.WaitAny or by creating a CancellationTokenSource with your desired timeone (which essentially just does the first way under the hood). In either case you will need to be careful about cancelling and reading exceptions from the task that loses the race.

Body:
I am sending cURL request using HttpClient through the method described here under.

The parameter used for this method are:

SelectedProxy = a custom class that stores my proxy's parameters

Parameters.WcTimeout = the timeout

url, header, content = the cURL request (based on this tool to convert to C# https://curl.olsh.me/).

        const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
        const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
        ServicePointManager.SecurityProtocol = Tls12;
        string source = "";

        using (var handler = new HttpClientHandler())
        {
            handler.UseCookies = usecookies;
            WebProxy wp = new WebProxy(SelectedProxy.Address);
            handler.Proxy = wp;

            using (var httpClient = new HttpClient(handler))
            {
                httpClient.Timeout = Parameters.WcTimeout;

                using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), url))
                {
                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
                        }
                    }
                    if (content != "")
                    {
                        request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
                    }

                    HttpResponseMessage response = new HttpResponseMessage();
                    try
                    {
                        response = await httpClient.SendAsync(request);
                    }
                    catch (Exception e)
                    {
                        //Here the exception happens
                    }
                    source = await response.Content.ReadAsStringAsync();
                }
            }
        }
        return source;

If I am running this without proxy, it works like a charm.
When I send a request using a proxy which I tested first from Chrome, I have the following error on my try {} catch {}. Here is the error tree

{"An error occurred while sending the request."}
    InnerException {"Unable to connect to the remote server"}
        InnerException {"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ProxyAdress]"}
        SocketErrorCode: TimedOut

By using a Stopwatch I see that the TimedOut occurred after around 30 sec.

I tried a few different handler based on the following links What's the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?, HttpClient Timeout confusion or with the WinHttpHandler.

It's worth noting that WinHttpHandler allow for a different error code, i.e. Error 12002 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'The operation timed out'. The underlying reason is the same though it helped to target where it bugs (i.e. WinInet) which confirms also what @DavidWright was saying regarding that timeouts from HttpClient manages a different part of the request sending.

Hence my issue is coming from the time it takes to establish a connection to the server, which triggers the 30sec timeout from WinInet.

My question is then How to change those timeout?

On a side note, it's worth noting that Chrome, which uses WinInet, does not seem to suffer from this timeout, nor Cefsharp on which a big part of my app is based, and through which the same proxies can properly send requests.


问:
How to call multiple APIs in parallel for load testing (using Gatling)?
I'm currently trying to load test my APIs using Gatling, but I have a very specific test that I want to perform. I would like to simulate a Virtual User calling all my APIs (the 16 of them) simultaneously. I would like to repeat this multiple times so I can have an idea of the average time it takes for my APIs to respond when called all together at the same time.

The method I used was :

Creating a Scenario for each of my API.

Calling every single one of the scenarios in my SetUp()

Injecting 60 users in every scenarios with a throttle of 1 Request per Second & holding it for 60 seconds.

The aim was to have 60 iterations of what I wanted.

FYI I'm using Gatling 3.1.2

//This is what all my scenarios look like

val bookmarkScn = scenario("Bookmarks").exec(http("Listing bookmarks")
                .get("/bookmarks")
                .check(status.is(200))
            )

//My setUp

setUp(
    bookmarkScn.inject(
        atOnceUsers(60)
    ).throttle(
        jumpToRps(1),
        holdFor(60)
    ),
    permissionScn.inject(
        atOnceUsers(60)
    ).throttle(
        jumpToRps(1),
        holdFor(60)
    ),

//Adding all the scenarios one after the other

).protocols(httpConfig)

```

I got some results with this method but they are not at all what I was expecting and if I keep the test going for too long eventually every call just timeout.

It was supposed to just take more time than usual (e.g from 100ms per API to 300ms).

My question is : Is this method correct ? Can you help me achieve my goal ?

答:
What you've got should work, but there's probably an easier way to specify this injection. Instead of

```<code>bookmarkScn.inject(
    atOnceUsers(60)
).throttle(
    jumpToRps(1),
    holdFor(60)
),
</code>```

you could use

```<code>bookmarkScn.inject(
    constantUsersPerSec(1) during (60 seconds)
),
</code>```

in terms of your results, I'd expect that the issue lies somewhere downstream of gatling - 16 concurrent users making simple GET requests is very straightforward for Gatling. You may have issues elsewhere with performance in your app or infrastructure in-between.

Body:
I'm currently trying to load test my APIs using Gatling, but I have a very specific test that I want to perform. I would like to simulate a Virtual User calling all my APIs (the 16 of them) simultaneously. I would like to repeat this multiple times so I can have an idea of the average time it takes for my APIs to respond when called all together at the same time.

The method I used was :

Creating a Scenario for each of my API.

Calling every single one of the scenarios in my SetUp()

Injecting 60 users in every scenarios with a throttle of 1 Request per Second & holding it for 60 seconds.

The aim was to have 60 iterations of what I wanted.

FYI I'm using Gatling 3.1.2

//This is what all my scenarios look like

val bookmarkScn = scenario("Bookmarks").exec(http("Listing bookmarks")
                .get("/bookmarks")
                .check(status.is(200))
            )

//My setUp

setUp(
    bookmarkScn.inject(
        atOnceUsers(60)
    ).throttle(
        jumpToRps(1),
        holdFor(60)
    ),
    permissionScn.inject(
        atOnceUsers(60)
    ).throttle(
        jumpToRps(1),
        holdFor(60)
    ),

//Adding all the scenarios one after the other

).protocols(httpConfig)

I got some results with this method but they are not at all what I was expecting and if I keep the test going for too long eventually every call just timeout.

It was supposed to just take more time than usual (e.g from 100ms per API to 300ms).

My question is : Is this method correct ? Can you help me achieve my goal ?

Body:
What you've got should work, but there's probably an easier way to specify this injection. Instead of

bookmarkScn.inject(
    atOnceUsers(60)
).throttle(
    jumpToRps(1),
    holdFor(60)
),

you could use

bookmarkScn.inject(
    constantUsersPerSec(1) during (60 seconds)
),

in terms of your results, I'd expect that the issue lies somewhere downstream of gatling - 16 concurrent users making simple GET requests is very straightforward for Gatling. You may have issues elsewhere with performance in your app or infrastructure in-between.


问:
Can't generate x64 version of apks in my project
According to the new Play Store policy * that will take effect in August * I need to ensure that my app provides not only the 32-bit version, but also a 64-bit version, but when I try to generate that version through NDK, I always get the same libs. After trying and trying and trying, I just received an apk without any kind of "lib" folder.

I've tried to set NDK with abiFilters on gradle and got no changes...

```<code>defaultConfig {
    applicationId "com.myproject.supermidia"
    minSdkVersion 17
    targetSdkVersion 26
    versionCode 20192201
    versionName "2.4"
    multiDexEnabled true
    vectorDrawables.useSupportLibrary = true
}
</code>```

答:
In order to build for ARM (and the x86 emulator), the splits should look alike this. x86_64 might be a little useless, because the x86_64 emulator is slow and there is no hardware I'd be aware of ...

```<code>android {

    defaultConfig {

        ...
        externalNativeBuild {
            cmake {
                arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_CPP_FEATURES=rtti exceptions"
            }
        }
    }

    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
        }
    }

    splits {
        abi {
            enable true
            reset()
            include "armeabi-v7a", "arm64-v8a", "x86"
            universalApk true
        }
    }
}
</code>```

Body:
According to the new Play Store policy * that will take effect in August * I need to ensure that my app provides not only the 32-bit version, but also a 64-bit version, but when I try to generate that version through NDK, I always get the same libs. After trying and trying and trying, I just received an apk without any kind of "lib" folder.

I've tried to set NDK with abiFilters on gradle and got no changes...

defaultConfig {
    applicationId "com.myproject.supermidia"
    minSdkVersion 17
    targetSdkVersion 26
    versionCode 20192201
    versionName "2.4"
    multiDexEnabled true
    vectorDrawables.useSupportLibrary = true
}

Body:
In order to build for ARM (and the x86 emulator), the splits should look alike this. x86_64 might be a little useless, because the x86_64 emulator is slow and there is no hardware I'd be aware of ...

android {

    defaultConfig {

        ...
        externalNativeBuild {
            cmake {
                arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_CPP_FEATURES=rtti exceptions"
            }
        }
    }

    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
        }
    }

    splits {
        abi {
            enable true
            reset()
            include "armeabi-v7a", "arm64-v8a", "x86"
            universalApk true
        }
    }
}


问:
PHP URL Rewriting for the link
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       document.location="delete_row.php";
       return false;
     }
</script>
</head>

<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th> </th>
<?php
while($row = mysql_fetch_array($result))
  {?>
  <tr>
  <td><?php echo $row['name'];?></td>
  <td><?php echo $row['age'];?></td>
  <td><a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete</a></td>
  </tr>
  <?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>
</code>```

This is the PHP part with file name delete_row.php

```<code><?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>
</code>```

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

答:
You should not use GET for this kind of action at all as GET is considered as being a safe method:

[…] the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".

Use a POST form instead where you can use a hidden form control for the ID:

```<code><form action="delete_row.php" method="post">
    <input type="hidden" name="id" value="5">
    <input type="submit" value="Delete row">
</form>
</code>```

Apart from the safe method reason, using POST instead of GET is also not that vulnerable against Cross-Site Request Forgery attacks. At that point you should also think about using so called CSRF tokens to further reducing the chances of successful CSRF attacks.

Title: PHP URL Rewriting for the link

Body:
I have delete link in a table for each row.
When I click on that link, I pass the id to a page which deletes that row using that id.
My last portion of my url looks like delete_row.php?id=5
Can I show only the delete_row.php with out showing the ?id=5

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>

Name
Age

<?php
while($row = mysql_fetch_array($result))
  {?>

  <?php echo $row['name'];?>
  <?php echo $row['age'];?>
  <a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete

  <?php } ?>

<?php
mysql_close($con);
?>

This is the PHP part with file name delete_row.php

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?>

The error which i am getting is
Notice: Undefined variable: id in C:\MYXAMPP\delete_row.php on line 13

Body:
You should not use GET for this kind of action at all as GET is considered as being a safe method:

[…] the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".

Use a POST form instead where you can use a hidden form control for the ID:

<form action="delete_row.php" method="post">
    <input type="hidden" name="id" value="5">
    <input type="submit" value="Delete row">
</form>

Apart from the safe method reason, using POST instead of GET is also not that vulnerable against Cross-Site Request Forgery attacks. At that point you should also think about using so called CSRF tokens to further reducing the chances of successful CSRF attacks.


问:
Is there a way to access Flutter resources from native code?
I want to use the main logo from Flutter resources in my native Android code — for example, to display a notification. As you know, in Android you usually get resources from drawable folder like this R.drawable.icon. But then I have to copy the icon to Android drawable folder as well. Maybe there is a way to access Flutter resources (read — assets) from native code?

答:
There's a nice section sort-of about this in the flutter documentation.

Given an asset "icons/heart.png", for android (since 1.22):

FlutterLoader loader = FlutterInjector.instance().flutterLoader();

String key = loader.getLookupKeyForAsset("icons/heart.png");

For iOS (swift):

let key = registrar.lookupKey(forAsset: "icons/heart.png");

let path = Bundle.main.path(forResource: key, ofType: nil)

For iOS (obj-c):

NSString* key = [registrar lookupKeyForAsset:@"icons/heart.png"];

NSString* path = [[NSBundle mainBundle] pathForResource:key
ofType:nil];

For android previous to Flutter version 1.22 (deprecated):

AssetManager assetManager = registrar.context().getAssets();

String key = registrar.lookupKeyForAsset("icons/heart.png");

AssetFileDescriptor fd = assetManager.openFd(key);

However, you won't be able to share a drawable item directly to flutter, and the main icon is a bit of a special case that you definitely can't share with flutter either. Flutter doesn't know what a 'drawable' is but rather deals with resources its own cross-platform way.


问:
Changing sprite at runtime causes it to stop resizing - Unity
I'm changing the sprite on an Image Component at runtime, and this causes it to stop resizing with the Image's RectTransform and just stays a fixed size. The code that changes the sprite is in Start() method:

```<code>public Sprite mySprite;

 GetComponent<Image>().sprite = mySprite
</code>```

If I comment it out the image resizes fine so I know this is the problem.

Also, this exact code worked fine in Unity 4, but ever since I updated it won't work.

答: Check if your Image component has Preserve Aspect ticked on, and if it does just untick it. Should solve your problem.</p>

Body:
I'm changing the sprite on an Image Component at runtime, and this causes it to stop resizing with the Image's RectTransform and just stays a fixed size. The code that changes the sprite is in Start() method:

public Sprite mySprite;

 GetComponent<Image>().sprite = mySprite

If I comment it out the image resizes fine so I know this is the problem.

Also, this exact code worked fine in Unity 4, but ever since I updated it won't work.


问:
Exporting Leaflet map with geojson layers to png in Angular 5
I have a leaflet map with a large amount of geojson. I want to be able to export the map image as a png. I have tried the leaflet-image plugin, which exports the base map, and I have also tried (independently) the html2canvas library to output the contents of the map div to a png file.

Unfortunately, outputting using leaflet-image only shows the background layer (the map) and not any of the geojson regions, whereas the outputting the results using html2canvas shows the layers but not the background map.

I don't think the leaflet-image plugin will be viable, as it has too many constraints. It requires all layers to be rendered to the canvas, but in doing so, the performance dives - it doesn't appear to be able to handle so many geo regions. I also don't have much control over the server, and nodejs is not installed there.

html2canvas is far more promising. Using that and file-saver, I was able to output the full image and regions, as follows:

```<code>html2canvas(myMap, {
            allowTaint:false,
            useCORS: true,
            width: 650,
            height: 500,

        }).then(canvas => {
            canvas.toBlob((blob) => {
                saveAs(blob, "my-map.png");
            });
        });
</code>```

This worked brilliantly, except for one problem - the regions are rendering on the canvas clipped in the wrong position. That is, the region offset is wrong. Here is an example. The bottom and right of the map should be covered to the edge with coloured choropleth regions:

How do I get the regions to render correctly on the map, and not be clipped in the wrong place?

Edit: I had a look at an issue on the html2canvas site here which looked promising. Mine doesn't seem to have a transform problem as such, but there was someone that experienced the what I thought was a layer offset problem. I implemented their solution here:

```<code>function redraw() {
    var lat_tmp = map.getCenter().lat;
    var lng_tmp = map.getCenter().lng;
    map.setView([-66.22149259832975, -1.142578125]);
    setTimeout(function () {
        waitForTilesToLoad()
    }, 50000);
    map.setView([lat_tmp, lng_tmp]);
}
</code>```

but it also didn't work, so I'm still trying to solve this problem. It's not really a layer offset problem I'm experiencing, but a layer clipping problem.

答: Since writing this question, a fair bit of time has passed. The solution that ultimately worked for me was to purchase Telerik Reporting and implement any mapping solution I needed in there. It's a very good option and has always worked for me, so if you have the chance to do so, I would highly recommend it. You also get a number of different file formats out of the box, and the solution looks significantly more professional. Just an option to consider.</p>

Body:
I have a leaflet map with a large amount of geojson. I want to be able to export the map image as a png. I have tried the leaflet-image plugin, which exports the base map, and I have also tried (independently) the html2canvas library to output the contents of the map div to a png file.

Unfortunately, outputting using leaflet-image only shows the background layer (the map) and not any of the geojson regions, whereas the outputting the results using html2canvas shows the layers but not the background map.

I don't think the leaflet-image plugin will be viable, as it has too many constraints. It requires all layers to be rendered to the canvas, but in doing so, the performance dives - it doesn't appear to be able to handle so many geo regions. I also don't have much control over the server, and nodejs is not installed there.

html2canvas is far more promising. Using that and file-saver, I was able to output the full image and regions, as follows:

html2canvas(myMap, {
            allowTaint:false,
            useCORS: true,
            width: 650,
            height: 500,

        }).then(canvas => {
            canvas.toBlob((blob) => {
                saveAs(blob, "my-map.png");
            });
        });

This worked brilliantly, except for one problem - the regions are rendering on the canvas clipped in the wrong position. That is, the region offset is wrong. Here is an example. The bottom and right of the map should be covered to the edge with coloured choropleth regions:

How do I get the regions to render correctly on the map, and not be clipped in the wrong place?

Edit: I had a look at an issue on the html2canvas site here which looked promising. Mine doesn't seem to have a transform problem as such, but there was someone that experienced the what I thought was a layer offset problem. I implemented their solution here:

function redraw() {
    var lat_tmp = map.getCenter().lat;
    var lng_tmp = map.getCenter().lng;
    map.setView([-66.22149259832975, -1.142578125]);
    setTimeout(function () {
        waitForTilesToLoad()
    }, 50000);
    map.setView([lat_tmp, lng_tmp]);
}

but it also didn't work, so I'm still trying to solve this problem. It's not really a layer offset problem I'm experiencing, but a layer clipping problem.


问:
Vuejs component not showing in my laravel blade
I am using laravel and vue and it is unable to load components into blade page. It showing empty.

I have tried many solutions but doesn't work.

welcome.blade

```<code><!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script>
        window.Laravel = { csrfToken: '{{ csrf_token() }}' }
    </script>
    <title>App</title>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css? family=Nunito:200,600" rel="stylesheet">
</head>
<body>
    <script type="text/javascripts" src="js/app.js"></script>
        <div id ="app">
            <div class="container">
                <articles></articles>
            </div>
        </div>
</body>
</html>
</code>```

Articles.vue

```<code><template>
    <div>
        <h2>Articles</h2>
    </div>
</template>
</code>```

App.js

```<code>/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

import articles from './components/Articles'
    window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 */

Eg. ./components/ExampleComponent.vue -> <example-component></example-component>

const files = require.context('./', true, /\.vue$/i);
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('articles', require('./components/Articles.vue'));

const app = new Vue({
    el: '#app',
});
</code>```

composer.json

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^3.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}
</code>```

I was expecting to see Articles as h2 but it shows nothing and when I inspect element I see this error

"Uncaught TypeError: Vue.components is not a function".

Any help will be appreciated.

答:
npm install vuejs package must show like this

then, in your app.js

```<code>Vue.component('articles', require('./components/Articles.vue').default);
const app = {
init() {
    this.setupVue();
},

setupVue() {
    new Vue({
        el: '#app',
    });
}
};
app.init()
</code>```

Body:
I am using laravel and vue and it is unable to load components into blade page. It showing empty.

I have tried many solutions but doesn't work.

welcome.blade

<!doctype html>
getLocale()) }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>App</title>

    <link href="https://fonts.googleapis.com/css? family=Nunito:200,600" rel="stylesheet">

                <articles></articles>

Articles.vue

<template>

Articles

</template>

App.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

import articles from './components/Articles'
    window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 */

Eg. ./components/ExampleComponent.vue -> <example-component></example-component>

const files = require.context('./', true, /\.vue$/i);
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('articles', require('./components/Articles.vue'));

const app = new Vue({
    el: '#app',
});

composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^3.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

I was expecting to see Articles as h2 but it shows nothing and when I inspect element I see this error

"Uncaught TypeError: Vue.components is not a function".

Any help will be appreciated.

Body:
npm install vuejs package must show like this

then, in your app.js

Vue.component('articles', require('./components/Articles.vue').default);
const app = {
init() {
    this.setupVue();
},

setupVue() {
    new Vue({
        el: '#app',
    });
}
};
app.init()


问:
Preventing progressive download of mp3?
I'm looking for some solutions for creating an mp3 player in flash; one that either uses streaming or some kind of obfuscation to prevent users from downloading the source mp3. If I used a server/solution that used the RMTP: protocol, would that prevent the download? Are there any possibilities for using Amazon S3 server for serving the files but hiding the actual URL of the file?</p>

答:
No, RTMP won't prevent direct downloading -- if the user can find out the direct URL, then they can still download the file.  I don't know about S3, but I have used streaming servers like Red5 and know that it is possible to directly download MP3 content from it, and therefore is prudent to secure your server in order to prevent people from viewing indexes, etc.

Obfuscating the URL is a possibility, as you suggest, as is on-the-fly renaming.  You could pass a GUID to the client, and then on the server, copy the MP3 to a directory named the same as that GUID.  The client downloads from that location, and then afterwards the copy is removed.  This would of course impose a higher disk load on the server, but I'm just throwing the idea out there in the interest of brainstorming. :)

In short, AFAIK it's possible to get the MP3 content directly over RTMP if the user is sufficiently motivated, so rather than playing cat-and-mouse, you should use a small amount of discouragement to prevent people from abusing your site, but not to prevent you from getting other work done in an effort to win such an arms race.

Edit: On second thought, this might be possible with some streaming media servers... maybe it's just ones like Red5 that permit the user to also download the content if they know the URL.  In spite of this, Scott has a good point, too... anything you transmit can be intercepted.

OwnerDisplayName: TypeOneError

ContentLicense: CC BY-SA 2.5

Title: Preventing progressive download of mp3?

OwnerDisplayName: sqook

LastEditorDisplayName: sqook


问:
Why my jQuery ajax call is not successful
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

```<code>$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })
</code>```

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

----------------EDIT---------------

Hi, I changed to use localhost request like:

```<code>$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })
</code>```

But I got the same error... more suggestions please... thank you.

答:
change your datatype to application/xml or text/xml

As the other comment suggests, is your URL on another domain? If not then try using relative URL's instead.

Body:
I am developing my web app and run it on localhost:8080, in my js file, I have an ajax call to get xml data from server:

$.ajax({
        url: 'http://COMPANY_DOMAIN.com/company-interface/the-id',
        type: 'GET',
        async: false,
        dataType: 'application/xml',
        data: {id: 43},
        success: function(data) {

            alert(data);

        },
        error: function(xhr, status, error){
            alert('error happens');
        }
     })

I can access the url http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43 which will show the xml result on browswer, but my above ajax call always go to error function.

I checked in firebug, the 'xml' tab shows "XML Parsing Error: no element found Location: moz-nullprincipal:{9fd0dca8-cf07-4401-b1de-ab04e8aa00bc} Line Number 1, Column 1:" and firebug shows the URL GET is http://COMPANY_DOMAIN.com/company-interface/the-id/?id=43& =1302610001570.

Why firebug GET shows the "...& =1302610001570"? what does it means? why my ajax call is failed, though I can access that URL?

----------------EDIT---------------

Hi, I changed to use localhost request like:

$.ajax({
            url: 'http://localhost:8080/company-interface/the-id',
            type: 'GET',
            async: false,
            dataType: 'xml',
            data: {id: 43},
            success: function(data) {

                alert(data);

            },
            error: function(xhr, status, error){
                alert('error happens');
            }
         })

But I got the same error... more suggestions please... thank you.


问:
Add Hover effect to Font Awesome Stars
I would like a simple method, whereby you hover over them and they are a solid yellow.

```<code>const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
  }
});

function Tasks(props) {
  const { classes } = props;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>
              <div className="name-label">
              Name
              </div>
              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>
              <div className="form-divider"></div>
                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">
      <i class="far fa-play-circle fa-2x"></i>
    </Grid>
    <div className="workers-assigned-label">
      Workers Assigned
    </div>
    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>
      <div class="star-rating">
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
        <label class="far fa-star fa-2x"></label>
      </div>
    <div>
      unassigned
    </div>
  </Grid>
          </Grid>
        </Grid>
      </Paper>
    </div>
  );
}

export default withStyles(styles)(Tasks);
</code>```

If anyone has any suggestions as to how to get them to change from https://fontawesome.com/v4.7.0/icon/star-o to having the centre fill with yellow that would be much appreciated. Whether it be best done with CSS or something using React.

答:
Taking a look at the content of that particular font, the 2 you'll use are content: "\f006" and content: "\f005". f005 is the filled star that you'll want to turn yellow.

const styles = theme => ({
  playButton: {
    "& .rating": {

      "& .fa-star-o": {
        "&:hover": {
          "&::before": {
            content: "\f005",
            color: "yellow"
          }
        }
      }

    },
  },
});```

And like the other person said, make sure the package is working.

Title: Add Hover effect to Font Awesome Stars

Body:
I would like a simple method, whereby you hover over them and they are a solid yellow.

const styles = theme => ({
  root: {
    flexGrow: 1,
    overflow: 'hidden',
    padding: theme.spacing(0, 3),
  },
  paper: {
    maxWidth: 800,
    margin: `${theme.spacing(2)}px auto`,
    padding: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
  playButton: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
    "& .playButton": {
      position: "absolute",
      top: "60%",
      left: "-55px",
      transform: "translateY(-50%)",
    },
  }
});

function Tasks(props) {
  const { classes } = props;
  return (

      <Paper className={classes.paper}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm container>
            <Grid item xs container direction="column" spacing={2}>
              <Grid item xs>

              Name

              <Typography variant="h6" gutterBottom>
              {props.name}
              </Typography>

                <Typography variant="body2" color="textSecondary">
                {props.description}
                </Typography>
              </Grid>
            </Grid>
            <Grid item classes={{ root: props.classes.playButton}}>
    <Grid item xs={3} className="playButton">

    </Grid>

      Workers Assigned

    <Typography variant="h6" gutterBottom>
        0/25
      </Typography>

      unassigned

  </Grid>
          </Grid>
        </Grid>
      </Paper>

  );
}

export default withStyles(styles)(Tasks);

If anyone has any suggestions as to how to get them to change from https://fontawesome.com/v4.7.0/icon/star-o to having the centre fill with yellow that would be much appreciated. Whether it be best done with CSS or something using React.

Body:
Taking a look at the content of that particular font, the 2 you'll use are content: "\f006" and content: "\f005". f005 is the filled star that you'll want to turn yellow.

const styles = theme => ({
  playButton: {
    "& .rating": {

      "& .fa-star-o": {
        "&:hover": {
          "&::before": {
            content: "\f005",
            color: "yellow"
          }
        }
      }

    },
  },
});

And like the other person said, make sure the package is working.


问:
Mapping an IQueryable to domain model for OData in .NET
I recently implemented OData in my ASP .NET Core web API. I have found success as long as I am returning the database models directly. I run into trouble, however, as soon as I attempt to return domain models instead.

The underlying issue involves mapping a data class to a domain class while maintaining the IQueryable return type. While I have found partial success using AutoMapper's MapTo extension method, I find that I am unsuccessful when using the $extend method to expand a collection of entities that are also domain objects.

I have created a sample project to illustrate this issue. You may view or download the full project on github here. See the description below.

Given the following two database classes:

```<code>public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<Order> Orders { get; set; }

    public Product() {
        Orders = new Collection<Order>();
    }
}

public class Order
{
    public int Id { get; set; }
    public Double Price { get; set; }
    public DateTime OrderDate { get; set; }

    [Required]
    public int ProductId { get; set; }
    public Product Product { get; set; }
}
</code>```

And the following domain models...

```<code>public class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<OrderEntity> Orders { get; set; }
}

public class OrderEntity
{
    public int Id { get; set; }
    public Double Price { get; set; }
    public DateTime OrderDate { get; set; }

    [Required]
    public int ProductId { get; set; }
    public Product Product { get; set; }
}
</code>```

And the Products Controller

```<code>public class ProductsController
{
    private readonly SalesContext context;

    public ProductsController(SalesContext context) {
        this.context = context;
    }

    [EnableQuery]
    public IQueryable<ProductEntity> Get() {
        return context.Products
            .ProjectTo<ProductEntity>()
            .AsQueryable();
    }
}
</code>```

All the following OData queries Pass:

http://localhost:51004/odata/Products

http://localhost:51004/odata/Orders

http://localhost:51004/odata/Orders?$expand=Products

The following query, however, does not pass:

http://localhost:51004/odata/Products?$expand=Orders

An HTTP response is never returned. The only failure message I get comes from the console:

```<code>System.InvalidOperationException: Sequence contains no matching element at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
</code>```

Finally, here is a reference to the mapping profile:

```<code>    public static class MappingProfile
{
    public static void RegisterMappings() {
        Mapper.Initialize(cfg =>
        {
           cfg.CreateMap<Order, OrderEntity>();
           cfg.CreateMap<Product, ProductEntity>();
        });
    }
}
</code>```

I can solve the issue by simply returning a List instead of an IEnumerable in the controller, but this of course would trigger a large query against the database that would be performance intensive.

As stated above, you can find a link to the full project on Github here. Let me know if you find any answers!

答:
I was able to get this working with a few small revisions.

Updating the domain models:

```<code>public class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<Order> Orders { get; set; }
}

public class OrderEntity
{
    public int Id { get; set; }
    public double Price { get; set; }
    public DateTime OrderDate { get; set; }

    [Required]
    public int ProductId { get; set; }
    public Product Product { get; set; }
}
</code>```

Manually enabling expansion on the route builder:

```<code>// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, SalesModelBuilder modelBuilder)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc(routeBuilder =>
        {
            routeBuilder.Expand().Select();
            routeBuilder.MapODataServiceRoute("ODataRoutes", "odata",
                    modelBuilder.GetEdmModel(app.ApplicationServices));
        });
}
</code>```

Using the following Queries:

http://localhost:51004/odata/Products

http://localhost:51004/odata/Orders

http://localhost:51004/odata/Orders?$expand=Product

http://localhost:51004/odata/Products?$expand=Orders

Body:
I recently implemented OData in my ASP .NET Core web API. I have found success as long as I am returning the database models directly. I run into trouble, however, as soon as I attempt to return domain models instead.

The underlying issue involves mapping a data class to a domain class while maintaining the IQueryable return type. While I have found partial success using AutoMapper's MapTo extension method, I find that I am unsuccessful when using the $extend method to expand a collection of entities that are also domain objects.

I have created a sample project to illustrate this issue. You may view or download the full project on github here. See the description below.

Given the following two database classes:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<Order> Orders { get; set; }

    public Product() {
        Orders = new Collection<Order>();
    }
}

public class Order
{
    public int Id { get; set; }
    public Double Price { get; set; }
    public DateTime OrderDate { get; set; }

    [Required]
    public int ProductId { get; set; }
    public Product Product { get; set; }
}

And the following domain models...

public class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<OrderEntity> Orders { get; set; }
}

public class OrderEntity
{
    public int Id { get; set; }
    public Double Price { get; set; }
    public DateTime OrderDate { get; set; }

    [Required]
    public int ProductId { get; set; }
    public Product Product { get; set; }
}

And the Products Controller

public class ProductsController
{
    private readonly SalesContext context;

    public ProductsController(SalesContext context) {
        this.context = context;
    }

    [EnableQuery]
    public IQueryable<ProductEntity> Get() {
        return context.Products
            .ProjectTo<ProductEntity>()
            .AsQueryable();
    }
}

All the following OData queries Pass:

http://localhost:51004/odata/Products

http://localhost:51004/odata/Orders

http://localhost:51004/odata/Orders?$expand=Products

The following query, however, does not pass:

http://localhost:51004/odata/Products?$expand=Orders

An HTTP response is never returned. The only failure message I get comes from the console:

System.InvalidOperationException: Sequence contains no matching element at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)

Finally, here is a reference to the mapping profile:

    public static class MappingProfile
{
    public static void RegisterMappings() {
        Mapper.Initialize(cfg =>
        {
           cfg.CreateMap<Order, OrderEntity>();
           cfg.CreateMap<Product, ProductEntity>();
        });
    }
}

I can solve the issue by simply returning a List instead of an IEnumerable in the controller, but this of course would trigger a large query against the database that would be performance intensive.

As stated above, you can find a link to the full project on Github here. Let me know if you find any answers!

Body:
I was able to get this working with a few small revisions.

Updating the domain models:

public class ProductEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<Order> Orders { get; set; }
}

public class OrderEntity
{
    public int Id { get; set; }
    public double Price { get; set; }
    public DateTime OrderDate { get; set; }

    [Required]
    public int ProductId { get; set; }
    public Product Product { get; set; }
}

Manually enabling expansion on the route builder:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, SalesModelBuilder modelBuilder)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc(routeBuilder =>
        {
            routeBuilder.Expand().Select();
            routeBuilder.MapODataServiceRoute("ODataRoutes", "odata",
                    modelBuilder.GetEdmModel(app.ApplicationServices));
        });
}

Using the following Queries:

http://localhost:51004/odata/Products

http://localhost:51004/odata/Orders

http://localhost:51004/odata/Orders?$expand=Product

http://localhost:51004/odata/Products?$expand=Orders


问:
Exclude unpacked packages from Package Control menu
Is there a way to exclude packages in Packages directory from being visible in Package Control menu? I'm afraid of accidentally delete them.

答:
I'm assuming you're referring to the PackageControl: RemovePackage command here, in which case unfortunately the answer is No (or Yes, with hackery as outlined below).

When displaying the list of packages to remove, PackageControl gathers the list of all packages and excludes from it the User and Default packages as well as any package that ships with Sublime (most notably it doesn't remove itself from the list of packages that it will remove).

As such, outside of that all packages will be offered for removal.

In theory you can add an empty sublime-package file to the Packages folder alongside the binary, which is where the packages that ship with Sublime are stored. Since PackageControl removes those packages from the list of packages to remove, that would stop it from offering it for removal.

If the package is question is a sublime-package file natively, then the version in Installed Packages will override it completely as if it was not there (except that it's listed as a shipped package in tools like OverrideAudit and PackageControl). If it is installed as a folder in Packages, then technically the contents of that folder are treated as overrides for the shipped package, but since that package is empty this should have no effect.

Having said that, although simple testing shows that this works, it may or may not have other consequences.


问:
Taking a screenshot, analyzing it, then deleting it
I've been trying to code an auto clicker for a simple game online (a php coded one), but I've had trouble analyzing the colors on-screen. (English isn't my first language, sorry!) I've already done a bit of C++ in university, but only for science-oriented simple console programs. (Edit: I'm working on windows!! forgot to mention)

I've already tried the getpixel function, but since my chrome window is zoomed out at 80% to get the full game in frame, it seems I'm having some DPI related issues, but looking into this made my head dizzy.

After watching a Codebullet video, I thought a better approach to this would be to take a screenshot of the problematic area, analyze it to see if the condition is filled, then delete the screenshot. The problem is, I have no idea how I could achieve this and Google didn't help much this time :\

My code is extremely messy so I can't show it right now, but it's basically just a:

-click there

-click there after 5 seconds

-click there if this pixel is this color

-repeat

Is there an easy answer to this? I'd be really thankful if there is. Have a nice day! :)

答:
You don't need to save the screen shot if you don't want to:

Pass the target window handle to GetDC(), t will return the the device context of the window.

Pass the device context to CreateCompatibleDC() to create a compatible DC.

Use CreateCompatibleBitmap(), passing in the DC and the size of the window.  This returns a handle to a bitmap

Use SelectObject() to select the bitmap

Use BitBlt() to do a bitblock transfer of the selected pixels from the regular DC into the compatible DC using the SRCCOPY raster operation code to do a normal copy.

Create a BITMAP object.  Use GetObject() and pass the handle to the bitmap you created.

Create a BITMAPINFOHEADER and define the member vars.  Create an array of unsigned chars big enough to fit all the pixels from your bitmap.

Use GetDIBits() passing in the handle to the compatible bitmap, the bitmap header and a pointer to the pixel array.  This loads the pixels from the bitmap into the pixel array.

Now parse all that juicy pixel data, search for the colors you're looking for and test the results against your conditionals to decide what to do next.

Don't forget to delete objects and release memory & device contexts.

I believe this is the tutorial I followed where I learned this, courtesy of MSDN: https://learn.microsoft.com/en-us/windows/desktop/gdi/capturing-an-image


问:
Opening a Workspace causes python.pythonPath to be ignored
Problem

VS Code refuses to use the custom python.pythonPath I have specified in settings.json to run Python files through Microsoft's Python Extension. This only occurs when I open a workspace. Opening individual files is fine.

Expected Solution

Even when opening a workspace, the python.pythonPath variable should be respected and used instead of whatever the Python: Select Interpreter command or respective button (in the bottom-left) says.

Further Explanation

For background, the A:\ drive is a portable driver that has many school-related files, including the Python Installation, VS Code Installation and the Python project's scripts I'm running.

When I open a workspace I use for a project I'm working on, I suddenly am forced into using a Python Interpreter other than what I have specified in settings.json.

Attempting to set one in the workspace settings file by copying the python.pythonPath line doesn't exhibit anything like the solution I need.
How can I get VS Code's Python extension to respect this setting, or if not possible, how can I set it (in the workspace settings) to also use the same extension I have specified.

Directory for my Python Project A:\Programming\Python\Projects\Project Name\
(contains workspace.code-workspace file, as well as all scripts being ran)

Directory of the Python Installation A:\Installations\WinPython 64\python-3.6.6.amd64\
(python.exe is located within here)

Directory of the VS Code x64 Portable Installation A:\Installations\Visual Studio Code x64\
(Code.exe is located within here)

settings.json - full file

```<code>{
    python.pythonPath": "A:\\Installations\\WinPython 64\\python-3.6.6.amd64\\python.exe",
    ...
    "python.jediEnabled": false
}
</code>```

workspace.code-workspace

```<code>{
    "folders": [
        {
            "path": "."
        }
    ],
    "settings": {
        "python.pythonPath": "A:\\Installations\\WinPython 64\\python-3.6.6.amd64\\python.exe"
    }
}
</code>```

答:
You said:

... the python.pythonPath variable should be respected and used instead of whatever the Python: Select Interpreter command or respective button (in the bottom-left) says.

But python.pythonPath is what is actually set when you run Python: Select Interpreter or click on the interpreter in the status bar, and its value is what ends up being shown in the status bar. There isn't a way to have a different value in python.pythonPath compared to what is shown in the status bar.

Body:
Problem

VS Code refuses to use the custom python.pythonPath I have specified in settings.json to run Python files through Microsoft's Python Extension. This only occurs when I open a workspace. Opening individual files is fine.

Expected Solution

Even when opening a workspace, the python.pythonPath variable should be respected and used instead of whatever the Python: Select Interpreter command or respective button (in the bottom-left) says.

Further Explanation

For background, the A:\ drive is a portable driver that has many school-related files, including the Python Installation, VS Code Installation and the Python project's scripts I'm running.

When I open a workspace I use for a project I'm working on, I suddenly am forced into using a Python Interpreter other than what I have specified in settings.json.

Attempting to set one in the workspace settings file by copying the python.pythonPath line doesn't exhibit anything like the solution I need.
How can I get VS Code's Python extension to respect this setting, or if not possible, how can I set it (in the workspace settings) to also use the same extension I have specified.

Directory for my Python Project A:\Programming\Python\Projects\Project Name\
(contains workspace.code-workspace file, as well as all scripts being ran)

Directory of the Python Installation A:\Installations\WinPython 64\python-3.6.6.amd64\
(python.exe is located within here)

Directory of the VS Code x64 Portable Installation A:\Installations\Visual Studio Code x64\
(Code.exe is located within here)

settings.json - full file

{
    python.pythonPath": "A:\\Installations\\WinPython 64\\python-3.6.6.amd64\\python.exe",
    ...
    "python.jediEnabled": false
}

workspace.code-workspace

{
    "folders": [
        {
            "path": "."
        }
    ],
    "settings": {
        "python.pythonPath": "A:\\Installations\\WinPython 64\\python-3.6.6.amd64\\python.exe"
    }
}


问:
NativeXml and  threading
I am tryng to get this library working with thread but I am not able to get result back to the main thread using syncronize.

No problem creating xml within excute method.

Someone have used it?

NativeXml

```<code>   TMyThread = class(TThread)
       private
       ADoc : TNativeXml;
        protected
         procedure Execute; override;
         procedure DoProgress;
       public
         constructor Create(CreateSuspended: Boolean);
      end;

    { TMyThread }

    constructor TMyThread.Create(CreateSuspended: Boolean);
    begin
      inherited;
    end;

procedure TMyThread.DoProgress;
begin
 formMain.meminfo.Lines.Add(ADoc.WriteToString);
end;

procedure TMyThread.Execute;
var i,j : integer;
begin
  inherited;
begin
    ADoc:= ADoc.Create(formMain);
    try
    Adoc.XmlFormat := xfReadable;
    ADoc.LoadFromFile('test.xml');
    Synchronize(DoProgress);
    finally
       FreeAndNil(ADoc);
    end;
end;
end;
</code>```

答:
Not getting the result back to the main thread or getting access violation at this line?

```<code>ADoc:= ADoc.Create(formMain);
</code>```

That single line of code contains one bug and one code smell: The code smell is that you're reffering to formMain, from a thread. The bug is that you're not calling .Create() on a class name but on the variable name itself! You probably wanted:

```<code>ADoc := TNativeXml.Create(nil);
</code>```

Title: NativeXml and  threading

Body:
I am tryng to get this library working with thread but I am not able to get result back to the main thread using syncronize.

No problem creating xml within excute method.

Someone have used it?

NativeXml

   TMyThread = class(TThread)
       private
       ADoc : TNativeXml;
        protected
         procedure Execute; override;
         procedure DoProgress;
       public
         constructor Create(CreateSuspended: Boolean);
      end;

    { TMyThread }

    constructor TMyThread.Create(CreateSuspended: Boolean);
    begin
      inherited;
    end;

procedure TMyThread.DoProgress;
begin
 formMain.meminfo.Lines.Add(ADoc.WriteToString);
end;

procedure TMyThread.Execute;
var i,j : integer;
begin
  inherited;
begin
    ADoc:= ADoc.Create(formMain);
    try
    Adoc.XmlFormat := xfReadable;
    ADoc.LoadFromFile('test.xml');
    Synchronize(DoProgress);
    finally
       FreeAndNil(ADoc);
    end;
end;
end;

Body:
Not getting the result back to the main thread or getting access violation at this line?

ADoc:= ADoc.Create(formMain);

That single line of code contains one bug and one code smell: The code smell is that you're reffering to formMain, from a thread. The bug is that you're not calling .Create() on a class name but on the variable name itself! You probably wanted:

ADoc := TNativeXml.Create(nil);


问:
How to make a Vuetify rule async and await with a ajax call
I am using Vuetify form validation to check an input field, and I'm trying to figure out if it's possible to call a ajax get call and make it await so that I can use the result in a rule?

I've attempted it below, but it doesn't seem to work!

```<code>export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },

      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }
</code>```

答:
I found a better solution, as I needed to perform a check similar to checking another email address in the database. So I used 'error-messages'

like this

@input="newLocationNameSearch($event)" :error-messages="newLocationErrorMessages"

this way every character that is input will be checked in 'newLocationNameSearch()' and I fill and remove items from 'newLocationErrorMessages' to display to the user!

Body:
I am using Vuetify form validation to check an input field, and I'm trying to figure out if it's possible to call a ajax get call and make it await so that I can use the result in a rule?

I've attempted it below, but it doesn't seem to work!

export default {
  data() {
    return {
      rules: {
        isLocationNew: value => {

          if (value == '' || value == null || value.length <= 1) {
            this.validLocation = false;
            return 'Invalid length.';
          }

          this.validLocation = true;

          var hasName = this.newLocationNameSearch(value);
          if (hasName) {
            return 'Location name already exists.';
          } else {
            return true;
          }
        }
      },

      // down in methods
      methods: {
        async newLocationNameSearch(text) {
          if (text == '' || text == null || text.length <= 1) {
            return false;
          }

          await axios.get('/api/Locations/HasLocationName', {
            params: {
              text: text,
              jobsiteId: this.jobsiteId
            }
          }).then(response => {
            return response.data;
          }).catch(function(error) {
            console.log(error)
          })

        }
      }


问:
Get non matching record
I have two views. Both the views have most of the columns same. View1 has 20 columns and View2 has 22 columns. View2 has 20 columns same as View1.
Now I want a query to find out if the data in these common 20 columns is the same or not and if not I would like to get those records

View1

```<code>Columns FN  LN  EmpID
    a   b   1
    c   d   2
</code>```

View2

```<code>Columns FN  LN  EmpID
    a   b   1
    c   b   2
</code>```

I want a query where I can check if there is any mismatch in column values  between View1 and View2 and if there is a mismatch than return that record. Like the query should return View2's second record because it does not match with View1 second record

答:
```<code>select *
from view1 a , view2 b
where a.Columns = b.Columns
having ( a.FN  <> b.FN  or a.LN  <> b.LN  or a.EmpID <> b.EmpID )
</code>```

Title: Get non matching record

Body:
I have two views. Both the views have most of the columns same. View1 has 20 columns and View2 has 22 columns. View2 has 20 columns same as View1.
Now I want a query to find out if the data in these common 20 columns is the same or not and if not I would like to get those records

View1

Columns FN  LN  EmpID
    a   b   1
    c   d   2

View2

Columns FN  LN  EmpID
    a   b   1
    c   b   2

I want a query where I can check if there is any mismatch in column values  between View1 and View2 and if there is a mismatch than return that record. Like the query should return View2's second record because it does not match with View1 second record


问:
Excel macro - open macro without going into Visual Basic?
I've finished my macro! But is there an easier way in runnning it?

I know two ways

Open Visual Basic, select the correct macro and run!

View Macro's, select the correct macro and run!

Is there an easier way, or are these the only two ways?

Thanks

答:
There are several options:

Toolbar or Menu (Excel 2003 & earlier)

http://peltiertech.com/WordPress/how-to-assign-a-macro-to-a-toolbar-or-menu/

ActiveX control

http://peltiertech.com/WordPress/how-to-assign-a-macro-to-an-activex-control/

Button (Forms menu control) or Shape

http://peltiertech.com/WordPress/how-to-assign-a-macro-to-a-button-or-shape/


问:
Problem with if-else loop in a user-controlled do-while loop
My pseudocode:

Best case:
1) Ask user for a number
2) Test if user's input is a numerical value
3) If user's input is valid, perform floor, round, and ceil functions on user's input
4) Display floor, round, and ceil values of user's input

Worst case:
1) Ask user for a number
2) Test if user's input is a numerical value
3) If user's input is invalid, ask if the user wants to try again with a Y/N choice
4) If user says yes, go back to 1), if user says no - terminate

```<code>#include <stdio.h>
#include <math.h>

int main(void) {

    float user_input;
    int a;
    char answ;

    do {
        printf ("Enter a number to find its lower bound, rounded, and upper bound values: ");

        if ((a = scanf("%f", &user_input) == 1)) {

            float floored_input = floor(user_input);
            float rounded_input = round(user_input);
            float ceiled_input = ceil(user_input);

            printf("Lower Bound: %1.0f\n", floored_input);
            printf("Rounded:     %1.0f\n", rounded_input);
            printf("Upper Bound: %1.0f\n", ceiled_input);

            break;

        } else {

            printf("Invalid input. Do you want to try again? (Y/N): ");
            scanf("%c", &answ);

        }
    } while(answ == 'Y' || answ == 'y');

    return 0;
}
</code>```

The only problem I am having is that when a user enters a value literally other than 'i' the program terminates and i'm back in my working directory.

The user can enter any number and it will work.
The user can enter i and he or she will be prompted with a Y/N option

HOWEVER, when the user enters "i2", "hello", "h", "b", "yoooo", etc

The user does not get a Y/N option and the program is terminated

答:
the following proposed code:

cleanly compiles

performs the desired functionality

makes use of the header file: ctype.h function: toupper()

uses the proper functions for float values

properly initializes the variable: answ

and now, the proposed code:

```<code>#include <stdio.h>
#include <math.h>
#include <ctype.h>

int main(void)
{
    float user_input;
    char answ = 'Y';

    while( toupper( answ ) != 'N' )
    {
        printf ("Enter a number to find its lower bound, rounded, and upper bound values: ");

        if ( scanf("%f", &user_input) == 1 )
        {
            float floored_input = floorf( user_input );
            float rounded_input = roundf( user_input );
            float ceiled_input  = ceilf(  user_input );

            printf( "Lower Bound: %1.0f\n", floored_input );
            printf( "Rounded:     %1.0f\n", rounded_input );
            printf( "Upper Bound: %1.0f\n", ceiled_input );
        }

        do
        {
            printf( "Do you want to try again? {Y/N}: " );
            scanf( " %c", &answ );
            //printf( "debug: answ = %x\n", answ );
        } while( toupper(answ) != 'Y' && toupper( answ ) != 'N' );
    }
    return 0;
}
</code>```

Body:
My pseudocode:

Best case:
1) Ask user for a number
2) Test if user's input is a numerical value
3) If user's input is valid, perform floor, round, and ceil functions on user's input
4) Display floor, round, and ceil values of user's input

Worst case:
1) Ask user for a number
2) Test if user's input is a numerical value
3) If user's input is invalid, ask if the user wants to try again with a Y/N choice
4) If user says yes, go back to 1), if user says no - terminate

#include <stdio.h>
#include <math.h>

int main(void) {

    float user_input;
    int a;
    char answ;

    do {
        printf ("Enter a number to find its lower bound, rounded, and upper bound values: ");

        if ((a = scanf("%f", &user_input) == 1)) {

            float floored_input = floor(user_input);
            float rounded_input = round(user_input);
            float ceiled_input = ceil(user_input);

            printf("Lower Bound: %1.0f\n", floored_input);
            printf("Rounded:     %1.0f\n", rounded_input);
            printf("Upper Bound: %1.0f\n", ceiled_input);

            break;

        } else {

            printf("Invalid input. Do you want to try again? (Y/N): ");
            scanf("%c", &answ);

        }
    } while(answ == 'Y' || answ == 'y');

    return 0;
}

The only problem I am having is that when a user enters a value literally other than 'i' the program terminates and i'm back in my working directory.

The user can enter any number and it will work.
The user can enter i and he or she will be prompted with a Y/N option

HOWEVER, when the user enters "i2", "hello", "h", "b", "yoooo", etc

The user does not get a Y/N option and the program is terminated

Body:
the following proposed code:

cleanly compiles

performs the desired functionality

makes use of the header file: ctype.h function: toupper()

uses the proper functions for float values

properly initializes the variable: answ

and now, the proposed code:

#include <stdio.h>
#include <math.h>
#include <ctype.h>

int main(void)
{
    float user_input;
    char answ = 'Y';

    while( toupper( answ ) != 'N' )
    {
        printf ("Enter a number to find its lower bound, rounded, and upper bound values: ");

        if ( scanf("%f", &user_input) == 1 )
        {
            float floored_input = floorf( user_input );
            float rounded_input = roundf( user_input );
            float ceiled_input  = ceilf(  user_input );

            printf( "Lower Bound: %1.0f\n", floored_input );
            printf( "Rounded:     %1.0f\n", rounded_input );
            printf( "Upper Bound: %1.0f\n", ceiled_input );
        }

        do
        {
            printf( "Do you want to try again? {Y/N}: " );
            scanf( " %c", &answ );
            //printf( "debug: answ = %x\n", answ );
        } while( toupper(answ) != 'Y' && toupper( answ ) != 'N' );
    }
    return 0;
}