问:
Vue Unit Testing: How to test complex components with props, vuex store, watchers, getters etc
I have a question about unit testing (Jest) within a vue app - I guess it is rather an architectural question, but maybe specific code examples could also help me out.

I have sketched out a more or less complex setup of vue components from my app. They are still simplified but I guess they should help to describe the situation.

(PDF Attachment for those preferring non-pixel data :)

I have a Wrapper which has three child components:

Search (Input field to search on Map)

List (List of stores, represented also as markers on map)

Map (Google Map itself)

I would really like to write some unit tests for this, but it seems so super tedious to setup those tests, so that I doubt that this is the way to do it.

It starts with the way I load the google maps API: The wrapper loads it asynchronously, sets API key etc. As soon as the google map API is loaded it passes it down to the children.

Of course the map only really starts to load, create and display markers, as soon as google is present and I can use new this.google.maps.Map() for example.

Even if I would like to test some methods of the Map component, I have to provide an actual google object, because otherwise the whole init process in mount() fails. It can't make a map.

So do I have to load the actual google's map API in my tests? Or could I somehow skip mounting the map but still test a few isolated methods?

Further you can see that my Map watches a getter from the vuex store: Whenever the searchCoordinates set by Search change in my vuex store, I want to execute some functions (for example center my map to the new search coordinates or remove a current location marker if the search did not return valid searchCoordinates).

How could I somehow break down the interlinking between these components, but still write good and helpful tests, which help me to guarantee that the app does what it is supposed to do?

I know that I can use a vuex store within my tests (Medium article about vuex testing).
But still I feel like the whole app is so much inter-connected that doing actual unit testing – testing one small piece at a time – is impossible.
It seems like that I would have to mount not only Map alone, but also the other components and a vuex store with actual data, to really write bulletproof tests.

A few other examples, where I struggle:

In my mounted() I subscribe to an action with this.$store.subscribeAction((action) => {... - of course $store is undefined in my tests. Should I mock it?

As I said I am watching a getter: This throws errors like TypeError: Cannot use 'in' operator to search for 'searchCoordinates' in undefined. Would I have to mock all the getters as well? If so: what remains to be tested? If I mock (~=leave away) all the vuex stuff, it seems to me, that testing becomes useless...

But maybe I am mistaken here. Also I am quite new to unit testing, so any hints are very welcome.
Thank you very much in advance. I hope somebody has some valuable input.
All those examples (even in books like Vue.js - up and running) are always broken down to very simple and understandable examples, but on the other hand don't really reflect real-life apps...

Cheers

----- Edit:

I got a needs more focus vote by someone.
So I try to sum up simple and small questions:

Summary of Questions

Does somebody have a general input on how to test larger and more complex vue applications?

Is there a way to test a component with a google map (or a component that is relying heavily on any third party code)

Is mocking getters, store and actions a good idea in this case? (I have my doubts there).

For testing watched properties from the vuex store, I read in this thread that mapState should be mocked. (in my case probably my getters). Does this make sense to mocke those getters in my case?

Is it best practice to simplify as many things as possible in an tested component (for example, I started to override some methods, which failed (the one including google map initiation) to just get my test up and running:

```<code>const initMapMock = jest.fn();
const initMarkersMock = jest.fn();
...
const wrapper = shallowMount(Map, {
    methods: {
        initMap: initMapMock, // replace initMap(), which needs google map API
        initMarkers: initMarkersMock,
      },
    ...

</code>```

Does that make sense?

答:
After diving deeper into this question I realized one thing:
If one has such a complex situation like described above, unit testing is probably not the right tool for this!

In this case end to end testing also called integration testing would be much more suitable for the job.

Because what I actually want to test is, that all the different component react in the right way, if something is changed/triggered and so on, I need to see the whole picture.

If I go back to my example I want to see that the map changes if the search input registers a change and so on.

I ended up integrating a few tests for this by using a headless browser googles puppeteer, opening the webpage, filling in a search query and then search the DOM for reliable changes in the map for example.

Unfortunately I did not have the time to really go into detail with the testing on this one because of budget restrictions, but I got an idea of how this should be approached.

My initial ideas of mocking a store etc. would require so much work which would be nothing else than building a big mock which resembles the rest of the app around a unit test, that it would be downright stupid to do that. With integration tests I use this already built app around my test, but I have the advantage of being able to test everything in sync!

I personally also think that integration tests are much more powerful than unit tests, because they illuminate the parts of an application that are not so easy to grasp by a developer and will throw errors if one part of the application is changed and the other fails to function as desired.

If somebody has more to add, I am still very glad to hear opinions on that matter.

Cheers

Body:
I have a question about unit testing (Jest) within a vue app - I guess it is rather an architectural question, but maybe specific code examples could also help me out.

I have sketched out a more or less complex setup of vue components from my app. They are still simplified but I guess they should help to describe the situation.

(PDF Attachment for those preferring non-pixel data :)

I have a Wrapper which has three child components:

Search (Input field to search on Map)

List (List of stores, represented also as markers on map)

Map (Google Map itself)

I would really like to write some unit tests for this, but it seems so super tedious to setup those tests, so that I doubt that this is the way to do it.

It starts with the way I load the google maps API: The wrapper loads it asynchronously, sets API key etc. As soon as the google map API is loaded it passes it down to the children.

Of course the map only really starts to load, create and display markers, as soon as google is present and I can use new this.google.maps.Map() for example.

Even if I would like to test some methods of the Map component, I have to provide an actual google object, because otherwise the whole init process in mount() fails. It can't make a map.

So do I have to load the actual google's map API in my tests? Or could I somehow skip mounting the map but still test a few isolated methods?

Further you can see that my Map watches a getter from the vuex store: Whenever the searchCoordinates set by Search change in my vuex store, I want to execute some functions (for example center my map to the new search coordinates or remove a current location marker if the search did not return valid searchCoordinates).

How could I somehow break down the interlinking between these components, but still write good and helpful tests, which help me to guarantee that the app does what it is supposed to do?

I know that I can use a vuex store within my tests (Medium article about vuex testing).
But still I feel like the whole app is so much inter-connected that doing actual unit testing – testing one small piece at a time – is impossible.
It seems like that I would have to mount not only Map alone, but also the other components and a vuex store with actual data, to really write bulletproof tests.

A few other examples, where I struggle:

In my mounted() I subscribe to an action with this.$store.subscribeAction((action) => {... - of course $store is undefined in my tests. Should I mock it?

As I said I am watching a getter: This throws errors like TypeError: Cannot use 'in' operator to search for 'searchCoordinates' in undefined. Would I have to mock all the getters as well? If so: what remains to be tested? If I mock (~=leave away) all the vuex stuff, it seems to me, that testing becomes useless...

But maybe I am mistaken here. Also I am quite new to unit testing, so any hints are very welcome.
Thank you very much in advance. I hope somebody has some valuable input.
All those examples (even in books like Vue.js - up and running) are always broken down to very simple and understandable examples, but on the other hand don't really reflect real-life apps...

Cheers

----- Edit:

I got a needs more focus vote by someone.
So I try to sum up simple and small questions:

Summary of Questions

Does somebody have a general input on how to test larger and more complex vue applications?

Is there a way to test a component with a google map (or a component that is relying heavily on any third party code)

Is mocking getters, store and actions a good idea in this case? (I have my doubts there).

For testing watched properties from the vuex store, I read in this thread that mapState should be mocked. (in my case probably my getters). Does this make sense to mocke those getters in my case?

Is it best practice to simplify as many things as possible in an tested component (for example, I started to override some methods, which failed (the one including google map initiation) to just get my test up and running:

const initMapMock = jest.fn();
const initMarkersMock = jest.fn();
...
const wrapper = shallowMount(Map, {
    methods: {
        initMap: initMapMock, // replace initMap(), which needs google map API
        initMarkers: initMarkersMock,
      },
    ...

Does that make sense?


来源: stackexchange

问:
Is Logging using FileHandler a bottleneck?
I am considering logging business events in a J2EE web application by using Java logging and FileHandler.

I am wondering whether that could cause a performance bottleneck, since many log records will be written to one file.

What are your experiences and opinions?

Is logging a busy web application to one file with Java logging and FileHandler likely to become performance bottleneck?

答:
In a recent project, I log audit events to a database table and I was concerned about performance, so I added the ability to log in 'asynchronous' mode.  In this mode the logger runs in a low-priority background thread and the act of logging from the main thread just puts the log events onto a queue which are lazily retrieved and written by the background logging thread.

This approach will only work, however, if there are natural 'breaks' in the processing; if your system is constantly busy then the queue will never be emptied.  One way to solve this is to make the background thread more active depending on the number of the log messages in the queue (an enhancement I've yet to implement).

ContentLicense: CC BY-SA 3.0


问:
Impossible to display BottomNavigationBar in flutter
I have an issue about to display Bottom Navigation Bar. I don't understand why I have no issues in the console.

```<code>
class MyApp extends StatefulWidget {
  @override

  State<StatefulWidget> createState(){
    return _MyAppState();
  }

}

class _MyAppState extends State<MyApp>  {

  int _selectedPage =0;
  final _pageOptions = [
    HomeScreen(),
    ProfileScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    var localizationDelegate = LocalizedApp.of(context).delegate;
    return  LocalizationProvider(
      state: LocalizationProvider.of(context).state,
      child: MaterialApp(
          localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          localizationDelegate
        ],
        initialRoute: '',
        onGenerateRoute: MyRoutes().getRoute,
        supportedLocales: localizationDelegate.supportedLocales,
//        locale: localizationDelegate.currentLocale,
        theme: ThemeData( primarySwatch: Colors.red),
        home:  Scaffold(
          body: _pageOptions[_selectedPage],
          bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: _selectedPage,
              onTap: (int index){
                setState(() {
                  _selectedPage = index;
                });
              },
              items: [
                BottomNavigationBarItem(
                  icon: Icon(Icons.home),
                  title: Text('Home'),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.account_circle),
                  title: Text('Me'),
                ),
              ]
          ),
        ),
      ),
    );

  }
}

</code>```

I use flutter_translate. I know it's a very simple case but I'm stuck on it. I search in google but I find nothing which can fit my case.

Thank you.

Solved

Delete App from my device (mobile)

Flutter clean in the console

Launch Debug in Android Studio

答:
Without the location code, works fine, have you made setup of flutter_translate correctly? settings delegate and assets like below:

```<code>  var delegate = await LocalizationDelegate.create(
        fallbackLocale: 'en_US',
        supportedLocales: ['en_US', 'es', 'fa']);

  runApp(LocalizedApp(delegate, MyApp()));
</code>```

https://github.com/bratan/flutter_translate/wiki/1.-Installation,-Configuration-&-Usage

Seens to me that you have missing something in that setup.

Can you describe more what happens exactly? Show some print or gif with behavior?

see ya

ContentLicense: CC BY-SA 4.0

Body:
I have an issue about to display Bottom Navigation Bar. I don't understand why I have no issues in the console.

class MyApp extends StatefulWidget {
  @override

  State<StatefulWidget> createState(){
    return _MyAppState();
  }

}

class _MyAppState extends State<MyApp>  {

  int _selectedPage =0;
  final _pageOptions = [
    HomeScreen(),
    ProfileScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    var localizationDelegate = LocalizedApp.of(context).delegate;
    return  LocalizationProvider(
      state: LocalizationProvider.of(context).state,
      child: MaterialApp(
          localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          localizationDelegate
        ],
        initialRoute: '',
        onGenerateRoute: MyRoutes().getRoute,
        supportedLocales: localizationDelegate.supportedLocales,
//        locale: localizationDelegate.currentLocale,
        theme: ThemeData( primarySwatch: Colors.red),
        home:  Scaffold(
          body: _pageOptions[_selectedPage],
          bottomNavigationBar: BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: _selectedPage,
              onTap: (int index){
                setState(() {
                  _selectedPage = index;
                });
              },
              items: [
                BottomNavigationBarItem(
                  icon: Icon(Icons.home),
                  title: Text('Home'),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.account_circle),
                  title: Text('Me'),
                ),
              ]
          ),
        ),
      ),
    );

  }
}

I use flutter_translate. I know it's a very simple case but I'm stuck on it. I search in google but I find nothing which can fit my case.

Thank you.

Solved

Delete App from my device (mobile)

Flutter clean in the console

Launch Debug in Android Studio

Body:
Without the location code, works fine, have you made setup of flutter_translate correctly? settings delegate and assets like below:

  var delegate = await LocalizationDelegate.create(
        fallbackLocale: 'en_US',
        supportedLocales: ['en_US', 'es', 'fa']);

  runApp(LocalizedApp(delegate, MyApp()));

https://github.com/bratan/flutter_translate/wiki/1.-Installation,-Configuration-&-Usage

Seens to me that you have missing something in that setup.

Can you describe more what happens exactly? Show some print or gif with behavior?

see ya


问:
What does a returned link to a C ++ object look like
1) I do not understand what * this looks like

2) I don’t understand what the return link to the object looks like

3) When this link is returned, what happens in the part c = a = b

```<code> MyClass& operator = (const MyClass& copyObject) {
        //Copy dynamic array
        return *this
    }

    int main(){
    MyClass a(5);
    MyClass b(3)
    MyClass c(3)
    c=a=b;
    }
</code>```

答:
It's not link, it's a reference (russian ссылка is a translator's enemy word). this is pointer to instance, your operator return a reference to current object operator was called for. Dereferencing a pointer returns a reference.

That line equals to due operator associativity

```<code>c=(a=b)
</code>```

Or

```<code>c.operator=(a.operator=(b))
</code>```

Nothing happens because your operator doesn't do anything to object

Body:
1) I do not understand what * this looks like

2) I don’t understand what the return link to the object looks like

3) When this link is returned, what happens in the part c = a = b

 MyClass& operator = (const MyClass& copyObject) {
        //Copy dynamic array
        return *this
    }

    int main(){
    MyClass a(5);
    MyClass b(3)
    MyClass c(3)
    c=a=b;
    }

Body:
It's not link, it's a reference (russian ссылка is a translator's enemy word). this is pointer to instance, your operator return a reference to current object operator was called for. Dereferencing a pointer returns a reference.

That line equals to due operator associativity

c=(a=b)

Or

c.operator=(a.operator=(b))

Nothing happens because your operator doesn't do anything to object


问:
create nested object from records oriented dictionary
I have the following data frame:

```<code>[{'Name': 'foo', 'Description': 'foobar', 'Value': '5'}, {'Name': 'baz', 'Description': 'foobaz', 'Value': '4'}, {'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}]
</code>```

And I'd like to create two nested categories. One category for Name, Description keys and another category for Value key. Example of output for one object:

```<code>{'details': {'Name': 'foo', 'Description': 'foobar'}, 'stats': { 'Value': '5' }}
</code>```

so far I'm only able to achieve this by joining "manually" each items. I'm pretty sure this is not the right solution.

答:
Here is one solution:

```<code>data = [{'Name': 'foo', 'Description': 'foobar', 'Value': '5'}, {'Name': 'baz', 'Description': 'foobaz', 'Value': '4'}, {'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}]
df = pd.DataFrame(data)

m = df.to_dict('records')

stats = [{'stats':i.popitem()}  for i in m]

details = [{'details':i} for i in m]

g = list(zip(details,stats))

print(*g)

({'details': {'Name': 'foo', 'Description': 'foobar'}}, {'stats': ('Value', '5')}) ({'details': {'Name': 'baz', 'Description': 'foobaz'}}, {'stats': ('Value', '4')}) ({'details': {'Name': 'bar', 'Description': 'foofoo'}}, {'stats': ('Value', '8')})
</code>```

The major function here is popitem(), which destructively pulls out a pair from the dictionary.

Body:
I have the following data frame:

[{'Name': 'foo', 'Description': 'foobar', 'Value': '5'}, {'Name': 'baz', 'Description': 'foobaz', 'Value': '4'}, {'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}]

And I'd like to create two nested categories. One category for Name, Description keys and another category for Value key. Example of output for one object:

{'details': {'Name': 'foo', 'Description': 'foobar'}, 'stats': { 'Value': '5' }}

so far I'm only able to achieve this by joining "manually" each items. I'm pretty sure this is not the right solution.

Body:
Here is one solution:

data = [{'Name': 'foo', 'Description': 'foobar', 'Value': '5'}, {'Name': 'baz', 'Description': 'foobaz', 'Value': '4'}, {'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}]
df = pd.DataFrame(data)

m = df.to_dict('records')

stats = [{'stats':i.popitem()}  for i in m]

details = [{'details':i} for i in m]

g = list(zip(details,stats))

print(*g)

({'details': {'Name': 'foo', 'Description': 'foobar'}}, {'stats': ('Value', '5')}) ({'details': {'Name': 'baz', 'Description': 'foobaz'}}, {'stats': ('Value', '4')}) ({'details': {'Name': 'bar', 'Description': 'foofoo'}}, {'stats': ('Value', '8')})

The major function here is popitem(), which destructively pulls out a pair from the dictionary.


问:
Cannot load google-maps-react map when attempting to hide API key in a create-react-app using dotenv
I have a create-react-app that is using dotenv to hide a Google Maps API key, but when I try this I'm unable to get the map to load: I get an error saying Google Maps API error: InvalidKeyMapError. I was able to get this working before, but this was with the API key exposed.

Here's what I have in my files. In App.js:

```<code>import React, { Component } from 'react'
import { GoogleApiWrapper } from 'google-maps-react'
require('dotenv').config()

const apiKey = `${process.env.REACT_APP_GOOGLE_MAPS_KEY}`
console.log(apiKey)

...

export default GoogleApiWrapper({
apiKey: apiKey,
})(App)
</code>```

In my .env file I have: REACT_APP_GOOGLE_MAPS_KEY=myapikey

In my app.js file I pass down the google props to my MapContainer component, which is in my render method, that loads the map itself. Is there some kind of conflict with dotenv and being able to read the google-maps-react API key?

I've already tried searching for the answer here and came across this: How do I hide API key in create-react-app?

However even after restarting the server multiple times I get back the same error as well as undefined for the console.log(apiKey).

答:
For anyone struggling with this there is an alternative library called google-map-react (missing the "s") which seems to work fine with .env variables

https://github.com/google-map-react/google-map-react

Body:
I have a create-react-app that is using dotenv to hide a Google Maps API key, but when I try this I'm unable to get the map to load: I get an error saying Google Maps API error: InvalidKeyMapError. I was able to get this working before, but this was with the API key exposed.

Here's what I have in my files. In App.js:

import React, { Component } from 'react'
import { GoogleApiWrapper } from 'google-maps-react'
require('dotenv').config()

const apiKey = `${process.env.REACT_APP_GOOGLE_MAPS_KEY}`
console.log(apiKey)

...

export default GoogleApiWrapper({
apiKey: apiKey,
})(App)

In my .env file I have: REACT_APP_GOOGLE_MAPS_KEY=myapikey

In my app.js file I pass down the google props to my MapContainer component, which is in my render method, that loads the map itself. Is there some kind of conflict with dotenv and being able to read the google-maps-react API key?

I've already tried searching for the answer here and came across this: How do I hide API key in create-react-app?

However even after restarting the server multiple times I get back the same error as well as undefined for the console.log(apiKey).


问:
RHEL - Environment variable
I have an environment file named .env337_dev. I need to run this file to set the environment before running another command. How to run this file?

Inside the file, it contains several variables like this

```<code>export AB_HOME=/et/dev/abinitio/sit1/abinitio-V2   #/gcc3p32   # for 32-bit
export PATH=${AB_HOME}/bin:${PATH}
</code>```

Apart from . ./.env337_devcommand which will run and set the environment, is there any other way to run this file ?

答:
Are you looking for the user-specific .bashrc (bash is the default shell on RHEL 6) or a system-wide /etc/profile.d/<something>.sh? For the first, you would edit $HOME/.bashrc and append a line like . .env337_dev (it's still run before any "regular" command, because .bashrc is the Bash standard personal initialization file). Second option suggests that you use an absolute path.

If this doesn't answer your question, a more specific question and/or more details would be very helpful.

Title: RHEL - Environment variable

Body:
I have an environment file named .env337_dev. I need to run this file to set the environment before running another command. How to run this file?

Inside the file, it contains several variables like this

export AB_HOME=/et/dev/abinitio/sit1/abinitio-V2   #/gcc3p32   # for 32-bit
export PATH=${AB_HOME}/bin:${PATH}

Apart from . ./.env337_devcommand which will run and set the environment, is there any other way to run this file ?


问:
how to reference a YAML "setting" from elsewhere in the same YAML file?
I have the following YAML:

```<code>paths:
  patha: /path/to/root/a
  pathb: /path/to/root/b
  pathc: /path/to/root/c
</code>```

How can I "normalise" this, by removing /path/to/root/ from the three paths, and have it as its own setting, something like:

```<code>paths:
  root: /path/to/root/
  patha: *root* + a
  pathb: *root* + b
  pathc: *root* + c
</code>```

Obviously that's invalid, I just made it up. What's the real syntax? Can it be done?

答:
With Yglu, you can write your example as:

```<code>paths:
  root: /path/to/root/
  patha: !? .paths.root + a
  pathb: !? .paths.root + b
  pathc: !? .paths.root + c
</code>```

Disclaimer: I am the author of Yglu.

Body:
I have the following YAML:

paths:
  patha: /path/to/root/a
  pathb: /path/to/root/b
  pathc: /path/to/root/c

How can I "normalise" this, by removing /path/to/root/ from the three paths, and have it as its own setting, something like:

paths:
  root: /path/to/root/
  patha: *root* + a
  pathb: *root* + b
  pathc: *root* + c

Obviously that's invalid, I just made it up. What's the real syntax? Can it be done?

Body:
With Yglu, you can write your example as:

paths:
  root: /path/to/root/
  patha: !? .paths.root + a
  pathb: !? .paths.root + b
  pathc: !? .paths.root + c

Disclaimer: I am the author of Yglu.


问:
Duplicate identifier when declaring types with same name in different files
I have a simple TypeScript 'snippets' project, and I've run into an issue where multiple .ts files will have the same type names (eg. Foo).

```<code>//file-a.ts

type Foo = {

}
</code>```

```<code>//file-b.ts

type Foo = {

}
</code>```

If I try compile this I get:

```<code> error TS2300: Duplicate identifier 'Foo'.
</code>```

This doesn't make sense to me - as these typings should be specific to the module.

I'm using typescript version 3.7.5, and my tsconfig.json has these properties (everything else defaults):

```<code>{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

</code>```

What's going on here here? The actual code here.

答: If you do not export anything from a TypeScript file, it gets compiled in the global scope. To make a .ts file an enclosed module you need to export at least one thing.

Body:
I have a simple TypeScript 'snippets' project, and I've run into an issue where multiple .ts files will have the same type names (eg. Foo).

//file-a.ts

type Foo = {

}

//file-b.ts

type Foo = {

}

If I try compile this I get:

 error TS2300: Duplicate identifier 'Foo'.

This doesn't make sense to me - as these typings should be specific to the module.

I'm using typescript version 3.7.5, and my tsconfig.json has these properties (everything else defaults):

{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

What's going on here here? The actual code here.


问:
gradlew.bat failed with exit code 1
i am very new to nativescript, i try to build my first app in nativescript, but it shows

=============================================================================
C:\Nativescript\Grab1>

C:\Nativescript\Grab1>tns prepare android
Executing before-prepare hook from C:\Nativescript\Grab1\hooks\before-prepare\na
tivescript-dev-android-snapshot.js
Preparing project...
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further detail
s.

FAILURE: Build failed with an exception.

What went wrong:
org/slf4j/impl/StaticLoggerBinder

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output.
Processing node_modules failed. Error: Command C:\Nativescript\Grab1\platforms\a
ndroid\gradlew.bat failed with exit code 1

C:\Nativescript\Grab1>

================================================================================

here i attached my command prompt screen shot also, please help me to solve this problem friends

答:
Just in case if someone out there is having the same problem on MacOS systems

tns platform remove iOS

tns platform add iOS

Title: gradlew.bat failed with exit code 1


问:
R Custom Order Output Of paste0
I desire to paste text in specific order. This is my attempt at it:

```<code>paste0("car",1:3, "conv",1:3)
</code>```

but this gives "car1conv1" "car2conv2" "car3conv3"

my desired outputs are:

"car1","conv1","car2","conv2","car3","conv3"

i am not sure how to do the ordering other than doing it manually but just imagine having to do this for 100 items, so i am seeking assitance in generating this type of output in 1 or 2 steps thanks so much.

答:
We can use outer

```<code>c(outer(c("car", "conv"), 1:3, paste0))
#[1] "car1"  "conv1" "car2"  "conv2" "car3"  "conv3"
</code>```

Title: R Custom Order Output Of paste0

Body:
I desire to paste text in specific order. This is my attempt at it:

paste0("car",1:3, "conv",1:3)

but this gives "car1conv1" "car2conv2" "car3conv3"

my desired outputs are:

"car1","conv1","car2","conv2","car3","conv3"

i am not sure how to do the ordering other than doing it manually but just imagine having to do this for 100 items, so i am seeking assitance in generating this type of output in 1 or 2 steps thanks so much.

Body:
We can use outer

c(outer(c("car", "conv"), 1:3, paste0))
#[1] "car1"  "conv1" "car2"  "conv2" "car3"  "conv3"


问:
execute exe file using Jint - Javascript Interpreter
i have a created one console application and in that i had use Jint - JavaScript Interpreter to run javascript function . but when i use activexobject in javascript it give me a error the code is:

```<code>string  script= @"
                  function square() {
                    MyObject = new ActiveXObject( 'WScript.Shell' );
                    MyObject.Run('file:///D:/test/Tools/ofc.exe D:/test/Tools/ofc.ini') ;
                    return 2 * 2;
                  };

                  return square();
                  ";

var result = new JintEngine()
                  .Run(script);
</code>```

Can anyone tell me how can i do this?

答:
Jint doesn't know what ActiveXObject is, so you have to tell Jint. I don't know if you can pass something into a JintEngine which can be treated as a JavaScript constructor, but you can register a custom function which creates an instance for a given COM ProgId:

```<code>private delegate object CreateActiveXObjectDelegate(string progId);

private static object CreateActiveXObject(string progId)
{
    var type = Type.GetTypeFromProgID(progId);
    if(type!=null)
    {
        return Activator.CreateInstance(type);
    } else
    {
        return null; // alternatively throw an exception or whatever is suitable in your situation
    }
}
</code>```

Then you can register this method as a function in your JintEngine which then can be called from your script:

```<code>string script = @"
          function square() {
            MyObject = createActiveXObject('WScript.Shell' );
            MyObject.Run('whatever');
            return 2 * 2;
          };

          return square();
          ";
var jintEngine = new JintEngine();
jintEngine.DisableSecurity(); // required, cannot tell why exactly
jintEngine.SetFunction("createActiveXObject", (CreateActiveXObjectDelegate)CreateActiveXObject);
var result = jintEngine.Run(script);
</code>```

Jint uses reflection when it tries to call MyObject.Run, which fails in my example with an error saying Method isn't defined: Run. I suspect that calling Run doesn't work because COM-Interop and reflection can get tricky (I think MethodInfos cannot be retrieved from the underlying COM type).

A different approach might be to register a function which simply calls WScript.Shell.Run (or maybe even better: System.Diagnostics.Process.Start):

```<code>private delegate void Runner(string progId);

private static void ShellRun(string command)
{
    var type = Type.GetTypeFromProgID("WScript.Shell");
    if(type!=null)
    {
        var shell = Activator.CreateInstance(type);
        type.InvokeMember("Run", BindingFlags.InvokeMethod, null, shell, new object[] {command});
    }
}
</code>```

Then call ShellRun from you script (registered as run):

```<code>string script = @"
              function square() {
                run('whatever');
                return 2 * 2;
              };

              return square();
              ";

var jintEngine = new JintEngine();
jintEngine.DisableSecurity(); // required, cannot tell why exactly
jintEngine.SetFunction("run", (Runner)ShellRun);
var result = jintEngine.Run(script);
</code>```

Hope that helps.

ContentLicense: CC BY-SA 2.5

Body:
i have a created one console application and in that i had use Jint - JavaScript Interpreter to run javascript function . but when i use activexobject in javascript it give me a error the code is:

string  script= @"
                  function square() {
                    MyObject = new ActiveXObject( 'WScript.Shell' );
                    MyObject.Run('file:///D:/test/Tools/ofc.exe D:/test/Tools/ofc.ini') ;
                    return 2 * 2;
                  };

                  return square();
                  ";

var result = new JintEngine()
                  .Run(script);

Can anyone tell me how can i do this?

Body:
Jint doesn't know what ActiveXObject is, so you have to tell Jint. I don't know if you can pass something into a JintEngine which can be treated as a JavaScript constructor, but you can register a custom function which creates an instance for a given COM ProgId:

private delegate object CreateActiveXObjectDelegate(string progId);

private static object CreateActiveXObject(string progId)
{
    var type = Type.GetTypeFromProgID(progId);
    if(type!=null)
    {
        return Activator.CreateInstance(type);
    } else
    {
        return null; // alternatively throw an exception or whatever is suitable in your situation
    }
}

Then you can register this method as a function in your JintEngine which then can be called from your script:

string script = @"
          function square() {
            MyObject = createActiveXObject('WScript.Shell' );
            MyObject.Run('whatever');
            return 2 * 2;
          };

          return square();
          ";
var jintEngine = new JintEngine();
jintEngine.DisableSecurity(); // required, cannot tell why exactly
jintEngine.SetFunction("createActiveXObject", (CreateActiveXObjectDelegate)CreateActiveXObject);
var result = jintEngine.Run(script);

Jint uses reflection when it tries to call MyObject.Run, which fails in my example with an error saying Method isn't defined: Run. I suspect that calling Run doesn't work because COM-Interop and reflection can get tricky (I think MethodInfos cannot be retrieved from the underlying COM type).

A different approach might be to register a function which simply calls WScript.Shell.Run (or maybe even better: System.Diagnostics.Process.Start):

private delegate void Runner(string progId);

private static void ShellRun(string command)
{
    var type = Type.GetTypeFromProgID("WScript.Shell");
    if(type!=null)
    {
        var shell = Activator.CreateInstance(type);
        type.InvokeMember("Run", BindingFlags.InvokeMethod, null, shell, new object[] {command});
    }
}

Then call ShellRun from you script (registered as run):

string script = @"
              function square() {
                run('whatever');
                return 2 * 2;
              };

              return square();
              ";

var jintEngine = new JintEngine();
jintEngine.DisableSecurity(); // required, cannot tell why exactly
jintEngine.SetFunction("run", (Runner)ShellRun);
var result = jintEngine.Run(script);

Hope that helps.


问:
how to create a keystore with a specific website cert for java clients?
In chrome, you can click the 'lock' icon to the left of the https url and this comes up

I don't see a way to download this though and then how do I install it in a keystore.  Also, it looks like I would have to download 3 different ones?

thanks,
Dean

答:
Ah, ok, I finally ran into this answer on exporting which was tricky...drag and drop into finder on MAC ..

How to Export Certificate from Chrome on a Mac?


问:
Whats the best/simplest way to protect API keys in Xcode?
I am working on a simple iOS app in Swift that uses an API that I pay for. I do not have a ton of resources and have yet to find a simple/up to date solution to this issue. I want to protect my API key and not put the key directly in my code where I make requests (I have heard this is best practice).
What would be the simplest way to protect my API key from someone taking apart my code and using it.

I've heard something about using Keychain but I'm unsure if this is the best route.

```<code>class APIService {

    static let shared = APIService()
    private let token = "(my token goes here)"

    //...various API request functions
}
</code>```

答:
There is no easy way, nor is there a way to completely protect them from attackers.  You can always do some simple key obfuscation or store them in a server but if a hacker can reverse-engineer your code they can likely reverse-engineer your obfuscation.

It'd be good to develop safety measures to take if someone does get your keys (database backups, etc.. ).

This link helped me when I was originally looking into this topic for one of my apps.

Body:
I am working on a simple iOS app in Swift that uses an API that I pay for. I do not have a ton of resources and have yet to find a simple/up to date solution to this issue. I want to protect my API key and not put the key directly in my code where I make requests (I have heard this is best practice).
What would be the simplest way to protect my API key from someone taking apart my code and using it.

I've heard something about using Keychain but I'm unsure if this is the best route.

class APIService {

    static let shared = APIService()
    private let token = "(my token goes here)"

    //...various API request functions
}


问:
reading a txt file of String of scientific notation converting to numerical
I have a .txt file I am reading from and it looks something like this:

```<code>-1.000000000000000000e+01 4.495406013054247296e+02
-9.933110367892975745e+00 7.574962784496592576e+02
-9.866220735785953266e+00 9.492438285952409842e+02
-9.799331103678929011e+00 1.096930466897883889e+03
...
</code>```

I am reading this into a 2D array and then putting into separate column arrays. When I do this, I receive an error and am not sure what to do.

```<code>with open("hw2_data.txt", "r") as dataFile:
    data = [line.split() for line in dataFile]
i = 0
x = []
y = []
for line in lines:
    x.append(int(data[i][0]))
    y.append(data[i][1])
    i = i + 1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-b77a8a85fae8> in <module>()
      3 y = []
      4 for line in lines:
----> 5     x.append(int(data[i][0]))
      6     y.append(data[i][1])
      7     i = i + 1

ValueError: invalid literal for int() with base 10: '-1.000000000000000000e+01'
</code>```

What is the solution to this problem?
A few days new to python here and would also appreciate an explanation!

答:
The question is solved, but this answer shall update on any users coming here with same problem. The problem is that a ValueError is thrown if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, you can convert to a float first, then to an integer:

The code below should show you what's going wrong with your input.

```<code>>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5
</code>```

As you've mentioned in the comments then converting into float instead of int would also work, like this.

```<code>x.append(float(data[i][0]))
</code>```

You can read more about it here

Body:
I have a .txt file I am reading from and it looks something like this:

-1.000000000000000000e+01 4.495406013054247296e+02
-9.933110367892975745e+00 7.574962784496592576e+02
-9.866220735785953266e+00 9.492438285952409842e+02
-9.799331103678929011e+00 1.096930466897883889e+03
...

I am reading this into a 2D array and then putting into separate column arrays. When I do this, I receive an error and am not sure what to do.

with open("hw2_data.txt", "r") as dataFile:
    data = [line.split() for line in dataFile]
i = 0
x = []
y = []
for line in lines:
    x.append(int(data[i][0]))
    y.append(data[i][1])
    i = i + 1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-b77a8a85fae8> in <module>()
      3 y = []
      4 for line in lines:
----> 5     x.append(int(data[i][0]))
      6     y.append(data[i][1])
      7     i = i + 1

ValueError: invalid literal for int() with base 10: '-1.000000000000000000e+01'

What is the solution to this problem?
A few days new to python here and would also appreciate an explanation!

Body:
The question is solved, but this answer shall update on any users coming here with same problem. The problem is that a ValueError is thrown if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, you can convert to a float first, then to an integer:

The code below should show you what's going wrong with your input.

>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5

As you've mentioned in the comments then converting into float instead of int would also work, like this.

x.append(float(data[i][0]))

You can read more about it here


问:
How Can i remove duplicate from a list in Groovy
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

```<code>["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]
</code>```

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

```<code>// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.
</code>```

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

答:
Sounds like you want to use groupBy method:

```<code>def list = ['154515 Sawgrass', '170985 Mexico APIs for Payments', '153026 CitiCards Consumer and Business Account Online (authenticated pgs)', 'No CSI App ID', '153890 GC Citibank Online - Singapore IPB v3', '144564 Citibank Online (CBOL) US', 'Zack Dummy CSI #3', '171706 Quip', '167518 GC Eclipse [Teller]', '167518 GC Eclipse [Signature]']

List result = list.groupBy{ String s ->
    String num
    s.eachMatch( /^(\d+).+$/ ){ num = it[ 1 ] }
    num
}.findResults{ String num, List<String> vals ->
    num ? vals.sort().first() : null
}
</code>```

1st the groupBy is called groupping by "id" using the regex, as a result you are getting a map keyed by the "id" and valued with a list of matching strings.

Then the findResults is called to filter out mismatching values like 'No CSI App ID', and sort the match lists alphabetically and get the first() (or last()) element out of it.

The result would look like:

[154515 Sawgrass, 170985 Mexico APIs for Payments, 153026 CitiCards Consumer and Business Account Online (authenticated pgs), 153890 GC Citibank Online - Singapore IPB v3, 144564 Citibank Online (CBOL) US, 171706 Quip, 167518 GC Eclipse [Signature]]

Body:
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

Body:
Sounds like you want to use groupBy method:

def list = ['154515 Sawgrass', '170985 Mexico APIs for Payments', '153026 CitiCards Consumer and Business Account Online (authenticated pgs)', 'No CSI App ID', '153890 GC Citibank Online - Singapore IPB v3', '144564 Citibank Online (CBOL) US', 'Zack Dummy CSI #3', '171706 Quip', '167518 GC Eclipse [Teller]', '167518 GC Eclipse [Signature]']

List result = list.groupBy{ String s ->
    String num
    s.eachMatch( /^(\d+).+$/ ){ num = it[ 1 ] }
    num
}.findResults{ String num, List<String> vals ->
    num ? vals.sort().first() : null
}

1st the groupBy is called groupping by "id" using the regex, as a result you are getting a map keyed by the "id" and valued with a list of matching strings.

Then the findResults is called to filter out mismatching values like 'No CSI App ID', and sort the match lists alphabetically and get the first() (or last()) element out of it.

The result would look like:

[154515 Sawgrass, 170985 Mexico APIs for Payments, 153026 CitiCards Consumer and Business Account Online (authenticated pgs), 153890 GC Citibank Online - Singapore IPB v3, 144564 Citibank Online (CBOL) US, 171706 Quip, 167518 GC Eclipse [Signature]]


问:
Pathname to the image field in Django
I have this model which has Image field to be uploaded. It has a foreign key reference to another class.

```<code>from django.template.defaultfilters import slugify

def upload_to(path, attribute):

    def upload_callback(instance, filename):
        return '%s%s/%s' % (path, unicode(slugify(getattr(instance, attribute))), filename)

    return upload_callback

class Data(models.Model):
    place = models.CharField(max_length=40)
    typeOfProperty = models.CharField(max_length=30)
    typeOfPlace = models.CharField(max_length=20)
    price = models.IntegerField()
    ownerName = models.CharField(max_length=80)

class ImageData(models.Model):
    property = models.ForeignKey(Data, related_name='images')
    image = models.ImageField(upload_to = upload_to('image/', 'ownerName'),blank=True,null=True)

    def __unicode__(self):
        return self.property.ownerName
</code>```

I have refered this This Web Page to create a dynamic field for images to be stored.

My doubt is can I use the onerName as the attribute in (as the ownerName is in the super class) :

```<code>image = models.ImageField(upload_to = upload_to('image/', 'ownerName'),blank=True,null=True)
</code>```

How does Django consider this request that is need to be served?

Please can anyone explain me this?

答:
'ownerName' is not going to work. It's quite complicated to do the definition of what you want to save in the ImageField directly. Maybe you should do something like this:

```<code>def upload_to(path):

    def upload_callback(instance, filename):
        return '%s%s/%s' % (path, unicode(slugify(instance.property.ownerName), filename)

    return upload_callback
</code>```

If you really want to make it as dynamic as possible you have to pass something like 'property.ownerName' to the function, split the string, retrieve attrtibute property from ImageData instance and then attribute ownerName from its foreign key instance.

Though I think this makes things way to complicated and you better define extra functions for different use cases.

Title: Pathname to the image field in Django

Body:
I have this model which has Image field to be uploaded. It has a foreign key reference to another class.

from django.template.defaultfilters import slugify

def upload_to(path, attribute):

    def upload_callback(instance, filename):
        return '%s%s/%s' % (path, unicode(slugify(getattr(instance, attribute))), filename)

    return upload_callback

class Data(models.Model):
    place = models.CharField(max_length=40)
    typeOfProperty = models.CharField(max_length=30)
    typeOfPlace = models.CharField(max_length=20)
    price = models.IntegerField()
    ownerName = models.CharField(max_length=80)

class ImageData(models.Model):
    property = models.ForeignKey(Data, related_name='images')
    image = models.ImageField(upload_to = upload_to('image/', 'ownerName'),blank=True,null=True)

    def __unicode__(self):
        return self.property.ownerName

I have refered this This Web Page to create a dynamic field for images to be stored.

My doubt is can I use the onerName as the attribute in (as the ownerName is in the super class) :

image = models.ImageField(upload_to = upload_to('image/', 'ownerName'),blank=True,null=True)

How does Django consider this request that is need to be served?

Please can anyone explain me this?

Body:
'ownerName' is not going to work. It's quite complicated to do the definition of what you want to save in the ImageField directly. Maybe you should do something like this:

def upload_to(path):

    def upload_callback(instance, filename):
        return '%s%s/%s' % (path, unicode(slugify(instance.property.ownerName), filename)

    return upload_callback

If you really want to make it as dynamic as possible you have to pass something like 'property.ownerName' to the function, split the string, retrieve attrtibute property from ImageData instance and then attribute ownerName from its foreign key instance.

Though I think this makes things way to complicated and you better define extra functions for different use cases.


问:
Convert Raw CSV Line into Array
The other suggestions were either in Java, or didn't take this into account (that I found).

```<code>reader := bufio.NewReader(file)
for err == nil {
    line, err = Readln(reader)
    record := strings.Split(line, ",")
    fmt.Println(len(record), line)
}
</code>```

Using this loop, I'm efficiently reading through my CSV file, however, there is a problem with Split when it encounters a row that has commas inside the intended value. For example, "Fake Company USA, Inc.",
strings.Split will split on that comma inside the string as well.

Is there a way to Split on the intended comma here? Such as, a comma with 0 white space around it, or a comma that isn't surrounded by quotes?

Note: I'm going the raw method becausethe csv readers I was using before didn't play well with large files, so I'm resorting to bufio for processing sake.

答:
Is there a reason you wouldn't use the built in encoding/csv package?  As long as you use .Read and not .ReadAll the performance should be the same as reading line by line and trying to split yourself.

```<code>import (
    "encoding/csv"
    "io"
    "fmt"
)

reader := csv.NewReader(file)

for {
    records, err := reader.Read()
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatal(err)
    }

    fmt.Println(records)
}
</code>```

Title: Convert Raw CSV Line into Array

Body:
The other suggestions were either in Java, or didn't take this into account (that I found).

reader := bufio.NewReader(file)
for err == nil {
    line, err = Readln(reader)
    record := strings.Split(line, ",")
    fmt.Println(len(record), line)
}

Using this loop, I'm efficiently reading through my CSV file, however, there is a problem with Split when it encounters a row that has commas inside the intended value. For example, "Fake Company USA, Inc.",
strings.Split will split on that comma inside the string as well.

Is there a way to Split on the intended comma here? Such as, a comma with 0 white space around it, or a comma that isn't surrounded by quotes?

Note: I'm going the raw method becausethe csv readers I was using before didn't play well with large files, so I'm resorting to bufio for processing sake.

Body:
Is there a reason you wouldn't use the built in encoding/csv package?  As long as you use .Read and not .ReadAll the performance should be the same as reading line by line and trying to split yourself.

import (
    "encoding/csv"
    "io"
    "fmt"
)

reader := csv.NewReader(file)

for {
    records, err := reader.Read()
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatal(err)
    }

    fmt.Println(records)
}


问:
Java Client Server menu
So i am trying to make a java Client Server application. On the client side I have a menu with options for the user to select. What I want the server to do then is respond to the option entered with the appropriate data. Here is my code, where am I going wrong?(I also have a players database class created with functions but no need to include for answer to my question)

Server class

```<code>public class Server {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SQLException {
        try {

            System.out.println("Server started and awaiting connections....");
            // Create a server socket
            ServerSocket serverSocket = new ServerSocket(8000);

            // Start listening for connections on the server socket
            Socket connectToClient = serverSocket.accept();

            // Create an input stream to get data from the client
            DataInputStream isFromClient = new DataInputStream(
                    connectToClient.getInputStream());

            // Create an output stream to send data to the client
            DataOutputStream osToClient = new DataOutputStream(
                    connectToClient.getOutputStream());

            InetAddress clientInetAddress = connectToClient.getInetAddress();

            System.out.println("Clients host name is " + clientInetAddress.getHostName());
            System.out.println("Clients IP address is " + clientInetAddress.getHostAddress());

            // Continuously read from the client and process it,
            // and send result back to the client
            while (true) {

                // Read a string from the input stream
                int option = isFromClient.readInt();

                // Display option on console
                System.out.println("Option received from client: " + option);

                // Compute option

                //int x = (int) option1();
                if (option == 1){
                       List<players> list = PlayersDB.getAllplayers();
                    //System.out.println("Number of players " + list.size());
                    int x = list.size();
                // Send the result to the client
                osToClient.writeInt(x);
                osToClient.flush();

                // Print the result to the console
                System.out.println("Answer to opton is: " + x);
                }

            }//end while
        }//end try
        catch (IOException ex) {
            System.err.println(ex);
        }//end catch
    }}
</code>```

2.Client Class

```<code>public class Client {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

                try {

            Scanner scanner = new Scanner(System.in);

            // Create a socket to connect to the server
            // Socket connectToServer = new Socket("130.254.32.8", 8000);
            Socket connectToServer = new Socket("localhost", 8000);

            // Create an input stream to receive data from the server
            DataInputStream isFromServer = new DataInputStream(
                    connectToServer.getInputStream());

            // Create an output stream to send data to the server
            DataOutputStream osToServer
                    = new DataOutputStream(connectToServer.getOutputStream());

            // Continuously send radius and receive area from the server
            while (true) {
                // Read the radius from the keyboard
                System.out.println("Please select an option:");
                System.out.println("1 - Number of players:");
                System.out.println("2 - Number of English players:");

                int option = scanner.nextInt();

                // Send the option selected to the server
                osToServer.writeInt(option);
                osToServer.flush();

                // Get answer from the server
                int answer = isFromServer.readInt();

                // Print answer on the console
                System.out.println("Answer to the selected option is " + answer);

            }//end while
        }//end try
        catch (IOException ex) {
            System.err.println(ex);
        }//end catch
    }
}
</code>```

答:
Change order of input/output stream opening on the client or on the server.
If you opening input stream on one side, current thread will be blocked until the on the other end will be opened output stream and vice versa.
I suppose now your programs just hang.</p>

Title: Java Client Server menu

Body:
So i am trying to make a java Client Server application. On the client side I have a menu with options for the user to select. What I want the server to do then is respond to the option entered with the appropriate data. Here is my code, where am I going wrong?(I also have a players database class created with functions but no need to include for answer to my question)

Server class

public class Server {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SQLException {
        try {

            System.out.println("Server started and awaiting connections....");
            // Create a server socket
            ServerSocket serverSocket = new ServerSocket(8000);

            // Start listening for connections on the server socket
            Socket connectToClient = serverSocket.accept();

            // Create an input stream to get data from the client
            DataInputStream isFromClient = new DataInputStream(
                    connectToClient.getInputStream());

            // Create an output stream to send data to the client
            DataOutputStream osToClient = new DataOutputStream(
                    connectToClient.getOutputStream());

            InetAddress clientInetAddress = connectToClient.getInetAddress();

            System.out.println("Clients host name is " + clientInetAddress.getHostName());
            System.out.println("Clients IP address is " + clientInetAddress.getHostAddress());

            // Continuously read from the client and process it,
            // and send result back to the client
            while (true) {

                // Read a string from the input stream
                int option = isFromClient.readInt();

                // Display option on console
                System.out.println("Option received from client: " + option);

                // Compute option

                //int x = (int) option1();
                if (option == 1){
                       List<players> list = PlayersDB.getAllplayers();
                    //System.out.println("Number of players " + list.size());
                    int x = list.size();
                // Send the result to the client
                osToClient.writeInt(x);
                osToClient.flush();

                // Print the result to the console
                System.out.println("Answer to opton is: " + x);
                }

            }//end while
        }//end try
        catch (IOException ex) {
            System.err.println(ex);
        }//end catch
    }}

2.Client Class

public class Client {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

                try {

            Scanner scanner = new Scanner(System.in);

            // Create a socket to connect to the server
            // Socket connectToServer = new Socket("130.254.32.8", 8000);
            Socket connectToServer = new Socket("localhost", 8000);

            // Create an input stream to receive data from the server
            DataInputStream isFromServer = new DataInputStream(
                    connectToServer.getInputStream());

            // Create an output stream to send data to the server
            DataOutputStream osToServer
                    = new DataOutputStream(connectToServer.getOutputStream());

            // Continuously send radius and receive area from the server
            while (true) {
                // Read the radius from the keyboard
                System.out.println("Please select an option:");
                System.out.println("1 - Number of players:");
                System.out.println("2 - Number of English players:");

                int option = scanner.nextInt();

                // Send the option selected to the server
                osToServer.writeInt(option);
                osToServer.flush();

                // Get answer from the server
                int answer = isFromServer.readInt();

                // Print answer on the console
                System.out.println("Answer to the selected option is " + answer);

            }//end while
        }//end try
        catch (IOException ex) {
            System.err.println(ex);
        }//end catch
    }
}


问:
How to Import All Element Nodes in Google Sheets from XML
Is there a way to download a full XML schema including headers into a Google Sheet worksheet?

I'm looking to import all elements including the headers from an online XML page into Google Sheets.

The XML page looks like this:

```<code><staff>
    <admin>
        <first-name>Patrice</first-name>
        <family-name>Withers</family-name>
        <year-started>2006</year-started>
        <starting-salary>30,500</starting-salary>
        <current-salary>34,000</current-salary>
    </admin>
    <admin>
        <first-name>Shelly</first-name>
        <family-name>Lancer</family-name>
        <year-started>2015</year-started>
        <starting-salary>32,500</starting-salary>
        <current-salary>33,500</current-salary>
    </admin>
</staff>
<students>
    <full-time>
        <first-name>Henry</first-name>
        <family-name>Nunes</family-name>
        <status>Freshman</status>
        <current-tuition>2,400</current-tuition>
        <last-year-tuition>2,200</last-year-tuition>
    </full-time>
    <part-time>
        <first-name>Leslie</first-name>
        <family-name>Franks</family-name>
        <status>Senior</status>
        <current-tuition>2,300</current-tuition>
        <last-year-tuition>2,100</last-year-tuition>
    </part-time>
</students>
</code>```

I'm trying to have Google Sheets download the full XML page, including the element headers, and display it, preferably as above in indented columns, or in a single column to look like this:

```<code><staff>
<admin>
<first-name>Patrice</first-name>
<family-name>Withers</family-name>
<year-started>2006</year-started>
<starting-salary>30,500</starting-salary>
<current-salary>34,000</current-salary>
</admin>
<admin>
<first-name>Shelly</first-name>
<family-name>Lancer</family-name>
<year-started>2015</year-started>
<starting-salary>32,500</starting-salary>
<current-salary>33,500</current-salary>
</admin>
</staff>
<students>
<full-time>
<first-name>Henry</first-name>
<family-name>Nunes</family-name>
<status>Freshman</status>
<current-tuition>2,400</current-tuition>
<last-year-tuition>2,200</last-year-tuition>
</full-time>
<part-time>
<first-name>Leslie</first-name>
<family-name>Franks</family-name>
<status>Senior</status>
<current-tuition>2,300</current-tuition>
<last-year-tuition>2,100</last-year-tuition>
</students>
</code>```

IMPORTDATA, as another user was advised with a similar question here, failed because some of the XML data have commas, similar to the sample output above.

答:
if the url of yours can be scraped from behind authentication credentials you could try:

```<code>=ARRAYFORMULA(TRIM(TRANSPOSE(QUERY(TRANSPOSE(
 ARRAY_CONSTRAIN(IMPORTDATA("url_here"), 5000, 20)),,999^99))))
</code>```

also you could perhaps try:

```<code>=IMPORTXML("url_here", "//*")
</code>```

Body:
Is there a way to download a full XML schema including headers into a Google Sheet worksheet?

I'm looking to import all elements including the headers from an online XML page into Google Sheets.

The XML page looks like this:

<staff>
    <admin>
        <first-name>Patrice</first-name>
        <family-name>Withers</family-name>
        <year-started>2006</year-started>
        <starting-salary>30,500</starting-salary>
        <current-salary>34,000</current-salary>
    </admin>
    <admin>
        <first-name>Shelly</first-name>
        <family-name>Lancer</family-name>
        <year-started>2015</year-started>
        <starting-salary>32,500</starting-salary>
        <current-salary>33,500</current-salary>
    </admin>
</staff>
<students>
    <full-time>
        <first-name>Henry</first-name>
        <family-name>Nunes</family-name>
        <status>Freshman</status>
        <current-tuition>2,400</current-tuition>
        <last-year-tuition>2,200</last-year-tuition>
    </full-time>
    <part-time>
        <first-name>Leslie</first-name>
        <family-name>Franks</family-name>
        <status>Senior</status>
        <current-tuition>2,300</current-tuition>
        <last-year-tuition>2,100</last-year-tuition>
    </part-time>
</students>

I'm trying to have Google Sheets download the full XML page, including the element headers, and display it, preferably as above in indented columns, or in a single column to look like this:

<staff>
<admin>
<first-name>Patrice</first-name>
<family-name>Withers</family-name>
<year-started>2006</year-started>
<starting-salary>30,500</starting-salary>
<current-salary>34,000</current-salary>
</admin>
<admin>
<first-name>Shelly</first-name>
<family-name>Lancer</family-name>
<year-started>2015</year-started>
<starting-salary>32,500</starting-salary>
<current-salary>33,500</current-salary>
</admin>
</staff>
<students>
<full-time>
<first-name>Henry</first-name>
<family-name>Nunes</family-name>
<status>Freshman</status>
<current-tuition>2,400</current-tuition>
<last-year-tuition>2,200</last-year-tuition>
</full-time>
<part-time>
<first-name>Leslie</first-name>
<family-name>Franks</family-name>
<status>Senior</status>
<current-tuition>2,300</current-tuition>
<last-year-tuition>2,100</last-year-tuition>
</students>

IMPORTDATA, as another user was advised with a similar question here, failed because some of the XML data have commas, similar to the sample output above.

Body:
if the url of yours can be scraped from behind authentication credentials you could try:

=ARRAYFORMULA(TRIM(TRANSPOSE(QUERY(TRANSPOSE(
 ARRAY_CONSTRAIN(IMPORTDATA("url_here"), 5000, 20)),,999^99))))

also you could perhaps try:

=IMPORTXML("url_here", "//*")


问:
Not able to attach click event to an Anchor tag inside a react component
Below is my code
ComponentA.js

return statement inside the component

```<code> return (
       ......

        <a id="MytoolTip" ......

       <ComponentB
          content={
            `
            <div class="share_cart_tt">
                  <a
                  data-automation-id="..."
                  class="callFunction"
                   > Invite </a>
            </div>
           `
          }
          target={'MytoolTip'}
          closeButton
       />

);
</code>```

ComponentB.js (this is a tooltip which will be displayed when user clicks on anchor tag MytoolTip)

```<code>.....

class ComponentB extends Component {
  launchModal() {
    console.log("hey its fine");
  }
     ...
      renderContent = () => {
          document.getElementsByClassName('callFunction').
          addEventListener('click', this.launchModal);
      **I am trying to bind click event here but its not working out**
     }

}
</code>```

I am beginner to react and I tried different methods to bind the click event but nothing worked out.. need help.
When the user click on the anchor tag inside the tooltip with class .callFunction console.log should be printed.

Please note that I am trying to add onClick event to the anchor tag, which is just a static content in ComponentA and a tooltip will be created by getting static content in prop.content in ComponentB

答:
React components have synthetic event listeners.  All you need to do is add the onClick property to the element. So yours would look like this:

```<code>return (
       ......

        <a id="MytoolTip" ......

       <ComponentB
          content={
            `
            <div class="share_cart_tt">
                  <a
                  data-automation-id="..."
                  onClick={FunctionToBeCalledWhenClicked}
                  class="callFunction"
                   > Invite </a>
            </div>
           `
          }
          target={'MytoolTip'}
          closeButton
       />

);
</code>```

Body:
Below is my code
ComponentA.js

return statement inside the component

 return (
       ......

        <a id="MytoolTip" ......

       <ComponentB
          content={
            `

                   Invite

           `
          }
          target={'MytoolTip'}
          closeButton
       />

);

ComponentB.js (this is a tooltip which will be displayed when user clicks on anchor tag MytoolTip)

.....

class ComponentB extends Component {
  launchModal() {
    console.log("hey its fine");
  }
     ...
      renderContent = () => {
          document.getElementsByClassName('callFunction').
          addEventListener('click', this.launchModal);
      **I am trying to bind click event here but its not working out**
     }

}

I am beginner to react and I tried different methods to bind the click event but nothing worked out.. need help.
When the user click on the anchor tag inside the tooltip with class .callFunction console.log should be printed.

Please note that I am trying to add onClick event to the anchor tag, which is just a static content in ComponentA and a tooltip will be created by getting static content in prop.content in ComponentB

Body:
React components have synthetic event listeners.  All you need to do is add the onClick property to the element. So yours would look like this:

return (
       ......

        <a id="MytoolTip" ......

       <ComponentB
          content={
            `
            <div class="share_cart_tt">
                  <a
                  data-automation-id="..."
                  onClick={FunctionToBeCalledWhenClicked}
                  class="callFunction"
                   > Invite </a>
            </div>
           `
          }
          target={'MytoolTip'}
          closeButton
       />

);


问:
Trying to create bar plot from data frame in R
I would like to better visualize a set of data I created in R using the barplot() function. However, I am unsure how to go about this procedure based on 2 columns in a data frame.

name of my data frame: myData

Below is the contents of my data frame:

```<code>   States Churn
1      AK     3
2      AL     8
3      AR    11
4      AZ     4
5      CA     9
6      CO     9
7      CT    12
8      DC     5
9      DE     9
10     FL     8
11     GA     8
12     HI     3
13     IA     3
14     ID     9
15     IL     5
16     IN     9
17     KS    13
18     KY     8
19     LA     4
20     MA    11
21     MD    17
22     ME    13
23     MI    16
24     MN    15
25     MO     7
26     MS    14
27     MT    14
28     NC    11
29     ND     6
30     NE     5
31     NH     9
32     NJ    18
33     NM     6
34     NV    14
35     NY    15
36     OH    10
37     OK     9
38     OR    11
39     PA     8
40     RI     6
41     SC    14
42     SD     8
43     TN     5
44     TX    18
45     UT    10
46     VA     5
47     VT     8
48     WA    14
49     WI     7
50     WV    10
51     WY     9
</code>```

Basically, I would like to create a barplot showing the value of 3 for AK, 8 for AL, 11 for AR,and so on.

I tried:
barplot(myData)
but I get the error message Error in barplot.default(myData) : 'height' must be a vector or a matrix

Body:
I would like to better visualize a set of data I created in R using the barplot() function. However, I am unsure how to go about this procedure based on 2 columns in a data frame.

name of my data frame: myData

Below is the contents of my data frame:

   States Churn
1      AK     3
2      AL     8
3      AR    11
4      AZ     4
5      CA     9
6      CO     9
7      CT    12
8      DC     5
9      DE     9
10     FL     8
11     GA     8
12     HI     3
13     IA     3
14     ID     9
15     IL     5
16     IN     9
17     KS    13
18     KY     8
19     LA     4
20     MA    11
21     MD    17
22     ME    13
23     MI    16
24     MN    15
25     MO     7
26     MS    14
27     MT    14
28     NC    11
29     ND     6
30     NE     5
31     NH     9
32     NJ    18
33     NM     6
34     NV    14
35     NY    15
36     OH    10
37     OK     9
38     OR    11
39     PA     8
40     RI     6
41     SC    14
42     SD     8
43     TN     5
44     TX    18
45     UT    10
46     VA     5
47     VT     8
48     WA    14
49     WI     7
50     WV    10
51     WY     9

Basically, I would like to create a barplot showing the value of 3 for AK, 8 for AL, 11 for AR,and so on.

I tried:
barplot(myData)
but I get the error message Error in barplot.default(myData) : 'height' must be a vector or a matrix

Body:
If we are passing a single parameter, then it can be a named vector

barplot(setNames(myData$Churn, myData$States))

Or otherwise, it can be a formula method

barplot(Churn ~ States, myData)

data

myData <- structure(list(States = c("AK", "AL", "AR", "AZ", "CA", "CO",
"CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS",
"KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC",
"ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA",
"RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV",
"WY"), Churn = c(3L, 8L, 11L, 4L, 9L, 9L, 12L, 5L, 9L, 8L, 8L,
3L, 3L, 9L, 5L, 9L, 13L, 8L, 4L, 11L, 17L, 13L, 16L, 15L, 7L,
14L, 14L, 11L, 6L, 5L, 9L, 18L, 6L, 14L, 15L, 10L, 9L, 11L, 8L,
6L, 14L, 8L, 5L, 18L, 10L, 5L, 8L, 14L, 7L, 10L, 9L)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51"))


问:
GPOs for User Configuration are not overrided
I've a two GPOs on my domain -> "Default Domain Policy" and "GPO - Diretoria". Default Domain Policy is configured to set proxy settings on all IE browser of the clients (User Config > Policies > Windows Settings > Internet Explorer Maintenance > Connection > Proxy Settings). Here are the detailed config used:

```<code>Internet Explorer Connection
----------------------------
    HTTP Proxy Server:   192.168.100.1:3128
    Secure Proxy Server: 192.168.100.1:3128
    FTP Proxy Server:    192.168.100.1:3128
    Gopher Proxy Server: 192.168.100.1:3128
    Socks Proxy Server:  192.168.100.1:3128
    Auto Config Enable:  No
    Enable Proxy:        Yes
    Use same Proxy:      Yes
</code>```

In the other GPO (GPO - Diretoria) the proxy settings are not configured. The "Enable proxy settings" check box are disabled in Proxy Settings window. This GPO are linked to an OU called Diretoria. Inside this OU, there are 3 computers. When I exec a gpupdate (even gpupdate /force) in any of the 3 computers, the proxy settings still setted as configured in Default Domain Policy!

Then, I´ve performed various tests only with User Configuration Settings and, I´ve noticed (by running gpresult /z) that any User Configuration Setting setted on Default Domain Policy GPO cannot be replaced by the "GPO - Diretoria" User Configuration Settings! BUT, the Computer Configuration Settings are replaced perfectly!

```<code>COMPUTER SETTINGS
------------------
    CN=MARCOS-SUPVM,OU=Diretoria,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:36 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        internal
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        GPO - Diretoria
        Default Domain Policy

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)
.
.
.
.

USER SETTINGS
--------------
    CN=Administrador,CN=Users,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:39 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        INTERNAL
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        Default Domain Policy  <-- SEE HERE??? "GPO - Diretoria" ARE NOT PROCESSED!

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)
</code>```

Why?

答: I think you are confusing user policy and computer policy, the policy you setup is applicable to users in an OU not to computer. Am I wrong ?</p>

Body:
I've a two GPOs on my domain -> "Default Domain Policy" and "GPO - Diretoria". Default Domain Policy is configured to set proxy settings on all IE browser of the clients (User Config > Policies > Windows Settings > Internet Explorer Maintenance > Connection > Proxy Settings). Here are the detailed config used:

Internet Explorer Connection
----------------------------
    HTTP Proxy Server:   192.168.100.1:3128
    Secure Proxy Server: 192.168.100.1:3128
    FTP Proxy Server:    192.168.100.1:3128
    Gopher Proxy Server: 192.168.100.1:3128
    Socks Proxy Server:  192.168.100.1:3128
    Auto Config Enable:  No
    Enable Proxy:        Yes
    Use same Proxy:      Yes

In the other GPO (GPO - Diretoria) the proxy settings are not configured. The "Enable proxy settings" check box are disabled in Proxy Settings window. This GPO are linked to an OU called Diretoria. Inside this OU, there are 3 computers. When I exec a gpupdate (even gpupdate /force) in any of the 3 computers, the proxy settings still setted as configured in Default Domain Policy!

Then, I´ve performed various tests only with User Configuration Settings and, I´ve noticed (by running gpresult /z) that any User Configuration Setting setted on Default Domain Policy GPO cannot be replaced by the "GPO - Diretoria" User Configuration Settings! BUT, the Computer Configuration Settings are replaced perfectly!

COMPUTER SETTINGS
------------------
    CN=MARCOS-SUPVM,OU=Diretoria,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:36 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        internal
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        GPO - Diretoria
        Default Domain Policy

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)
.
.
.
.

USER SETTINGS
--------------
    CN=Administrador,CN=Users,DC=internal,DC=domain,DC=com,DC=br
    Last time Group Policy was applied: 5/16/2011 at 5:31:39 PM
    Group Policy was applied from:      DC4.internal.domain.com.br
    Group Policy slow link threshold:   500 kbps
    Domain Name:                        INTERNAL
    Domain Type:                        Windows 2000

    Applied Group Policy Objects
    -----------------------------
        Default Domain Policy  <-- SEE HERE??? "GPO - Diretoria" ARE NOT PROCESSED!

    The following GPOs were not applied because they were filtered out
    -------------------------------------------------------------------
        Local Group Policy
            Filtering:  Not Applied (Empty)

Why?


问:
Taking screenshot using Swift 5 returns a black image and not the app's screen
I'm trying to take a screenshot of my app and then share it.

The problem I'm having is that when I take a screenshot and save it to the Photos app, the image that gets saved is completely black (and not the screenshot of my app).

How can I get the screenshot to be of my app? What am I missing?

```<code>func takeScreenshot() {
        let bounds = UIScreen.main.bounds
        UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
        self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
        self.present(activityViewController, animated: true, completion: nil)
    }
</code>```

App is a single screen.

Swift 5

xCode 10

I've tried browsing other similar StackOverflow issues and tweaking my code to theirs but getting the same results. Hitting a wall and trying here.

Thanks for any help!

答:
Try changing

```<code> afterScreenUpdates: false
</code>```

To

```<code> afterScreenUpdates: true
</code>```

That way there will be some drawing to snapshot.

Body:
I'm trying to take a screenshot of my app and then share it.

The problem I'm having is that when I take a screenshot and save it to the Photos app, the image that gets saved is completely black (and not the screenshot of my app).

How can I get the screenshot to be of my app? What am I missing?

func takeScreenshot() {
        let bounds = UIScreen.main.bounds
        UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
        self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
        self.present(activityViewController, animated: true, completion: nil)
    }

App is a single screen.

Swift 5

xCode 10

I've tried browsing other similar StackOverflow issues and tweaking my code to theirs but getting the same results. Hitting a wall and trying here.

Thanks for any help!

Body:
Try changing

 afterScreenUpdates: false

To

 afterScreenUpdates: true

That way there will be some drawing to snapshot.


问:
How to enable css modules only for .mod.css files ? Nextjs
There are two kind of styling files i use in my project .css files & .mod.css files. I want to enable CSS modules only for the files whose extension is *.mod.css.

My next.config.js file

```<code>const withCSS = require('@zeit/next-css')

module.exports = withCSS({
      cssModules:true,
      cssLoaderOptions: {
        localIdentName: "[local]_[hash:base64:5]",
      },
      webpack(config, options) {
        config.module.rules.push({
          test: /\.mod.css$/,
        })
        return config
      }
})
</code>```

答:
This was my solution, in next.config.js. It allows use of css modules and global stylesheets, and is customizable.

This takes a file called components/Layout/index.module.scss containing a class called .container and transforms it into the class name Layout__container--cF6H8. Obviously your file structure or needs may be different, but this is flexible and customizable

```<code>const crypto = require('crypto');

...

const nextConfig = {
  cssLoaderOptions: {
    getLocalIdent: (loaderContext, localIdentName, localName, options) => {
      const filePath = loaderContext.resourcePath;
      const fileBaseName = path.basename(filePath);

      if (/\.module\.scss$/.test(fileBaseName)) {
        const modulePathParts = filePath.split('/');

        const moduleName = modulePathParts[modulePathParts.length - 2];

        return `${moduleName}__${localName}--${crypto
          .createHash('sha1')
          .update(filePath)
          .digest('base64')
          .slice(0, 5)}`;
      }

      return localName;
    },

    ...

</code>```

Body:
There are two kind of styling files i use in my project .css files & .mod.css files. I want to enable CSS modules only for the files whose extension is *.mod.css.

My next.config.js file

const withCSS = require('@zeit/next-css')

module.exports = withCSS({
      cssModules:true,
      cssLoaderOptions: {
        localIdentName: "[local]_[hash:base64:5]",
      },
      webpack(config, options) {
        config.module.rules.push({
          test: /\.mod.css$/,
        })
        return config
      }
})

Body:
This was my solution, in next.config.js. It allows use of css modules and global stylesheets, and is customizable.

This takes a file called components/Layout/index.module.scss containing a class called .container and transforms it into the class name Layout__container--cF6H8. Obviously your file structure or needs may be different, but this is flexible and customizable

const crypto = require('crypto');

...

const nextConfig = {
  cssLoaderOptions: {
    getLocalIdent: (loaderContext, localIdentName, localName, options) => {
      const filePath = loaderContext.resourcePath;
      const fileBaseName = path.basename(filePath);

      if (/\.module\.scss$/.test(fileBaseName)) {
        const modulePathParts = filePath.split('/');

        const moduleName = modulePathParts[modulePathParts.length - 2];

        return `${moduleName}__${localName}--${crypto
          .createHash('sha1')
          .update(filePath)
          .digest('base64')
          .slice(0, 5)}`;
      }

      return localName;
    },

    ...


问:
How to show dateTime values on x-axis in Vega Chart with time interval of 5 minutes
I am plotting timestamp values on x-axis in Vega chart. Since the amount of data is huge, it shows tick labels with a gap of 24 hours (or 12 hours) based on tickCount value. Can anyone suggest me how to plot the tick labels with less time interval (For eg. 5 minutes). I tried to increase the range in scales attribute, but it seems to lag a lot to render on the Vega editor.

Link of spec that I'm using in Vega online editor

Also, can anyone tell if plotting labels with lesser time interval is the same thing as zooming in ? Currently it looks like this:

答:
You can increase the number of tick labels by decreasing the distance with</p>

```<code>"tickCount":  {"signal": "ceil(height/20)"}
</code>```

Body:
I am plotting timestamp values on x-axis in Vega chart. Since the amount of data is huge, it shows tick labels with a gap of 24 hours (or 12 hours) based on tickCount value. Can anyone suggest me how to plot the tick labels with less time interval (For eg. 5 minutes). I tried to increase the range in scales attribute, but it seems to lag a lot to render on the Vega editor.

<a href="https://vega.github.io/editor/#[encoded data, 20895 characters]" rel="nofollow noreferrer">Link of spec that I'm using in Vega online editor

Also, can anyone tell if plotting labels with lesser time interval is the same thing as zooming in ? Currently it looks like this:

Body:
You can increase the number of tick labels by decreasing the distance with

"tickCount":  {"signal": "ceil(height/20)"}