问:
Error: LateInitializationError: Field 'sharedPreferences' has not been initialized. Flutter Verygoodcli web app

Error Initializing an already late variable.

In my app there is a composition_root.dart file that composes all the pages. I am migrating code to Flutter 2.10 with a verygoodcli app using verygoodanalysis.

Here is the Composition root:

class CompositionRoot {
  static late SharedPreferences _sharedPreferences;
  static late ILocalStore _localStore;
  static late String _baseUrl;
  static late Client _client;

  static void configure() {
    _localStore = LocalStore(_sharedPreferences);
    _client = Client();
    _baseUrl = 'http://localhost:3000';
  }

  static Widget composeAuthUI() {
    final IAuthApi _api = AuthApi(_baseUrl, _client);
    final _manager = AuthManager(_api);
    final _authCubit = AuthstateCubit(_localStore);
    final _signUpService = SignUpService(_api);

    return BlocProvider(
      create: (BuildContext context) => _authCubit,
      child: AuthPage(_manager, _signUpService),
    );
  }
}

```
<p>However when I run the code, I seem to get the following error message:</p>
<pre class="lang-sh prettyprint-override"><code>
Error: LateInitializationError: Field 'sharedPreferences' has not been
initialized.
    at Object.throw_ [as throw] (http://localhost:40837/dart_sdk.js:5067:11)
    at Function.get sharedPreferences [as sharedPreferences]
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:58
    :37)
    at Function.configure
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:88
    :118)
    at main
    (http://localhost:40837/packages/verygoodapp/main_development.dart.lib.js:45
    :38)
    at main (http://localhost:40837/web_entrypoint.dart.lib.js:36:29)
    at main.next (<anonymous>)

</code>```

How can I debug this errror also do you mind explaining whats going on, I can't seem to understand. The app is configured in the main_*.dart file before the UI is composed.

main_*.dart

void main() {
  CompositionRoot.configure();
  bootstrap(() => const App());
}

```
<p>Our App Widget Class:</p>
<pre class="lang-dart prettyprint-override"><code>class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
        colorScheme: ColorScheme.fromSwatch(
          accentColor: const Color.fromARGB(255, 190, 27, 27),
        ),
      ),
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      home: CompositionRoot.composeAuthUI(),
    );
  }
}

</code>```

I can't seem to understand please help. Thanks in advance.

答:
Just as takudzw-m, answered I was able to instantiate the sharedPreferences in this manner.

  /// This is an async method that instantiates
  /// and configures the static variables and
  /// should not but returns void.
  // ignore: avoid_void_async
  static void configure() async {
    _sharedPreferences = await SharedPreferences.getInstance();
    _localStore = LocalStore(_sharedPreferences);
    _client = Client();
    _baseUrl = 'http://localhost:3000';
  }

```

Thank you StackOverflow Community.

Body:
Error Initializing an already late variable.

In my app there is a composition_root.dart file that composes all the pages. I am migrating code to Flutter 2.10 with a verygoodcli app using verygoodanalysis.

Here is the Composition root:

class CompositionRoot {
  static late SharedPreferences _sharedPreferences;
  static late ILocalStore _localStore;
  static late String _baseUrl;
  static late Client _client;

  static void configure() {
    _localStore = LocalStore(_sharedPreferences);
    _client = Client();
    _baseUrl = 'http://localhost:3000';
  }

  static Widget composeAuthUI() {
    final IAuthApi _api = AuthApi(_baseUrl, _client);
    final _manager = AuthManager(_api);
    final _authCubit = AuthstateCubit(_localStore);
    final _signUpService = SignUpService(_api);

    return BlocProvider(
      create: (BuildContext context) => _authCubit,
      child: AuthPage(_manager, _signUpService),
    );
  }
}

However when I run the code, I seem to get the following error message:

Error: LateInitializationError: Field 'sharedPreferences' has not been
initialized.
    at Object.throw_ [as throw] (http://localhost:40837/dart_sdk.js:5067:11)
    at Function.get sharedPreferences [as sharedPreferences]
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:58
    :37)
    at Function.configure
    (http://localhost:40837/packages/verygoodapp/composition_root.dart.lib.js:88
    :118)
    at main
    (http://localhost:40837/packages/verygoodapp/main_development.dart.lib.js:45
    :38)
    at main (http://localhost:40837/web_entrypoint.dart.lib.js:36:29)
    at main.next (<anonymous>)

How can I debug this errror also do you mind explaining whats going on, I can't seem to understand. The app is configured in the main_*.dart file before the UI is composed.

main_*.dart

void main() {
  CompositionRoot.configure();
  bootstrap(() => const App());
}

Our App Widget Class:

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
        colorScheme: ColorScheme.fromSwatch(
          accentColor: const Color.fromARGB(255, 190, 27, 27),
        ),
      ),
      debugShowCheckedModeBanner: false,
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      home: CompositionRoot.composeAuthUI(),
    );
  }
}

I can't seem to understand please help. Thanks in advance.

Body:
Just as takudzw-m, answered I was able to instantiate the sharedPreferences in this manner.

  /// This is an async method that instantiates
  /// and configures the static variables and
  /// should not but returns void.
  // ignore: avoid_void_async
  static void configure() async {
    _sharedPreferences = await SharedPreferences.getInstance();
    _localStore = LocalStore(_sharedPreferences);
    _client = Client();
    _baseUrl = 'http://localhost:3000';
  }

Thank you StackOverflow Community.


来源: stackexchange

问:
PostgreSQL views on views on views... is this the correct way?
I have a timescaledb receiving data from two families of energy sensors. The update frequency of ones is 5', for the other is 10", with different time offsets. The counters are cumulative, and I am good with the 5' time samples for the aggregated data. The solution I have come with makes use of 5 views: one for each sensor family to get the difference on natural samples, one for the time bucketing, and a final one to outer join both families:

CREATE VIEW sampled_net_energy AS
    SELECT
      time AS "time",
      energy_t1_in + energy_t2_in - lag(energy_t1_in) OVER(ORDER BY time) - lag(energy_t2_in) OVER(ORDER BY time) as net_in,
      energy_t1_out + energy_t2_out - lag(energy_t1_out) OVER(ORDER BY time) - lag(energy_t2_out) OVER(ORDER BY time) as net_out
    FROM electricity
    ORDER BY 1;

CREATE VIEW bucketized_net_energy AS
    SELECT
      time_bucket('5 minutes', time) AS five_min,
      sum(net_in) as bkt_net_in,
      sum(net_out) as bkt_net_out
    FROM sampled_net_energy
    GROUP BY five_min
    ORDER BY 1;

CREATE VIEW sampled_solar_energy AS
    SELECT
      time AS "time",
      pvenergytotal-lag(pvenergytotal) OVER(ORDER BY time) as solar_in
    FROM t040504
    ORDER BY 1;

CREATE VIEW bucketized_solar_energy AS
    SELECT
      time_bucket('5 minutes', time) AS five_min,
      sum(solar_in) as bkt_solar_in
    FROM sampled_solar_energy
    GROUP BY five_min
    ORDER BY 1;

CREATE VIEW energy_balance AS
    SELECT
        a.five_min, bkt_net_in, bkt_net_out, bkt_solar_in
    FROM bucketized_net_energy a
    INNER JOIN bucketized_solar_energy b
    ON a.five_min = b.five_min
    ORDER BY 1;
```

I tried to summarize the two views for each family onto a single one, but seems I cannot use lagged series in aggregation functions (the sum) and my postgresql knowledge does not go further than that.
My question, if there is any postgresql expert in the room is: Is this the correct way to tackle this issue?

UPDATE: by "I cannot user lagged series in aggregation functions" I mean that when I 'select sum(a - lag(a)) as b', I am returned the following error: 'ERROR:  aggregate function calls cannot contain window function calls'.

答:
The solution to your problem is a subquery. If you cannot do

```<code>SELECT sum(a - lag() OVER (...))
FROM ...
GROUP BY ...
</code>```

do this instead:

```<code>SELECT sum(b)
FROM (SELECT a - lag(a) OVER (...) AS b
      FROM ...) AS subq
GROUP BY ...
</code>```

But I want to caution you against defining views on views. There is no technical problem with that, but it makes it very hard to maintain and debug your queries. That is because in the actual queries, all views are resolved, and you end up with a rather complicated query that is hard to understand. In particular, you run the risk of joining extra unnecessary tables, or joining with the same table twice because it occurs in two views. I have repeatedly been asked to tune such queries because the performance was bad, and very often I just have to give up because the Babylonian tower of views is just too much for my simple brain.

ContentLicense: CC BY-SA 4.0

Body:
I have a timescaledb receiving data from two families of energy sensors. The update frequency of ones is 5', for the other is 10", with different time offsets. The counters are cumulative, and I am good with the 5' time samples for the aggregated data. The solution I have come with makes use of 5 views: one for each sensor family to get the difference on natural samples, one for the time bucketing, and a final one to outer join both families:

CREATE VIEW sampled_net_energy AS
    SELECT
      time AS "time",
      energy_t1_in + energy_t2_in - lag(energy_t1_in) OVER(ORDER BY time) - lag(energy_t2_in) OVER(ORDER BY time) as net_in,
      energy_t1_out + energy_t2_out - lag(energy_t1_out) OVER(ORDER BY time) - lag(energy_t2_out) OVER(ORDER BY time) as net_out
    FROM electricity
    ORDER BY 1;

CREATE VIEW bucketized_net_energy AS
    SELECT
      time_bucket('5 minutes', time) AS five_min,
      sum(net_in) as bkt_net_in,
      sum(net_out) as bkt_net_out
    FROM sampled_net_energy
    GROUP BY five_min
    ORDER BY 1;

CREATE VIEW sampled_solar_energy AS
    SELECT
      time AS "time",
      pvenergytotal-lag(pvenergytotal) OVER(ORDER BY time) as solar_in
    FROM t040504
    ORDER BY 1;

CREATE VIEW bucketized_solar_energy AS
    SELECT
      time_bucket('5 minutes', time) AS five_min,
      sum(solar_in) as bkt_solar_in
    FROM sampled_solar_energy
    GROUP BY five_min
    ORDER BY 1;

CREATE VIEW energy_balance AS
    SELECT
        a.five_min, bkt_net_in, bkt_net_out, bkt_solar_in
    FROM bucketized_net_energy a
    INNER JOIN bucketized_solar_energy b
    ON a.five_min = b.five_min
    ORDER BY 1;

I tried to summarize the two views for each family onto a single one, but seems I cannot use lagged series in aggregation functions (the sum) and my postgresql knowledge does not go further than that.
My question, if there is any postgresql expert in the room is: Is this the correct way to tackle this issue?

UPDATE: by "I cannot user lagged series in aggregation functions" I mean that when I 'select sum(a - lag(a)) as b', I am returned the following error: 'ERROR:  aggregate function calls cannot contain window function calls'.

Body:
The solution to your problem is a subquery. If you cannot do

SELECT sum(a - lag() OVER (...))
FROM ...
GROUP BY ...

do this instead:

SELECT sum(b)
FROM (SELECT a - lag(a) OVER (...) AS b
      FROM ...) AS subq
GROUP BY ...

But I want to caution you against defining views on views. There is no technical problem with that, but it makes it very hard to maintain and debug your queries. That is because in the actual queries, all views are resolved, and you end up with a rather complicated query that is hard to understand. In particular, you run the risk of joining extra unnecessary tables, or joining with the same table twice because it occurs in two views. I have repeatedly been asked to tune such queries because the performance was bad, and very often I just have to give up because the Babylonian tower of views is just too much for my simple brain.


问:
.NET error handling
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

```<code>public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}
</code>```

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

答:
You can get the method name and the parameters like this,

```<code>try
{
    int a = 0;
    int i = 1 / a;
}
catch (Exception exception)
{
    StackTrace s = new StackTrace(exception);
    StackFrame stackFrame = s.GetFrame(s.FrameCount - 1);
    if (stackFrame != null)
    {
        StringBuilder stackBuilder = new StringBuilder();
        MethodBase method = stackFrame.GetMethod();
        stackBuilder.AppendFormat("Method Name = {0}{1}Parameters:{1}", method.Name, Environment.NewLine);

        foreach (ParameterInfo parameter in method.GetParameters())
        {
            stackBuilder.AppendFormat("{0} {1}", parameter.ParameterType.FullName, parameter.Name);
            stackBuilder.AppendLine();
        }

        // or use this to get the value
        //stackBuilder.AppendLine("param1  = " + param1);
        //stackBuilder.AppendLine("param2  = " + param2);
    }
}
</code>```

I am not sure whether you can get the parameter values directly off the stack like a debugger.

ContentLicense: CC BY-SA 3.0

Title: .NET error handling

Body:
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

Body:
You can get the method name and the parameters like this,

try
{
    int a = 0;
    int i = 1 / a;
}
catch (Exception exception)
{
    StackTrace s = new StackTrace(exception);
    StackFrame stackFrame = s.GetFrame(s.FrameCount - 1);
    if (stackFrame != null)
    {
        StringBuilder stackBuilder = new StringBuilder();
        MethodBase method = stackFrame.GetMethod();
        stackBuilder.AppendFormat("Method Name = {0}{1}Parameters:{1}", method.Name, Environment.NewLine);

        foreach (ParameterInfo parameter in method.GetParameters())
        {
            stackBuilder.AppendFormat("{0} {1}", parameter.ParameterType.FullName, parameter.Name);
            stackBuilder.AppendLine();
        }

        // or use this to get the value
        //stackBuilder.AppendLine("param1  = " + param1);
        //stackBuilder.AppendLine("param2  = " + param2);
    }
}

I am not sure whether you can get the parameter values directly off the stack like a debugger.


问:
Should constructor call init or vice versa?
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?

init/open calls constructor:

```<code>struct S {
  S(params...) : initlist... {
    ... init code ...
  }
  void init(params...) {
    *this = S(params...);
  }
  ...
};
</code>```

Constructor calls init/open:

```<code>struct S {
  S(params...) {
    init(params...);
  }
  void init(params...) {
    ... init code ...
  }
  ...
};
</code>```

Think for example a class representing a file, that can have the path passed to the constructor or  call an open() method later.

答:
You might use different constructors: one with no parameters (that sets empty/default values) and one with the parameters you need. You can implement the Init method as a standalone private method called by the second constructor, or as body of the second constructor, depending on your taste.

```<code>struct S {
  /* Default / empty constructor */
  S() {
    // Code for the default / empty constructor
  }

  /* Parameters constructor */
  S(param1, param2, ...)
    // Init code here or call to Init function
  }

  // Init method code, if separated from constructor
};
</code>```

This is quite clean, as a programmer will search for a constructor by default, and not for any other initialization method.
If the code of the 2 constructors is not conflicting, and if you're using C++11 as i guess, you could also do something like:

```<code>struct S {
  /* Default / empty constructor */
  S() {
    // Code for the default / empty constructor
  }

  /* Parameters constructor */
  S(param1, param2, ...): S() // calls empty constructor first
    // Init code here or call to Init function
  }

  // Init method code, if separated from constructor
};
</code>```

where the second contructor calls the fist one before executing its init procedures

Body:
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?

init/open calls constructor:

struct S {
  S(params...) : initlist... {
    ... init code ...
  }
  void init(params...) {
    *this = S(params...);
  }
  ...
};

Constructor calls init/open:

struct S {
  S(params...) {
    init(params...);
  }
  void init(params...) {
    ... init code ...
  }
  ...
};

Think for example a class representing a file, that can have the path passed to the constructor or  call an open() method later.

Body:
You might use different constructors: one with no parameters (that sets empty/default values) and one with the parameters you need. You can implement the Init method as a standalone private method called by the second constructor, or as body of the second constructor, depending on your taste.

struct S {
  /* Default / empty constructor */
  S() {
    // Code for the default / empty constructor
  }

  /* Parameters constructor */
  S(param1, param2, ...)
    // Init code here or call to Init function
  }

  // Init method code, if separated from constructor
};

This is quite clean, as a programmer will search for a constructor by default, and not for any other initialization method.
If the code of the 2 constructors is not conflicting, and if you're using C++11 as i guess, you could also do something like:

struct S {
  /* Default / empty constructor */
  S() {
    // Code for the default / empty constructor
  }

  /* Parameters constructor */
  S(param1, param2, ...): S() // calls empty constructor first
    // Init code here or call to Init function
  }

  // Init method code, if separated from constructor
};

where the second contructor calls the fist one before executing its init procedures


问:
FileReader only reads the first two lines of TXT
I try to write a java program to read the user's input text and check the inputted text whether is duplicate or not. But I encounter a problem, FileReader only read the first two line of the specific TXT.
I've asked others for help, but they cannot figure out what's wrong! can anyone help me? THX!

PS If I type theodora, it will return the correct output. However if I type sophia, the other name in the txt file, it will return "Contact doesn't exist"

enter image description here

```<code>    Scanner fr1 = new Scanner (listFile);
    System.out.print ("Enter a contact name: ");

    inName = keyboard.nextLine ();

    if (!fr1.hasNext()){
        System.out.print ("Contact doesn't exist");
    }else{
        while (true){
            String strName = fr1.next();
            String strPhone = fr1.next();
            if (strName.equals(inName.trim())){
                System.out.print ("Contact name: " + strName+", Phone number: " + strPhone);
                keyboard.nextLine ();
                break;
            }else{
                System.out.print ("Contact doesn't exist");
                break;
            }
        }
    }fr1.close();
</code>```

答:
Hi You can use List to store all the data from txt and then fetch the data out of it

```<code>{
    File file = new File(
            "\\Desktop\\test.txt");

    BufferedReader br
            = new BufferedReader(new FileReader(file));

    String st;

    List contactList = new ArrayList();
    while ((st = br.readLine()) != null)
        contactList.add(st);

    if(contactList.contains("Mona")){
        int index = contactList.indexOf("Mona");
        System.out.print ("Contact name: " + contactList.get(index)+", Phone number: " + contactList.get(index+1));
    }
}
</code>```

My txt contains :
Tupan
123456
Mona
87546
Zen
97679

And output i am getting is
Contact name: Mona, Phone number: 87546

Body:
I try to write a java program to read the user's input text and check the inputted text whether is duplicate or not. But I encounter a problem, FileReader only read the first two line of the specific TXT.
I've asked others for help, but they cannot figure out what's wrong! can anyone help me? THX!

PS If I type theodora, it will return the correct output. However if I type sophia, the other name in the txt file, it will return "Contact doesn't exist"

enter image description here

    Scanner fr1 = new Scanner (listFile);
    System.out.print ("Enter a contact name: ");

    inName = keyboard.nextLine ();

    if (!fr1.hasNext()){
        System.out.print ("Contact doesn't exist");
    }else{
        while (true){
            String strName = fr1.next();
            String strPhone = fr1.next();
            if (strName.equals(inName.trim())){
                System.out.print ("Contact name: " + strName+", Phone number: " + strPhone);
                keyboard.nextLine ();
                break;
            }else{
                System.out.print ("Contact doesn't exist");
                break;
            }
        }
    }fr1.close();

Body:
Hi You can use List to store all the data from txt and then fetch the data out of it

{
    File file = new File(
            "\\Desktop\\test.txt");

    BufferedReader br
            = new BufferedReader(new FileReader(file));

    String st;

    List contactList = new ArrayList();
    while ((st = br.readLine()) != null)
        contactList.add(st);

    if(contactList.contains("Mona")){
        int index = contactList.indexOf("Mona");
        System.out.print ("Contact name: " + contactList.get(index)+", Phone number: " + contactList.get(index+1));
    }
}

My txt contains :
Tupan
123456
Mona
87546
Zen
97679

And output i am getting is
Contact name: Mona, Phone number: 87546


问:
importing go files in same folder
I am having difficulty in importing a local go file into another go file.

My project structure is like something below

```<code>-samplego
--pkg
--src
---github.com
----xxxx
-----a.go
-----b.go
--bin
</code>```

I am trying to import a.go inside b.go. I tried the following,

```<code>import "a"
import "github.com/xxxx/a"
</code>```

None of these worked..I understand I have to meddle up with GOPATH but I couldn't get it right. Presently my GOPATH is pointing to samplego(/workspace/samplego).I get the below error

```<code>cannot find package "a" in any of:
/usr/local/go/src/pkg/a (from $GOROOT)
/workspace/samplego/src/a (from $GOPATH)
</code>```

Also, how does GOPATH work when these source files are imported into another project/module? Would the local imports be an issue then? What is the best practice in this case - is it to have just one go file in module(with associated tests)?

答:
As I understand for packages in your project subfolders it's possible now to do, just need to add "." in front of module, like
. "github.com/ilyasf/deadlock-train/common"
where github.com/ilyasf/deadlock-train my main module name and common is just package from /common subfolder inside project.

Title: importing go files in same folder

Body:
I am having difficulty in importing a local go file into another go file.

My project structure is like something below

-samplego
--pkg
--src
---github.com
----xxxx
-----a.go
-----b.go
--bin

I am trying to import a.go inside b.go. I tried the following,

import "a"
import "github.com/xxxx/a"

None of these worked..I understand I have to meddle up with GOPATH but I couldn't get it right. Presently my GOPATH is pointing to samplego(/workspace/samplego).I get the below error

cannot find package "a" in any of:
/usr/local/go/src/pkg/a (from $GOROOT)
/workspace/samplego/src/a (from $GOPATH)

Also, how does GOPATH work when these source files are imported into another project/module? Would the local imports be an issue then? What is the best practice in this case - is it to have just one go file in module(with associated tests)?


问:
Error "Could not find PyAudio; check installation" on Windows
I have simple code in python to recognise my voice and convert it in text. I am using speech recognition.

But I am getting error "Could not find PyAudio; check installation". How to fix?

Here is my code:

```<code>import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone() as source:
    print('Speak anything')
    audio = r.listen(source)

    try:
        global command
        command = r.recognize_google(audio)
        print('You said : {}'.format(text))
    except:
        print('Sorry,coud not recognize')
</code>```

答:
even i faced py-audio error so you can install py-audio with the help of unofficial libraries  install it with the help of powershell in windows
python unoffical libraries</p>

Body:
I have simple code in python to recognise my voice and convert it in text. I am using speech recognition.

But I am getting error "Could not find PyAudio; check installation". How to fix?

Here is my code:

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone() as source:
    print('Speak anything')
    audio = r.listen(source)

    try:
        global command
        command = r.recognize_google(audio)
        print('You said : {}'.format(text))
    except:
        print('Sorry,coud not recognize')


问:
RangeError (index): Invalid value: Valid value range is empty: 1 , for videoplayer widget
In this shouldn't the valid range be 1 as at index 0 I have placed a button and at index 1 it's the video file. I tried other variations but I am not sure where the error persists as it's giving the same error for [index-1], [index], [index + 1] .

Add video class:

```<code>class _addVideoState extends State<addVideo> {
  bool uploading = false;
  double val = 0;
  CollectionReference? vidRef;
  firebase_storage.Reference? ref;
  File? video;
  VideoPlayerController? videoPlayerController;
  VideoPlayerController? INvideoPlayerController;

  List<File> _video = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add video'),
        actions: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                uploading = true;
              });

              uploadFile().whenComplete(() => Navigator.of(context).pop());
            },
            child: Text(
              'Upload Video',
              style: TextStyle(color: Colors.red),
            ),
          )
        ],
      ),
      body: ListView.builder(
          itemCount: _video.length + 1,
          itemBuilder: (ctx, index) {
            INvideoPlayerController = VideoPlayerController.file(
                _video[index + 1])
              ..setLooping(true)
              ..initialize().then((value) => INvideoPlayerController!.play());
            return index == 0
                ? Center(
                    child: ElevatedButton(
                        onPressed: () {
                          !uploading ? chooseVideo() : null;
                          print(_video);
                        },
                        child: const Text(
                          'Test',
                          style: TextStyle(color: Colors.black),
                        )),
                  )
                : AspectRatio(
                    aspectRatio: INvideoPlayerController!.value.aspectRatio,
                    child: VideoPlayer(INvideoPlayerController!),
                  );

          }),
    );
  }
</code>```

chooseVideo(this is where I am adding to my list):

```<code>chooseVideo() async {
    ImagePicker picker = ImagePicker();

    final pickedFile = await picker.pickVideo(source: ImageSource.gallery);

    setState(() {
      _video.add(File(pickedFile!.path));
    });
    videoPlayerController = VideoPlayerController.file(File(pickedFile!.path))
      ..addListener(() => setState(() {

          }))
      ..setLooping(true)
      ..initialize().then((_) {

        videoPlayerController!.play();
      });
    print(pickedFile.path);
    print(File(pickedFile.path));
    print('Kavya-choosevideo-videoPlayerController :   $videoPlayerController');
    if (pickedFile.path == null) retrieveLostData();
  }
</code>```

答:
On the first build of the widget your _video list is empty but you are forcing an

itemCount: _video.length + 1
```
<p>in your ListView, so you are forcing one item to be added to your ListView and immediately giving it the video file value of</p>
<pre class="lang-dart prettyprint-override"><code>_video[index + 1]
</code>```

It's important to note here that your are not assigning a value to _video but you are requesting the array item at index index + 1 which does not exist. At this point there is no items in this array and I don't see any code that added to it, so please add it to your answer if you have it, if not you need to populate the array before you can use it.

In any case, you need to add an if statement that displays another widget when the _video list is empty

if(_video.isEmpty)
// Show another widget
else
// Display video player
```

Body:
In this shouldn't the valid range be 1 as at index 0 I have placed a button and at index 1 it's the video file. I tried other variations but I am not sure where the error persists as it's giving the same error for [index-1], [index], [index + 1] .

Add video class:

class _addVideoState extends State<addVideo> {
  bool uploading = false;
  double val = 0;
  CollectionReference? vidRef;
  firebase_storage.Reference? ref;
  File? video;
  VideoPlayerController? videoPlayerController;
  VideoPlayerController? INvideoPlayerController;

  List<File> _video = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add video'),
        actions: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                uploading = true;
              });

              uploadFile().whenComplete(() => Navigator.of(context).pop());
            },
            child: Text(
              'Upload Video',
              style: TextStyle(color: Colors.red),
            ),
          )
        ],
      ),
      body: ListView.builder(
          itemCount: _video.length + 1,
          itemBuilder: (ctx, index) {
            INvideoPlayerController = VideoPlayerController.file(
                _video[index + 1])
              ..setLooping(true)
              ..initialize().then((value) => INvideoPlayerController!.play());
            return index == 0
                ? Center(
                    child: ElevatedButton(
                        onPressed: () {
                          !uploading ? chooseVideo() : null;
                          print(_video);
                        },
                        child: const Text(
                          'Test',
                          style: TextStyle(color: Colors.black),
                        )),
                  )
                : AspectRatio(
                    aspectRatio: INvideoPlayerController!.value.aspectRatio,
                    child: VideoPlayer(INvideoPlayerController!),
                  );

          }),
    );
  }

chooseVideo(this is where I am adding to my list):

chooseVideo() async {
    ImagePicker picker = ImagePicker();

    final pickedFile = await picker.pickVideo(source: ImageSource.gallery);

    setState(() {
      _video.add(File(pickedFile!.path));
    });
    videoPlayerController = VideoPlayerController.file(File(pickedFile!.path))
      ..addListener(() => setState(() {

          }))
      ..setLooping(true)
      ..initialize().then((_) {

        videoPlayerController!.play();
      });
    print(pickedFile.path);
    print(File(pickedFile.path));
    print('Kavya-choosevideo-videoPlayerController :   $videoPlayerController');
    if (pickedFile.path == null) retrieveLostData();
  }

Body:
On the first build of the widget your _video list is empty but you are forcing an

itemCount: _video.length + 1

in your ListView, so you are forcing one item to be added to your ListView and immediately giving it the video file value of

_video[index + 1]

It's important to note here that your are not assigning a value to _video but you are requesting the array item at index index + 1 which does not exist. At this point there is no items in this array and I don't see any code that added to it, so please add it to your answer if you have it, if not you need to populate the array before you can use it.

In any case, you need to add an if statement that displays another widget when the _video list is empty

if(_video.isEmpty)
// Show another widget
else
// Display video player


问:
React.js : How to start a react application on a different port
I just have started learning React.js and made two projects using Create React App.

Now if I want to start both projects at the same time, I can't because both start on port 3000 by default.

Is there any way I can change the default port of one of them to something else like http://localhost:3001 and run them simultaneously?

Note: I'm a Windows user

答:
Modify start command from scripts section of package.json.

```<code>"start": “set PORT=3005 && react-scripts start"
</code>```

There are couple of other ways also.
Refer this link
https://tech.amikelive.com/node-830/reactjs-changing-default-port-3000-in-create-react-app/

PS:
You can specify the port number which you want.

Body:
Modify start command from scripts section of package.json.

"start": “set PORT=3005 && react-scripts start"

There are couple of other ways also.
Refer this link
https://tech.amikelive.com/node-830/reactjs-changing-default-port-3000-in-create-react-app/

PS:
You can specify the port number which you want.


问:
How do I check the versions of Python modules?
I installed the Python modules construct and statlib using setuptools:

```<code>sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct
</code>```

How do I check their versions from the command line?

答:
For situations where field __version__ is not defined:

try:
    from importlib import metadata
except ImportError:
    import importlib_metadata as metadata # python<=3.7

metadata.version("package")
```
<p>Alternatively, and like it was already mentioned:</p>
<pre class="lang-py prettyprint-override"><code>import pkg_resources
pkg_resources.get_distribution('package').version
</code>```

Body:
I installed the Python modules construct and statlib using setuptools:

sudo apt-get install python-setuptools

sudo easy_install statlib
sudo easy_install construct

How do I check their versions from the command line?

Body:
For situations where field __version__ is not defined:

try:
    from importlib import metadata
except ImportError:
    import importlib_metadata as metadata # python<=3.7

metadata.version("package")

Alternatively, and like it was already mentioned:

import pkg_resources
pkg_resources.get_distribution('package').version


问:
What is the phase spectrum and why does it have values for the given graph of a simple sine function
I understand the first 2 graphs, the time domain representation and the frequency domain representation (amplitude spectrum) but I cannot wrap my head around the phase spectrum. Why does it contain a value at f = 100? Is it linked with the bandwidth of the system?

答: The phase plot is just showing that the phase of the associated sine wave at that frequency is -pi/2.  This results from the Fourier transform of a sine wave bing two components, one at positive and one at negative frequency, one with a phase to +90 degrees (pi/2) and the other with a phase of -90 degrees (-pi/2).  See The Fourier Transform of the Sine and Cosine Functions for more details</p>


问:
trying to make a bot that counts members in a voice channel
Please don't comment if think that what I'm asking is stupid.
I am completely new to this. I tried searching up solutions but couldn't find helpful ones or ones that a noob in discord.js would understand. Thank you for your help in advance!

const express = require ("express")
var app = require('express')();

app.get("/", (req, res) => {
  res.send("hello hell!")
})

app.listen(3000, () => {
  console.log("Project is ready")
})

let Discord = require("discord.js")
let client = new Discord.Client()

client.on('voiceStateUpdate', (oldVoiceState, newVoiceState) => {

let newUserChannel = newVoiceState.voiceChannel

let oldUserChannel = oldVoiceState.voiceChannel

if(oldUserChannel === undefined && newUserChannel !== undefined) {

// User Joins a voice channel
console.log(client.voiceConnections.size)

} else if(newUserChannel === undefined){

// User leaves a voice channel

console.log(client.voiceConnections.size)

}

})

client.login("token")

```
<p>repl.it
outcome when someone joins
Project is ready</p>
```console.log(client.voiceConnections.size)
                                    ^

TypeError: Cannot read property 'size' of undefined
    at Client.<anonymous> (/home/runner/VCC-Bot/index.js:30:37)
    at Client.emit (events.js:315:20)
    at Client.EventEmitter.emit (domain.js:483:12)
    at VoiceStateUpdate.handle (/home/runner/VCC-Bot/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:40:14)
    at Object.module.exports [as VOICE_STATE_UPDATE] (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
    at WebSocketManager.handlePacket (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/VCC-Bot/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:315:20)
```

答:
Not sure if i'm too late here, but you need to give the bot the intent to it.
You can add the intent like this:</p>
```<code>const { Client, Intents } = require("discord.js");

const client = new Client({
    intents: [Intents.FLAGS.GUILD_VOICE_STATES],
});
</code>```

Body:
Please don't comment if think that what I'm asking is stupid.
I am completely new to this. I tried searching up solutions but couldn't find helpful ones or ones that a noob in discord.js would understand. Thank you for your help in advance!

const express = require ("express")
var app = require('express')();

app.get("/", (req, res) => {
  res.send("hello hell!")
})

app.listen(3000, () => {
  console.log("Project is ready")
})

let Discord = require("discord.js")
let client = new Discord.Client()

client.on('voiceStateUpdate', (oldVoiceState, newVoiceState) => {

let newUserChannel = newVoiceState.voiceChannel

let oldUserChannel = oldVoiceState.voiceChannel

if(oldUserChannel === undefined && newUserChannel !== undefined) {

// User Joins a voice channel
console.log(client.voiceConnections.size)

} else if(newUserChannel === undefined){

// User leaves a voice channel

console.log(client.voiceConnections.size)

}

})

client.login("token")

repl.it
outcome when someone joins
Project is ready

console.log(client.voiceConnections.size)
                                    ^

TypeError: Cannot read property 'size' of undefined
    at Client.<anonymous> (/home/runner/VCC-Bot/index.js:30:37)
    at Client.emit (events.js:315:20)
    at Client.EventEmitter.emit (domain.js:483:12)
    at VoiceStateUpdate.handle (/home/runner/VCC-Bot/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:40:14)
    at Object.module.exports [as VOICE_STATE_UPDATE] (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
    at WebSocketManager.handlePacket (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/VCC-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/VCC-Bot/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:315:20)

Body:
Not sure if i'm too late here, but you need to give the bot the intent to it.
You can add the intent like this:

const { Client, Intents } = require("discord.js");

const client = new Client({
    intents: [Intents.FLAGS.GUILD_VOICE_STATES],
});


问:
The gap still keeps 100% in running Gurobi model
I am solving a mixed-integer linear programming model on Python platform using the solver Gurobi. However, The gap of the model still keeps 100 % during the long-running time.
I am trying to use the codes to limit the running time. The solution is found, but I don't know why the gap in the model doesn't reduce.
I have attached the file below.
Could you help me to fix this problem?
Thank you very much!

答: You could also add a small objective offset to enforce a non-zero dual bound. This will enable a more expressive gap. You could use the ObjCon model attribute to achieve this.</p>


问:
R: Extra-space in label position. gplots - VennDiagram - venn.diagramm()
I'm facing this little layout problem here with this 3-vector list venn diagram. I specified cat.pos = c(0, 0, 0), cat.dist = c(0.1, 0.1, 0.1) to have all 3 labels at noon above their respective area and at the same distance but I got the 3rd 1 step more above..
It is also farther when no cat.dist vector is passed to the function.

```<code># Get gene lists to do Venn diagram
ids_3883_pvsUNR <- c(paste0("gene",c(1:66)))
ids_3883_pvsCRSP <- c(paste0("gene",c(67:126)))
ids_3884 <- c(paste0("gene",c(1:30,67:85,1001:4054)))

head(ids_3883_pvsUNR)

length(ids_3883_pvsUNR)
length(ids_3883_pvsCRSP)
length(ids_3884)

#
geneLS <- list(ids_3883_pvsUNR, ids_3883_pvsCRSP, ids_3884)
# We can rename our list vectors
names(geneLS) <- c("Set_1_3883_pvsUNR","Set_1_3883_pvsCRSP", "Set_2_3884RUV")

# Now we can plot a Venn diagram with the VennDiagram R package, as follows:
require("VennDiagram")

VENN.LIST <- geneLS
labels <- c("Set_1_3883\nPat 1,2 vs UNR","Set_1_3883\nPat 1,2 vs 3 CRSP", "Set_2_3884RUV\nPat 3 vs 3 CRSP")
venn.plot <- venn.diagram(VENN.LIST , NULL, fill=c("darkmagenta", "darkblue", "grey"), alpha=c(0.5,0.5,0.5), cex = 2, cat.fontface=4, cat.pos = c(0, 0, 0), cat.dist = c(0.1, 0.1, 0.1), category.names=labels, main="Set_1_May_3883 (P vs UNR or CRSP) vs Set_2_May_3884_RUVcorrected")

# To plot the venn diagram we will use the grid.draw() function to plot the venn diagram
dev.off()
grid.draw(venn.plot)
</code>```

Does somebody know what is happening here?
Thanks for your feedback!
Daniel

<img src="https://i.stack.imgur.com/iwLx3.png" alt="extra space in label 3 <-> area despite same distance given in parameters" />

答:
Try the functions of the ggVennDiagram or ggvenn package.
Here are the data

```<code>genes <- paste("gene",1:3180,sep="")
x <- list(
  `Set_1_3883\n Pat 1,2 vs UNR` = genes[1:66],
  `Set_1_3883\n Pat 1,2 vs 3 CRSP` = genes[37:3139],
  `Set_2_3884RUV\n Pat 3 vs 3 CRSP` = genes[3121:3180]
)
</code>```

And now the graph

```<code>library(ggVennDiagram)
ggVennDiagram(x, label_alpha = 0)+
  scale_fill_gradient(low="gray",high = "blue")

</code>```

And with the ggvenn package

```<code>library(ggvenn)
ggvenn(
  x,
  fill_color = c("plum1", "blueviolet", "gray"),
  stroke_size = 0.5, set_name_size = 4
)
</code>```

In both cases they are ggplots so you will have much better control over them.

Body:
I'm facing this little layout problem here with this 3-vector list venn diagram. I specified cat.pos = c(0, 0, 0), cat.dist = c(0.1, 0.1, 0.1) to have all 3 labels at noon above their respective area and at the same distance but I got the 3rd 1 step more above..
It is also farther when no cat.dist vector is passed to the function.

# Get gene lists to do Venn diagram
ids_3883_pvsUNR <- c(paste0("gene",c(1:66)))
ids_3883_pvsCRSP <- c(paste0("gene",c(67:126)))
ids_3884 <- c(paste0("gene",c(1:30,67:85,1001:4054)))

head(ids_3883_pvsUNR)

length(ids_3883_pvsUNR)
length(ids_3883_pvsCRSP)
length(ids_3884)

#
geneLS <- list(ids_3883_pvsUNR, ids_3883_pvsCRSP, ids_3884)
# We can rename our list vectors
names(geneLS) <- c("Set_1_3883_pvsUNR","Set_1_3883_pvsCRSP", "Set_2_3884RUV")

# Now we can plot a Venn diagram with the VennDiagram R package, as follows:
require("VennDiagram")

VENN.LIST <- geneLS
labels <- c("Set_1_3883\nPat 1,2 vs UNR","Set_1_3883\nPat 1,2 vs 3 CRSP", "Set_2_3884RUV\nPat 3 vs 3 CRSP")
venn.plot <- venn.diagram(VENN.LIST , NULL, fill=c("darkmagenta", "darkblue", "grey"), alpha=c(0.5,0.5,0.5), cex = 2, cat.fontface=4, cat.pos = c(0, 0, 0), cat.dist = c(0.1, 0.1, 0.1), category.names=labels, main="Set_1_May_3883 (P vs UNR or CRSP) vs Set_2_May_3884_RUVcorrected")

# To plot the venn diagram we will use the grid.draw() function to plot the venn diagram
dev.off()
grid.draw(venn.plot)

Does somebody know what is happening here?
Thanks for your feedback!
Daniel

<img src="https://i.stack.imgur.com/iwLx3.png" alt="extra space in label 3 <-> area despite same distance given in parameters" />

Body:
Try the functions of the ggVennDiagram or ggvenn package.
Here are the data

genes <- paste("gene",1:3180,sep="")
x <- list(
  `Set_1_3883\n Pat 1,2 vs UNR` = genes[1:66],
  `Set_1_3883\n Pat 1,2 vs 3 CRSP` = genes[37:3139],
  `Set_2_3884RUV\n Pat 3 vs 3 CRSP` = genes[3121:3180]
)

And now the graph

library(ggVennDiagram)
ggVennDiagram(x, label_alpha = 0)+
  scale_fill_gradient(low="gray",high = "blue")

And with the ggvenn package

library(ggvenn)
ggvenn(
  x,
  fill_color = c("plum1", "blueviolet", "gray"),
  stroke_size = 0.5, set_name_size = 4
)

In both cases they are ggplots so you will have much better control over them.


问:
getting last three lines of python output assigned to 3 variables in bash
I have a python script that outputs a long list of files.

The script is ran from bash, and at the end i need to assign the last three files each to a specific variables.

I'm able to capture the output into a bash Variable, but then when I try to pipe it to 'tail' command, it seems to be one line only?

I've tried tips i've seen around, but can't seem to figure out how to work on an individual line basis with output.

it seems that any python output will be interpreted as one line?

echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(i)")

# check output
echo "$OUTPUT"

variable3=$(echo $OUTPUT | tail -1)

echo "VARIABLE CAPTURED"
echo $variable3
```
<p>here is what i get:
<img src="https://i.stack.imgur.com/giove.png" alt="enter image description here" /></p>
<p>But I actually need to capture variable1 as 3rd line from end, variable2 as 2nd line from end and variable3 as first line from the end</p>
<p>So that in the above example at the end the desired result is:</p>
```variable1 = 2
variable2 = 3
variable3 = 4
```

in order to pass these variables to next stage of the script...

答:
When you don't need your current environment, you can use set.

When you want to use the the variable names variable# you need to copy them.

```<code>set -- $( python -c "for i in range(5): print(i)"| tail -3)
variable1="$1"; variable2="$2"; variable3="$3"
# In my environment I can check the results with
set | grep "^variable.="
</code>```

An other option is reading them into the variables:

```<code>read -rd "\n" variable1 variable2 variable3 < <(
  python -c "for i in range(5): print(i)"| tail -3
)
</code>```

Body:
I have a python script that outputs a long list of files.

The script is ran from bash, and at the end i need to assign the last three files each to a specific variables.

I'm able to capture the output into a bash Variable, but then when I try to pipe it to 'tail' command, it seems to be one line only?

I've tried tips i've seen around, but can't seem to figure out how to work on an individual line basis with output.

it seems that any python output will be interpreted as one line?

echo "TESTING sample multi-line python output"
OUTPUT=$(python -c "for i in range(5): print(i)")

# check output
echo "$OUTPUT"

variable3=$(echo $OUTPUT | tail -1)

echo "VARIABLE CAPTURED"
echo $variable3

here is what i get:

But I actually need to capture variable1 as 3rd line from end, variable2 as 2nd line from end and variable3 as first line from the end

So that in the above example at the end the desired result is:

variable1 = 2
variable2 = 3
variable3 = 4

in order to pass these variables to next stage of the script...

Body:
When you don't need your current environment, you can use set.

When you want to use the the variable names variable# you need to copy them.

set -- $( python -c "for i in range(5): print(i)"| tail -3)
variable1="$1"; variable2="$2"; variable3="$3"
# In my environment I can check the results with
set | grep "^variable.="

An other option is reading them into the variables:

read -rd "\n" variable1 variable2 variable3 < <(
  python -c "for i in range(5): print(i)"| tail -3
)


问:
Using variables and functions in other fileis Node js
I have two separate files and I want to use functions and variables in my first file in another file.
What I mean is, here is the content of my first file:

```<code>const db = mongoose.connection;
</code>```

and in my second file I need to for example log it:

```<code>console.log(db)
</code>```

I used export and import but it did not work:

```<code>export const db = mongoose.connection;

import db from (./db.js)
console.log(db)
</code>```

I got this error:
SyntaxError: Cannot use import statement outside a module

答:
in node js (or modern another js platforms) you can use modules.

in node js. you have 2 choice.

1: common js (CJS) modules:

```<code>in a way, nodeJS based on CJS. and CJS modules builtin available in node.

you can imort a CJS module with this code :

const module = required("module file widout .js");
</code>```

and for create modules (in your module file) :

```<code>module.export = {your code};
</code>```

2 ES6 modules :

```<code>es6 is a newer version of JS and that supports modules defaultly.
</code>```

use module :

your example :) (in question post) :

```<code>from module import a;
console.log(a); //1
</code>```

create module :

```<code>export a = 1
</code>```

very important for ES6 modules: you should be use a js compiler, like babel to compile es6-21 to es5 nodeJS and browsers (i dont know other platforms) does not support es6 or above JS versions.

Body:
I have two separate files and I want to use functions and variables in my first file in another file.
What I mean is, here is the content of my first file:

const db = mongoose.connection;

and in my second file I need to for example log it:

console.log(db)

I used export and import but it did not work:

export const db = mongoose.connection;

import db from (./db.js)
console.log(db)

I got this error:
SyntaxError: Cannot use import statement outside a module

Body:
in node js (or modern another js platforms) you can use modules.

in node js. you have 2 choice.

1: common js (CJS) modules:

in a way, nodeJS based on CJS. and CJS modules builtin available in node.

you can imort a CJS module with this code :

const module = required("module file widout .js");

and for create modules (in your module file) :

module.export = {your code};

2 ES6 modules :

es6 is a newer version of JS and that supports modules defaultly.

use module :

your example :) (in question post) :

from module import a;
console.log(a); //1

create module :

export a = 1

very important for ES6 modules: you should be use a js compiler, like babel to compile es6-21 to es5 nodeJS and browsers (i dont know other platforms) does not support es6 or above JS versions.


问:
running python in low resolution in macOS Monterey
how can I run python.app in low resolution in macOS Monterey?

there used to be a checkbox in the app's info, but it is missing from Monterey, is there any way I could fix that?

答: Yes, Apple is no longer supporting "Low Resolution Mode". But There's a trick to open application in Low Resolution Mode. You need to Edit  info.plist of python.app and change the key NSHighResolutionCapable to false.


问:
Doesn't work stdout.write Method but can work stdout.writeln
```<code>import 'dart:io'
void main(){
stdout.write("abc");}
</code>```

that code doesn't worked but

```<code>void main(){
stdout.writeln("abc");}
</code>```

was work!! output is "abc" and

```<code>void main(){
stdout.write("abc");
stdout.writeln("def");}
</code>```

out put is "abcdef"
I can't understand this happend...

答:
Both write and writeln are non-blocking, with the difference that writeln is causing the buffer to be flushed. Your first code would work if you await a flush before ending your program:

```<code>import 'dart:io'

void main() async {
    stdout.write("abc");
    await stdout.flush();
}
</code>```

Body:
import 'dart:io'
void main(){
stdout.write("abc");}

that code doesn't worked but

void main(){
stdout.writeln("abc");}

was work!! output is "abc" and

void main(){
stdout.write("abc");
stdout.writeln("def");}

out put is "abcdef"
I can't understand this happend...

Body:
Both write and writeln are non-blocking, with the difference that writeln is causing the buffer to be flushed. Your first code would work if you await a flush before ending your program:

import 'dart:io'

void main() async {
    stdout.write("abc");
    await stdout.flush();
}


问:
Parametrizing base image version in Dockerfile of Docker container Github action
I am following "Creating a Docker container action" and everything works great for me except that I would like to parametrize FROM field in my Dockerfile (I need to run CI tests against different versions of dependency, packaged as Docker image).

Ideally, in my Dockerfile, I'd like to use ARG or something something similar to:

```<code>ARG version=latest

FROM alpine:${version}

...
</code>```

... but it is unclear how to pass build args.

Is there a way to something like this?

答:
I have not found a good way to do this out of the box.

At the moment Docker container action
won't even let you to specify Dockerfile using arguments (through runs.image in action.yml).

The solution for me was using this action.

Body:
I am following "Creating a Docker container action" and everything works great for me except that I would like to parametrize FROM field in my Dockerfile (I need to run CI tests against different versions of dependency, packaged as Docker image).

Ideally, in my Dockerfile, I'd like to use ARG or something something similar to:

ARG version=latest

FROM alpine:${version}

...

... but it is unclear how to pass build args.

Is there a way to something like this?


问:
Inheritance problem in C#
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

```<code>public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
</code>```

ISvdPredictor uses ISvdModel:

```<code>public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}
</code>```

Now I want to implement another variation:

```<code>public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
</code>```

Which uses IBiasSvdModel which derives from ISvdModel:

```<code>public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}
</code>```

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

答: You can use explicit interface implementation to hide the ones from ISvdPredictor, but you should implement them all or have a base abstract class to handle them.

Title: Inheritance problem in C#

Body:
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}

ISvdPredictor uses ISvdModel:

public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

Now I want to implement another variation:

public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}

Which uses IBiasSvdModel which derives from ISvdModel:

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.


问:
Please initialize Cardboard XR loader before calling this function
I followed the quickstart from google cardboard VR, everything is ok & I can build it to android. But if I play in unity, the console shows an error "Please initialize Cardboard XR loader before calling this function."

```<code>Please initialize the Cardboard XR loader before calling this function.
UnityEngine.Debug:LogError (object)
Google.XR.Cardboard.Api:UpdateScreenParams () (at Library/PackageCache/com.google.xr.cardboard@09d53ca94c/Runtime/Api.cs:295)
CardboardStartup:Update () (at Assets/Samples/Google Cardboard XR Plugin for Unity/1.12.0/Hello Cardboard/Scripts/CardboardStartup.cs:71)
</code>```

im using Unity 2020.3.27f1 and cardboard version 1.12.0

error screenshot

答:
Open CardboardStartup.cs, find Api.UpdateScreenParams(); at the bottom (around line 70) and add the conditions to be like this, and see if it works :</p>
```<code>#if !UNITY_EDITOR
        Api.UpdateScreenParams();
#endif
</code>```

Body:
I followed the quickstart from google cardboard VR, everything is ok & I can build it to android. But if I play in unity, the console shows an error "Please initialize Cardboard XR loader before calling this function."

Please initialize the Cardboard XR loader before calling this function.
UnityEngine.Debug:LogError (object)
Google.XR.Cardboard.Api:UpdateScreenParams () (at Library/PackageCache/com.google.xr.cardboard@09d53ca94c/Runtime/Api.cs:295)
CardboardStartup:Update () (at Assets/Samples/Google Cardboard XR Plugin for Unity/1.12.0/Hello Cardboard/Scripts/CardboardStartup.cs:71)

im using Unity 2020.3.27f1 and cardboard version 1.12.0

error screenshot

Body:
Open CardboardStartup.cs, find Api.UpdateScreenParams(); at the bottom (around line 70) and add the conditions to be like this, and see if it works :

#if !UNITY_EDITOR
        Api.UpdateScreenParams();
#endif


问:
Indented, multi-line logging in NodeJS
I want to print JSON.stringify()'d objects to the console, for context as part of a Mocha test suite output.

As the tests indent, I'd like the object log lines to be indented far enough rightwards (say, 3-4 tab spaces) that they are recognisably in the right describe() group.

How could I achieve this with something like console.log or process.stdout.write?

答:
under nodejs you can try util.inspect(obj, {depth:10, colors:true ...})
i used it under mocha tested to indent logs

```<code>const log = (...args:unknown[])=>{
    setTimeout(()=>{
        let indent = "\t";
        args = args.map(a=>util.inspect(a, {colors:true, depth:10}).replace(/^\x1B\[32m['"`]/ig, '\x1B[32m').replace(/['"`]\x1B\[39m$/ig, '\x1B[39m').replace(/\n/g, `\n${indent} `))
        console.log.call(console, indent, ...args);
    })
}
let user = {
    name:"surinder singh",
    age:38,
    hobbies:[{
        name:"Something interesting",
        from:"birth"
    },{
        name:"Electronic DIY",
        from:"from ~primary"
    },{
        name:"Coding",
        from:"after school"
    }]
}
let args = ["a string 1234", 123 , {xyz:"xyz", num:123, arr:["xxx", 123, {345:"xxx"}, user], bool:true}];

console.log( ...args );
log( ...args  )
</code>```

Title: Indented, multi-line logging in NodeJS

Body:
under nodejs you can try util.inspect(obj, {depth:10, colors:true ...})
i used it under mocha tested to indent logs

const log = (...args:unknown[])=>{
    setTimeout(()=>{
        let indent = "\t";
        args = args.map(a=>util.inspect(a, {colors:true, depth:10}).replace(/^\x1B\[32m['"`]/ig, '\x1B[32m').replace(/['"`]\x1B\[39m$/ig, '\x1B[39m').replace(/\n/g, `\n${indent} `))
        console.log.call(console, indent, ...args);
    })
}
let user = {
    name:"surinder singh",
    age:38,
    hobbies:[{
        name:"Something interesting",
        from:"birth"
    },{
        name:"Electronic DIY",
        from:"from ~primary"
    },{
        name:"Coding",
        from:"after school"
    }]
}
let args = ["a string 1234", 123 , {xyz:"xyz", num:123, arr:["xxx", 123, {345:"xxx"}, user], bool:true}];

console.log( ...args );
log( ...args  )


问:
What happens when default.aspx page is requested for the first time?
What happens when default.aspx page is requested for the first time?

.net is pure a pure Object Oriented Framework.

_default is a class which extends Page.

Without instantiating, Pre-Init,Init,Load cannot be called.
So How _default class is instantiated?
Who is responsible for that?

I want to know very detailed technical steps?

Pleasa clarify!

答:
The ASP.Net framework identifies that the request is for the page default.aspx and examines the markup of the corresponding .aspx file - using this it generates a class based on that markup.  The base class for that class is identified in the @Page directive:

```<code><%@ Page ... Inherits="WebApplication1._Default" %>
</code>```

It then creates an instance of that generated type - this type inherits from the given base class, in this case WebApplication1._Default.

The ASP.Net framework doesn't normally (ever?) directly create an instance of your "code behind" class.

You can see this for yourself by debugging a simple web application:

```<code>public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // default_asp NOT _Default as you might expect
        string typeName = this.GetType().Name;
    }
}
</code>```

This explains why event handlers only need to be marked as protected instead of public.

If you are really keen you can get the path to the generated assembly using  this.GetType().Assembly.CodeBase, make a copy of that file and inspect the generated class in something like IL Spy.

Body:
The ASP.Net framework identifies that the request is for the page default.aspx and examines the markup of the corresponding .aspx file - using this it generates a class based on that markup.  The base class for that class is identified in the @Page directive:

<%@ Page ... Inherits="WebApplication1._Default" %>

It then creates an instance of that generated type - this type inherits from the given base class, in this case WebApplication1._Default.

The ASP.Net framework doesn't normally (ever?) directly create an instance of your "code behind" class.

You can see this for yourself by debugging a simple web application:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // default_asp NOT _Default as you might expect
        string typeName = this.GetType().Name;
    }
}

This explains why event handlers only need to be marked as protected instead of public.

If you are really keen you can get the path to the generated assembly using  this.GetType().Assembly.CodeBase, make a copy of that file and inspect the generated class in something like IL Spy.


问:
Postgresql status is active and exited
Postgresql service status is active but excited ,because of that i am getting an error while running thingsboard.
Error from thingsboard and postgress status:

Caused by: org.postgresql.util.PSQLException: ERROR: column
a.propagate_to_owner does not exist

postgresql status: ● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
Active: active (exited) since Sun 2022-02-13 15:28:46 IST; 27s ago
Process: 161729 ExecStart=/bin/true (code=exited, status=0/SUCCESS)    Main PID: 161729 (code=exited, status=0/SUCCESS)

systemd[1]: Starting
PostgreSQL RDBMS...
systemd[1]: Finished PostgreSQL RDBMS.

can anyone help me how to restart postgresql without loosing my data.

答:
Don't let systemd confuse you.

Locate the PostgreSQL data directory and look for the postmaster.pid file there. See if the process mentioned there is running and is a PostgreSQL process. Then you know if PostgreSQL is running or not.

If it is running, and systemd thinks it is not, then PostgreSQL was probably started in some other fashion. Shutting down PostgreSQL and starting it viw systemctl usually fixes the problem.

If PostgreSQL is not running, figure out why. First, look at the PostgreSQL log – the problem might become apparent right away. If that does not solve the mystery, figure out how PostgreSQL is started in the systemd service file and repeat that process manually. The resulting error messages should clarify what the problem is (often, a broken configuration).

Title: Postgresql status is active and exited


问:
Convert oracle date to another date format using php language
I am extracting date from the oracle database in this format: 31-DEC-68, then I use PHP to convert it to date like this: 'Y-m-d'. it's working fine for me for dates after 2000 otherwise it gives a wrong date for example this date :31-DEC-68 converted to 2068-12-31, it should be 1968-12-31.

this is a sample of my code:

```<code>$query = "select * from my_table";
$stid = oci_parse($connection, $query);
oci_execute($stid);
while (oci_fetch($stid)) {
    $dateVariable = oci_result($stid, 'date_field_from_oracle');
}
</code>```

Any help, please?

答:
Assuming for a moment that the date column is really stored as a DATE in the database, don't use select * in your query: this is generally considered sloppy anyway, and in your case in particular you should be using the to_char() function to explicitly define the format in which you want the date returned.

Try something like the following:

```<code>select to_char(date_field,'YYYY-MM-DD'), other_field1, other_field2 from my_table
</code>```

Then you shouldn't have to do an additional format conversion in PHP or  worry about default session parameters. In general you should always define your expected columns and return formats explicitly in your SQL, as default formats may change between tools and sessions (as you're seeing already - that's most likely why the DBAs query results look different that yours), and to be able to identify which code is directly affected by changes to the underlying table (like changes to column names, addition or removal of columns, etc.).

Body:
I am extracting date from the oracle database in this format: 31-DEC-68, then I use PHP to convert it to date like this: 'Y-m-d'. it's working fine for me for dates after 2000 otherwise it gives a wrong date for example this date :31-DEC-68 converted to 2068-12-31, it should be 1968-12-31.

this is a sample of my code:

$query = "select * from my_table";
$stid = oci_parse($connection, $query);
oci_execute($stid);
while (oci_fetch($stid)) {
    $dateVariable = oci_result($stid, 'date_field_from_oracle');
}

Any help, please?

Body:
Assuming for a moment that the date column is really stored as a DATE in the database, don't use select * in your query: this is generally considered sloppy anyway, and in your case in particular you should be using the to_char() function to explicitly define the format in which you want the date returned.

Try something like the following:

select to_char(date_field,'YYYY-MM-DD'), other_field1, other_field2 from my_table

Then you shouldn't have to do an additional format conversion in PHP or  worry about default session parameters. In general you should always define your expected columns and return formats explicitly in your SQL, as default formats may change between tools and sessions (as you're seeing already - that's most likely why the DBAs query results look different that yours), and to be able to identify which code is directly affected by changes to the underlying table (like changes to column names, addition or removal of columns, etc.).


问:
Using for loop to extract items from .RData files into an empty vector?
I have a series of tests each with its own .RData file. I am trying to use a for loop in R to extract a particular variable from each file. The code I currently have is:

```<code>setwd("C:/Users/c7271616/test files directory/") #File where test data files are
schedule <- list.files(pattern = ".RData") #list of files
p_inputs<- vector(mode = "numeric", length = length(schedule)) # empty vector to store results

for (i in 1:length(schedule)){
  load(paste(getwd(),"/",schedule[i],sep = ""))
  p <- as.numeric(P1)
  p_inputs[i] <- p
}
p_inputs
</code>```

The result is an vector where the first n items are 0 then one value of P has been appended on the end of the mostly empty vector.

```<code>   0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000
0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000
0.000    0.000 6437.887
</code>```

How can I alter the code so the "p" values are stored in the empty vector? I know the loop is looping through all the files as I have experimented with a print(p) in the loop and it lists all the values but does not store them in the vector.

答:
I have managed to solve this by using a counter variable like so:</p>
```<code>setwd("C:/Users/c7271616/OneDrive - Leeds Beckett University/QUB Data/Gowbusk Farm/QUB Summarys/")
schedule <- list.files(pattern = ".RData")

#p_inputs <- data.frame(mode = "numeric", length = length(schedule))
p_inputs<- vector(mode = "numeric", length = length(schedule))
test_ids<- vector(mode = "character", length = length(schedule))
counter <- 1

for (i in 1:length(schedule)){
  load(paste(getwd(),"/",schedule[i],sep = ""))
  p <- P1
  p_inputs[counter] <- p
  test_id <- paste(test_date, duration)
  test_ids[counter] <- test_id
  counter <- counter +1
}

p_inputs
</code>```

Body:
I have a series of tests each with its own .RData file. I am trying to use a for loop in R to extract a particular variable from each file. The code I currently have is:

setwd("C:/Users/c7271616/test files directory/") #File where test data files are
schedule <- list.files(pattern = ".RData") #list of files
p_inputs<- vector(mode = "numeric", length = length(schedule)) # empty vector to store results

for (i in 1:length(schedule)){
  load(paste(getwd(),"/",schedule[i],sep = ""))
  p <- as.numeric(P1)
  p_inputs[i] <- p
}
p_inputs

The result is an vector where the first n items are 0 then one value of P has been appended on the end of the mostly empty vector.

   0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000
0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000    0.000
0.000    0.000 6437.887

How can I alter the code so the "p" values are stored in the empty vector? I know the loop is looping through all the files as I have experimented with a print(p) in the loop and it lists all the values but does not store them in the vector.

Body:
I have managed to solve this by using a counter variable like so:

setwd("C:/Users/c7271616/OneDrive - Leeds Beckett University/QUB Data/Gowbusk Farm/QUB Summarys/")
schedule <- list.files(pattern = ".RData")

#p_inputs <- data.frame(mode = "numeric", length = length(schedule))
p_inputs<- vector(mode = "numeric", length = length(schedule))
test_ids<- vector(mode = "character", length = length(schedule))
counter <- 1

for (i in 1:length(schedule)){
  load(paste(getwd(),"/",schedule[i],sep = ""))
  p <- P1
  p_inputs[counter] <- p
  test_id <- paste(test_date, duration)
  test_ids[counter] <- test_id
  counter <- counter +1
}

p_inputs


问:
what can i use instead of float or int if i want to show the zeros after point like number = 1.200
**i am adding two number with point **

number = float(str(num1)+"."+str(num2))

i am using them as index so when num1 = 1 and num2 = 200 it returns number = 1.2 instead I need
number = 1.200 how can I do that

答:
Here is simpler approach:

```<code>number = 1.2
print(number)
print(type(number))

number_of_zeros = 3
number_B = str(number) + "0" * number_of_zeros
print(number_B)
print(type(number_B))

number_C = format(number, f".{number_of_zeros+1}f")
print(number_C)
print(type(number_C))
</code>```

Output:

```<code>1.2
<class 'float'>
1.2000
<class 'str'>
1.2000
<class 'str'>
</code>```

Body:
Here is simpler approach:

number = 1.2
print(number)
print(type(number))

number_of_zeros = 3
number_B = str(number) + "0" * number_of_zeros
print(number_B)
print(type(number_B))

number_C = format(number, f".{number_of_zeros+1}f")
print(number_C)
print(type(number_C))

Output:

1.2
<class 'float'>
1.2000
<class 'str'>
1.2000
<class 'str'>


问:
Ruby: Ordered array and add to array at next number if number exists
I was wondering if anyone new of an easy way to organize an array by numbers but if the number already exists push it to the next number that doesn't exist I was thinking of just creating a multi-dimensional ordered array where if numbers clash (such as 2 pages having 1) then the first would be [1][1] and the second would be [1][2] but is there a better way to handle this?

Edit; an example:

```<code>page1 -> sets order to 1
page2 -> sets order to 1
page3 -> sets order to 2
</code>```

Normally I would go through and YAML read the pages configurations and get the order and then use that number and set _site.sidebar[_config["order"]] but in this case it would clash and it wouldn't add it. So I'm looking for a way to allow for user mistakes but preserve order keeping the first found as one but if one exists shift the array down and put the second 1 as two.

答:
Here is the final snippet on how I implemented what I was asking about, just in case somebody else stumbles upon this thread looking for the same sort of thing.  I basically just wanted to preserve the order, in my actual application of the code I used a normal multi-dimensional array since "order" was pulled from YAML front so it is it's own variable.</p>

```<code>data = []
demo = {
  "page_1" => {
    "order" => 1,
    "data" => "Hello World 1"
  },
  "page_2" => {
    "order" => 2,
    "data" => "Hello World 2"
  },
  "page_3" => {
    "order" => 1,
    "data" => "Hello World 3"
  },
  "page_4" => {
    "order" => "a",
    "data" => "Hello World 4"
  }
}

demo.each |key, page|
  local_data = page["data"]
  order      = page["order"].to_i.floor

  data[order] ||= []
  data[order] << local_data

}
puts data.flatten.join(" ").strip
</code>```

Body:
I was wondering if anyone new of an easy way to organize an array by numbers but if the number already exists push it to the next number that doesn't exist I was thinking of just creating a multi-dimensional ordered array where if numbers clash (such as 2 pages having 1) then the first would be [1][1] and the second would be [1][2] but is there a better way to handle this?

Edit; an example:

page1 -> sets order to 1
page2 -> sets order to 1
page3 -> sets order to 2

Normally I would go through and YAML read the pages configurations and get the order and then use that number and set _site.sidebar[_config["order"]] but in this case it would clash and it wouldn't add it. So I'm looking for a way to allow for user mistakes but preserve order keeping the first found as one but if one exists shift the array down and put the second 1 as two.

Body:
Here is the final snippet on how I implemented what I was asking about, just in case somebody else stumbles upon this thread looking for the same sort of thing.  I basically just wanted to preserve the order, in my actual application of the code I used a normal multi-dimensional array since "order" was pulled from YAML front so it is it's own variable.

data = []
demo = {
  "page_1" => {
    "order" => 1,
    "data" => "Hello World 1"
  },
  "page_2" => {
    "order" => 2,
    "data" => "Hello World 2"
  },
  "page_3" => {
    "order" => 1,
    "data" => "Hello World 3"
  },
  "page_4" => {
    "order" => "a",
    "data" => "Hello World 4"
  }
}

demo.each |key, page|
  local_data = page["data"]
  order      = page["order"].to_i.floor

  data[order] ||= []
  data[order] << local_data

}
puts data.flatten.join(" ").strip


问:
Customise Firefox extension using chrome/userChrome.css
I have foxclocks installed "{d37dc5d0-431d-44e5-8c91-49419370caa1}.xpi"

I have enabled use of chrome/userChrome.css and have hidden menu items so I know it is working.

I like to hide the "closer" in fox clocks but how do I reference it in chrome/userChrome.css

I tried

```<code>#closer { display: none !important }
</code>```

but didnt work?

See image below

答:
Works by doing the same with userContent.css and turning on

```<code>toolkit.legacyUserProfileCustomizations.stylesheets to true
</code>```

in about:config.

Body:
I have foxclocks installed "{d37dc5d0-431d-44e5-8c91-49419370caa1}.xpi"

I have enabled use of chrome/userChrome.css and have hidden menu items so I know it is working.

I like to hide the "closer" in fox clocks but how do I reference it in chrome/userChrome.css

I tried

#closer { display: none !important }

but didnt work?

See image below

Body:
Works by doing the same with userContent.css and turning on

toolkit.legacyUserProfileCustomizations.stylesheets to true

in about:config.


问:
Problem is infeasible with Gurobi, feasible with cbc (but can't access objective value)
I am solving a MILP with cbc and gurobi (via pyomo). Gurobi states that the model is infeasible. As to cbc the solver status states that a feasible and optimal solution is found, but then it fails to access the value of the objective (which in turn crashed my program).

Here is how I access the objective value

```<code>solver_parameters = "ResultFile=model.lp"
opt = SolverFactory(solver)

results = opt.solve(self.model, tee=False, options_string=solver_parameters,logfile="model.log")
# checking status and terminiation condition
print ("The solver returned a status of: "+str(results.solver.status))
print (str(results.solver))
if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition== TerminationCondition.optimal):
   print ("Problem is feasible and solution is optimal")
        objective_value = value(self.model.objective)
else:
   print("Problem is infeasible")
   objective_value = None
</code>```

With cbc I get

```<code>The solver returned a status of: ok

- Status: ok
  Message: CBC 2.10.5
  Termination condition: optimal
  Id: 0
  Error rc: 0
  Time: 0.011972904205322266

Problem is feasible and solution is optimal

ERROR: evaluating object as numeric value: x[0]
        (object: <class 'pyomo.core.base.var._GeneralVarData'>)
    No value for uninitialized NumericValue object x[0]
ERROR: evaluating object as numeric value: objective
        (object: <class 'pyomo.core.base.objective.SimpleObjective'>)
    No value for uninitialized NumericValue object x[0]
Traceback (most recent call last):
...
  File "c:...", line 531, in solve
    objective_value = value(self.model.objective)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 231, in pyomo.core.expr.numvalue.value
  File "C:...\lib\site-packages\pyomo\core\base\expression.py", line 55, in __call__
    return self.expr(exception=exception)
  File "pyomo\core\expr\numeric_expr.pyx", line 218, in pyomo.core.expr.numeric_expr.ExpressionBase.__call__
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 1054, in evaluate_expression
    return visitor.dfs_postorder_stack(exp)
  File "C:...\venv\lib\site-packages\pyomo\core\expr\visitor.py", line 584, in dfs_postorder_stack
    flag, value = self.visiting_potential_leaf(_sub)
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 962, in visiting_potential_leaf
    return True, value(node)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 233, in pyomo.core.expr.numvalue.value
ValueError: No value for uninitialized NumericValue object x[0]
</code>```

On the other hand with gurobi I get

```<code>WARNING: Loading a SolverResults object with a warning status into
    model.name="unknown";
      - termination condition: infeasible
      - message from solver: Model was proven to be infeasible.
The solver returned a status of: warning

- Status: warning
  Return code: 0
  Message: Model was proven to be infeasible.
  Termination condition: infeasible
  Termination message: Model was proven to be infeasible.
  Wall time: 0.0019626617431640625
  Error rc: 0
  Time: 0.08476400375366211

Problem is infeasible
</code>```

I'm assuming problem is indeed infeasible and the error comes from cbc. Is this kind of error common, and what would be a way to avoid this?

Finally, this is the lp model returned by gurobi

```<code>\ Model x79
\ LP format - for model browsing. Use MPS format to capture full model detail.
Maximize
  - 100 x12 - 200 x13 - 300 x14 - 400 x15 - 70 x16 - 140 x17 - 90 x18
   - 90 x19
Subject To
 c_u_x80_: x12 - 100 x1 <= 0
 c_u_x81_: x13 - 100 x2 <= 0
 c_u_x82_: x14 - 100 x3 <= 0
 c_u_x83_: x15 - 100 x4 <= 0
 c_u_x84_: x16 - 50 x5 <= 0
 c_u_x85_: x17 - 50 x6 <= 0
 c_u_x86_: x18 - 25 x7 <= 0
 c_u_x87_: x19 - 25 x8 <= 0
 c_l_x88_: x12 >= 0
 c_l_x89_: x13 >= 0
 c_l_x90_: x14 >= 0
 c_l_x91_: x15 >= 0
 c_l_x92_: x16 >= 0
 c_l_x93_: x17 >= 0
 c_l_x94_: x18 >= 0
 c_l_x95_: x19 >= 0
 c_u_x96_: x1 <= 1
 c_u_x97_: x2 <= 1
 c_u_x98_: x3 <= 1
 c_u_x99_: x4 <= 1
 c_u_x100_: x5 <= 1
 c_u_x101_: x6 <= 1
 c_u_x102_: x7 <= 1
 c_u_x103_: x8 <= 1
 c_e_x104_: x12 + x16 = 51
 c_e_x105_: x13 + x17 = 51
 c_e_x106_: x14 + x18 = 51
 c_e_x107_: x15 + x19 = 51
 c_u_x108_: - x7 + x9 <= 0
 c_u_x109_: - x6 + x10 <= 0
 c_u_x110_: - x2 - x3 + x11 <= 0
 c_u_x111_: x7 - 2 x9 <= 0
 c_u_x112_: x6 - 2 x10 <= 0
 c_u_x113_: x2 + x3 - 2 x11 <= 0
 c_u_x114_: 100 x13 + 20 x14 + 100 x17 + 20 x18 <= 6072
 c_u_x115_: - 20 x18 + 1260 x9 <= 0
 c_u_x116_: - 100 x17 + 1260 x10 <= 0
 c_u_x117_: - 100 x13 - 20 x14 + 1260 x11 <= 0
 c_u_x118_: 2 x1 - x24 <= 0
 c_u_x119_: 2 x2 - x25 <= 0
 c_u_x120_: 15 x3 - x26 <= 0
 c_u_x121_: 10 x4 - x27 <= 0
 c_u_x122_: 1.4 x5 - x24 <= 0
 c_u_x123_: 1.4 x6 - x25 <= 0
 c_u_x124_: 4.5 x7 - x26 <= 0
 c_u_x125_: 2.25 x8 - x27 <= 0
 c_u_x126_: 100 x12 + 200 x13 + 300 x14 + 400 x15 + 70 x16 + 140 x17
   + 90 x18 + 90 x19 - 2550 x24 - 5100 x25 - 1020 x26 - 2040 x27 + 6072 x48
   + 100 x60 + 100 x61 + 100 x62 + 100 x63 + 50 x64 + 50 x65 + 25 x66
   + 25 x67 - 1260 x76 - 1260 x77 - 1260 x78 <= 0
 c_u_x127_: - 1000 x1 + x60 <= 0
 c_u_x128_: - 1000 x2 + x61 <= 0
 c_u_x129_: - 1000 x3 + x62 <= 0
 c_u_x130_: - 1000 x4 + x63 <= 0
 c_u_x131_: - 1000 x5 + x64 <= 0
 c_u_x132_: - 1000 x6 + x65 <= 0
 c_u_x133_: - 1000 x7 + x66 <= 0
 c_u_x134_: - 1000 x8 + x67 <= 0
 c_u_x135_: x60 - x32 <= 0
 c_u_x136_: x61 - x33 <= 0
 c_u_x137_: x62 - x34 <= 0
 c_u_x138_: x63 - x35 <= 0
 c_u_x139_: x64 - x36 <= 0
 c_u_x140_: x65 - x37 <= 0
 c_u_x141_: x66 - x38 <= 0
 c_u_x142_: x67 - x39 <= 0
 c_u_x143_: 1000 x1 - x60 + x32 <= 1000
 c_u_x144_: 1000 x2 - x61 + x33 <= 1000
 c_u_x145_: 1000 x3 - x62 + x34 <= 1000
 c_u_x146_: 1000 x4 - x63 + x35 <= 1000
 c_u_x147_: 1000 x5 - x64 + x36 <= 1000
 c_u_x148_: 1000 x6 - x65 + x37 <= 1000
 c_u_x149_: 1000 x7 - x66 + x38 <= 1000
 c_u_x150_: 1000 x8 - x67 + x39 <= 1000
 c_u_x151_: - 1000 x1 + x68 <= 0
 c_u_x152_: - 1000 x2 + x69 <= 0
 c_u_x153_: - 1000 x3 + x70 <= 0
 c_u_x154_: - 1000 x4 + x71 <= 0
 c_u_x155_: - 1000 x5 + x72 <= 0
 c_u_x156_: - 1000 x6 + x73 <= 0
 c_u_x157_: - 1000 x7 + x74 <= 0
 c_u_x158_: - 1000 x8 + x75 <= 0
 c_u_x159_: x68 - x40 <= 0
 c_u_x160_: x69 - x41 <= 0
 c_u_x161_: x70 - x42 <= 0
 c_u_x162_: x71 - x43 <= 0
 c_u_x163_: x72 - x44 <= 0
 c_u_x164_: x73 - x45 <= 0
 c_u_x165_: x74 - x46 <= 0
 c_u_x166_: x75 - x47 <= 0
 c_u_x167_: 1000 x1 - x68 + x40 <= 1000
 c_u_x168_: 1000 x2 - x69 + x41 <= 1000
 c_u_x169_: 1000 x3 - x70 + x42 <= 1000
 c_u_x170_: 1000 x4 - x71 + x43 <= 1000
 c_u_x171_: 1000 x5 - x72 + x44 <= 1000
 c_u_x172_: 1000 x6 - x73 + x45 <= 1000
 c_u_x173_: 1000 x7 - x74 + x46 <= 1000
 c_u_x174_: 1000 x8 - x75 + x47 <= 1000
 c_u_x175_: - 1000 x9 + x76 <= 0
 c_u_x176_: - 1000 x10 + x77 <= 0
 c_u_x177_: - 1000 x11 + x78 <= 0
 c_u_x178_: x76 - x49 <= 0
 c_u_x179_: x77 - x50 <= 0
 c_u_x180_: x78 - x51 <= 0
 c_u_x181_: 1000 x9 - x76 + x49 <= 1000
 c_u_x182_: 1000 x10 - x77 + x50 <= 1000
 c_u_x183_: 1000 x11 - x78 + x51 <= 1000
 c_l_x184_: - 50 x24 + x32 - x40 >= -100
 c_l_x185_: - 100 x25 + 100 x48 + x33 - x41 - 100 x51 >= -200
 c_l_x186_: - 20 x26 + 20 x48 + x34 - x42 - 20 x51 >= -300
 c_l_x187_: - 40 x27 + x35 - x43 >= -400
 c_l_x188_: - 50 x24 + x36 - x44 >= -70
 c_l_x189_: - 100 x25 + 100 x48 + x37 - x45 - 100 x50 >= -140
 c_l_x190_: - 20 x26 + 20 x48 + x38 - x46 - 20 x49 >= -90
 c_l_x191_: - 40 x27 + x39 - x47 >= -90
 c_u_x192_: x24 <= 2
 c_u_x193_: x25 <= 2
 c_u_x194_: x26 <= 15
 c_u_x195_: x27 <= 10
 c_e_ONE_VAR_CONSTANT: ONE_VAR_CONSTANT = 1
Bounds
 x24 free
 x25 free
 x26 free
 x27 free
Binaries
 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
End
</code>```

答: This is already answered in this duplicate question over on OR exchange: The problem is indeed infeasible and CBC reports an incorrect optimality status.</p>

Body:
I am solving a MILP with cbc and gurobi (via pyomo). Gurobi states that the model is infeasible. As to cbc the solver status states that a feasible and optimal solution is found, but then it fails to access the value of the objective (which in turn crashed my program).

Here is how I access the objective value

solver_parameters = "ResultFile=model.lp"
opt = SolverFactory(solver)

results = opt.solve(self.model, tee=False, options_string=solver_parameters,logfile="model.log")
# checking status and terminiation condition
print ("The solver returned a status of: "+str(results.solver.status))
print (str(results.solver))
if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition== TerminationCondition.optimal):
   print ("Problem is feasible and solution is optimal")
        objective_value = value(self.model.objective)
else:
   print("Problem is infeasible")
   objective_value = None

With cbc I get

The solver returned a status of: ok

- Status: ok
  Message: CBC 2.10.5
  Termination condition: optimal
  Id: 0
  Error rc: 0
  Time: 0.011972904205322266

Problem is feasible and solution is optimal

ERROR: evaluating object as numeric value: x[0]
        (object: <class 'pyomo.core.base.var._GeneralVarData'>)
    No value for uninitialized NumericValue object x[0]
ERROR: evaluating object as numeric value: objective
        (object: <class 'pyomo.core.base.objective.SimpleObjective'>)
    No value for uninitialized NumericValue object x[0]
Traceback (most recent call last):
...
  File "c:...", line 531, in solve
    objective_value = value(self.model.objective)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 231, in pyomo.core.expr.numvalue.value
  File "C:...\lib\site-packages\pyomo\core\base\expression.py", line 55, in __call__
    return self.expr(exception=exception)
  File "pyomo\core\expr\numeric_expr.pyx", line 218, in pyomo.core.expr.numeric_expr.ExpressionBase.__call__
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 1054, in evaluate_expression
    return visitor.dfs_postorder_stack(exp)
  File "C:...\venv\lib\site-packages\pyomo\core\expr\visitor.py", line 584, in dfs_postorder_stack
    flag, value = self.visiting_potential_leaf(_sub)
  File "C:...\lib\site-packages\pyomo\core\expr\visitor.py", line 962, in visiting_potential_leaf
    return True, value(node)
  File "pyomo\core\expr\numvalue.pyx", line 246, in pyomo.core.expr.numvalue.value
  File "pyomo\core\expr\numvalue.pyx", line 233, in pyomo.core.expr.numvalue.value
ValueError: No value for uninitialized NumericValue object x[0]

On the other hand with gurobi I get

WARNING: Loading a SolverResults object with a warning status into
    model.name="unknown";
      - termination condition: infeasible
      - message from solver: Model was proven to be infeasible.
The solver returned a status of: warning

- Status: warning
  Return code: 0
  Message: Model was proven to be infeasible.
  Termination condition: infeasible
  Termination message: Model was proven to be infeasible.
  Wall time: 0.0019626617431640625
  Error rc: 0
  Time: 0.08476400375366211

Problem is infeasible

I'm assuming problem is indeed infeasible and the error comes from cbc. Is this kind of error common, and what would be a way to avoid this?

Finally, this is the lp model returned by gurobi

\ Model x79
\ LP format - for model browsing. Use MPS format to capture full model detail.
Maximize
  - 100 x12 - 200 x13 - 300 x14 - 400 x15 - 70 x16 - 140 x17 - 90 x18
   - 90 x19
Subject To
 c_u_x80_: x12 - 100 x1 <= 0
 c_u_x81_: x13 - 100 x2 <= 0
 c_u_x82_: x14 - 100 x3 <= 0
 c_u_x83_: x15 - 100 x4 <= 0
 c_u_x84_: x16 - 50 x5 <= 0
 c_u_x85_: x17 - 50 x6 <= 0
 c_u_x86_: x18 - 25 x7 <= 0
 c_u_x87_: x19 - 25 x8 <= 0
 c_l_x88_: x12 >= 0
 c_l_x89_: x13 >= 0
 c_l_x90_: x14 >= 0
 c_l_x91_: x15 >= 0
 c_l_x92_: x16 >= 0
 c_l_x93_: x17 >= 0
 c_l_x94_: x18 >= 0
 c_l_x95_: x19 >= 0
 c_u_x96_: x1 <= 1
 c_u_x97_: x2 <= 1
 c_u_x98_: x3 <= 1
 c_u_x99_: x4 <= 1
 c_u_x100_: x5 <= 1
 c_u_x101_: x6 <= 1
 c_u_x102_: x7 <= 1
 c_u_x103_: x8 <= 1
 c_e_x104_: x12 + x16 = 51
 c_e_x105_: x13 + x17 = 51
 c_e_x106_: x14 + x18 = 51
 c_e_x107_: x15 + x19 = 51
 c_u_x108_: - x7 + x9 <= 0
 c_u_x109_: - x6 + x10 <= 0
 c_u_x110_: - x2 - x3 + x11 <= 0
 c_u_x111_: x7 - 2 x9 <= 0
 c_u_x112_: x6 - 2 x10 <= 0
 c_u_x113_: x2 + x3 - 2 x11 <= 0
 c_u_x114_: 100 x13 + 20 x14 + 100 x17 + 20 x18 <= 6072
 c_u_x115_: - 20 x18 + 1260 x9 <= 0
 c_u_x116_: - 100 x17 + 1260 x10 <= 0
 c_u_x117_: - 100 x13 - 20 x14 + 1260 x11 <= 0
 c_u_x118_: 2 x1 - x24 <= 0
 c_u_x119_: 2 x2 - x25 <= 0
 c_u_x120_: 15 x3 - x26 <= 0
 c_u_x121_: 10 x4 - x27 <= 0
 c_u_x122_: 1.4 x5 - x24 <= 0
 c_u_x123_: 1.4 x6 - x25 <= 0
 c_u_x124_: 4.5 x7 - x26 <= 0
 c_u_x125_: 2.25 x8 - x27 <= 0
 c_u_x126_: 100 x12 + 200 x13 + 300 x14 + 400 x15 + 70 x16 + 140 x17
   + 90 x18 + 90 x19 - 2550 x24 - 5100 x25 - 1020 x26 - 2040 x27 + 6072 x48
   + 100 x60 + 100 x61 + 100 x62 + 100 x63 + 50 x64 + 50 x65 + 25 x66
   + 25 x67 - 1260 x76 - 1260 x77 - 1260 x78 <= 0
 c_u_x127_: - 1000 x1 + x60 <= 0
 c_u_x128_: - 1000 x2 + x61 <= 0
 c_u_x129_: - 1000 x3 + x62 <= 0
 c_u_x130_: - 1000 x4 + x63 <= 0
 c_u_x131_: - 1000 x5 + x64 <= 0
 c_u_x132_: - 1000 x6 + x65 <= 0
 c_u_x133_: - 1000 x7 + x66 <= 0
 c_u_x134_: - 1000 x8 + x67 <= 0
 c_u_x135_: x60 - x32 <= 0
 c_u_x136_: x61 - x33 <= 0
 c_u_x137_: x62 - x34 <= 0
 c_u_x138_: x63 - x35 <= 0
 c_u_x139_: x64 - x36 <= 0
 c_u_x140_: x65 - x37 <= 0
 c_u_x141_: x66 - x38 <= 0
 c_u_x142_: x67 - x39 <= 0
 c_u_x143_: 1000 x1 - x60 + x32 <= 1000
 c_u_x144_: 1000 x2 - x61 + x33 <= 1000
 c_u_x145_: 1000 x3 - x62 + x34 <= 1000
 c_u_x146_: 1000 x4 - x63 + x35 <= 1000
 c_u_x147_: 1000 x5 - x64 + x36 <= 1000
 c_u_x148_: 1000 x6 - x65 + x37 <= 1000
 c_u_x149_: 1000 x7 - x66 + x38 <= 1000
 c_u_x150_: 1000 x8 - x67 + x39 <= 1000
 c_u_x151_: - 1000 x1 + x68 <= 0
 c_u_x152_: - 1000 x2 + x69 <= 0
 c_u_x153_: - 1000 x3 + x70 <= 0
 c_u_x154_: - 1000 x4 + x71 <= 0
 c_u_x155_: - 1000 x5 + x72 <= 0
 c_u_x156_: - 1000 x6 + x73 <= 0
 c_u_x157_: - 1000 x7 + x74 <= 0
 c_u_x158_: - 1000 x8 + x75 <= 0
 c_u_x159_: x68 - x40 <= 0
 c_u_x160_: x69 - x41 <= 0
 c_u_x161_: x70 - x42 <= 0
 c_u_x162_: x71 - x43 <= 0
 c_u_x163_: x72 - x44 <= 0
 c_u_x164_: x73 - x45 <= 0
 c_u_x165_: x74 - x46 <= 0
 c_u_x166_: x75 - x47 <= 0
 c_u_x167_: 1000 x1 - x68 + x40 <= 1000
 c_u_x168_: 1000 x2 - x69 + x41 <= 1000
 c_u_x169_: 1000 x3 - x70 + x42 <= 1000
 c_u_x170_: 1000 x4 - x71 + x43 <= 1000
 c_u_x171_: 1000 x5 - x72 + x44 <= 1000
 c_u_x172_: 1000 x6 - x73 + x45 <= 1000
 c_u_x173_: 1000 x7 - x74 + x46 <= 1000
 c_u_x174_: 1000 x8 - x75 + x47 <= 1000
 c_u_x175_: - 1000 x9 + x76 <= 0
 c_u_x176_: - 1000 x10 + x77 <= 0
 c_u_x177_: - 1000 x11 + x78 <= 0
 c_u_x178_: x76 - x49 <= 0
 c_u_x179_: x77 - x50 <= 0
 c_u_x180_: x78 - x51 <= 0
 c_u_x181_: 1000 x9 - x76 + x49 <= 1000
 c_u_x182_: 1000 x10 - x77 + x50 <= 1000
 c_u_x183_: 1000 x11 - x78 + x51 <= 1000
 c_l_x184_: - 50 x24 + x32 - x40 >= -100
 c_l_x185_: - 100 x25 + 100 x48 + x33 - x41 - 100 x51 >= -200
 c_l_x186_: - 20 x26 + 20 x48 + x34 - x42 - 20 x51 >= -300
 c_l_x187_: - 40 x27 + x35 - x43 >= -400
 c_l_x188_: - 50 x24 + x36 - x44 >= -70
 c_l_x189_: - 100 x25 + 100 x48 + x37 - x45 - 100 x50 >= -140
 c_l_x190_: - 20 x26 + 20 x48 + x38 - x46 - 20 x49 >= -90
 c_l_x191_: - 40 x27 + x39 - x47 >= -90
 c_u_x192_: x24 <= 2
 c_u_x193_: x25 <= 2
 c_u_x194_: x26 <= 15
 c_u_x195_: x27 <= 10
 c_e_ONE_VAR_CONSTANT: ONE_VAR_CONSTANT = 1
Bounds
 x24 free
 x25 free
 x26 free
 x27 free
Binaries
 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11
End