问:
Why won't MYSQL procedure properly iterate new ROWS in TABLE using WHILE statement?
I am creating this basic procedure using MySQL Workbench to accept a single input parameter.
The table "unique_days" has a single PRIMARY KEY column called "dayid" which currently has a single ROW with a value of 1.

```<code>DROP PROCEDURE IF EXISTS dayid_iteration;
DELIMITER $$
CREATE PROCEDURE dayid_iteration(maxdate_final INT)
BEGIN
    DECLARE maxdate_current INT;
    SET @maxdate_current = (SELECT (MAX(dayid) + 1) FROM unique_days);
    DELETE FROM unique_days WHERE dayid > 1;

    WHILE (maxdate_current > maxdate_final) DO
        INSERT INTO unique_days (dayid) VALUES (maxdate_current);
        SET maxdate_current = (maxdate_current+1);
    END WHILE;

END$$
DELIMITER ;
</code>```

The procedure is then called with an integer parameter.

```<code>CALL dayid_iteration(11);
</code>```

The variables are setting properly because I can run a select statement with the variable and it shows the correct new value. The deletion of dayid > 1 also works (Tested by manually adding additional rows, and then running procedure). However, I can't seem to get the WHILE statement to insert new rows with the value provided.

Any help is much appreciated. I searched multiple other questions, and countless forums, but everything looks like it should be working.

I am expecting the code to CREATE 9 ROWS for a total of 10 ROWS.

The following is included just so you can see the starting values of the table.

```<code>SELECT * FROM unique_days;
</code>```

答:
For anyone who finds this question, the following code functions correctly. The input variable on the parameter was not setting properly. Once the parameter had "IN" placed in front of the variable name, it correctly received the parameter.

```<code>CREATE PROCEDURE dayid_iteration(IN maxdate_final INT)
</code>```
```<code>DROP PROCEDURE IF EXISTS dayid_iteration;
DELIMITER $$
CREATE PROCEDURE dayid_iteration(IN maxdate_final INT)
BEGIN
    DECLARE maxdate_current INT;
    SET maxdate_current = (SELECT (MAX(dayid) + 1) FROM unique_days);

    WHILE (maxdate_current <= maxdate_final) DO
        INSERT INTO unique_days (dayid) VALUES (maxdate_current);
        SET maxdate_current = (maxdate_current+1);
    END WHILE;

END$$
DELIMITER ;

CALL dayid_iteration(1000);
</code>```

This call procedure now properly works.

```<code>CALL dayid_iteration(1000);
</code>```

Body:
I am creating this basic procedure using MySQL Workbench to accept a single input parameter.
The table "unique_days" has a single PRIMARY KEY column called "dayid" which currently has a single ROW with a value of 1.

DROP PROCEDURE IF EXISTS dayid_iteration;
DELIMITER $$
CREATE PROCEDURE dayid_iteration(maxdate_final INT)
BEGIN
    DECLARE maxdate_current INT;
    SET @maxdate_current = (SELECT (MAX(dayid) + 1) FROM unique_days);
    DELETE FROM unique_days WHERE dayid > 1;

    WHILE (maxdate_current > maxdate_final) DO
        INSERT INTO unique_days (dayid) VALUES (maxdate_current);
        SET maxdate_current = (maxdate_current+1);
    END WHILE;

END$$
DELIMITER ;

The procedure is then called with an integer parameter.

CALL dayid_iteration(11);

The variables are setting properly because I can run a select statement with the variable and it shows the correct new value. The deletion of dayid > 1 also works (Tested by manually adding additional rows, and then running procedure). However, I can't seem to get the WHILE statement to insert new rows with the value provided.

Any help is much appreciated. I searched multiple other questions, and countless forums, but everything looks like it should be working.

I am expecting the code to CREATE 9 ROWS for a total of 10 ROWS.

The following is included just so you can see the starting values of the table.

SELECT * FROM unique_days;

Body:
For anyone who finds this question, the following code functions correctly. The input variable on the parameter was not setting properly. Once the parameter had "IN" placed in front of the variable name, it correctly received the parameter.

CREATE PROCEDURE dayid_iteration(IN maxdate_final INT)

DROP PROCEDURE IF EXISTS dayid_iteration;
DELIMITER $$
CREATE PROCEDURE dayid_iteration(IN maxdate_final INT)
BEGIN
    DECLARE maxdate_current INT;
    SET maxdate_current = (SELECT (MAX(dayid) + 1) FROM unique_days);

    WHILE (maxdate_current <= maxdate_final) DO
        INSERT INTO unique_days (dayid) VALUES (maxdate_current);
        SET maxdate_current = (maxdate_current+1);
    END WHILE;

END$$
DELIMITER ;

CALL dayid_iteration(1000);

This call procedure now properly works.

CALL dayid_iteration(1000);


来源: stackexchange

问:
Sinon Spy on all function calls within a function
Say we have a function like this in flow.js which is a web component so all are functions inside a class within this file.

```<code>change(){

   this.getParams();
   this.loadData();
}
</code>```

I want to write a test case that can test change() and confirm whether these two functions have been invoked. I tried many approaches but it dint work. One of the approaches I tried is:

```<code>  it('change() test', function () {
     const sandbox = sinon.createSandbox();
     sandbox.spy(el);
     el.change();
     assert(el.change.calledOnce); // output is true
     assert(el.getParams.calledOnce); // output is false
     assert(el.loadData.calledOnce); // output is false
  }
</code>```

el is the object/webcomponent.

Could you please let me know what is wrong here and what is the right implementation for this scenario ?

答:
You should add spy to el.getParams() and el.loadData() methods.

E.g.

flow.js:

class Flow {
  change() {
    this.getParams();
    this.loadData();
  }
  getParams() {}
  loadData() {}
}

module.exports = Flow;
```
<p><code>flow.test.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>const Flow = require('./flow');
const sinon = require('sinon');

describe('flow', () => {
  it('should pass', () => {
    const sandbox = sinon.createSandbox();
    const flow = new Flow();
    sandbox.spy(flow, 'getParams');
    sandbox.spy(flow, 'loadData');
    flow.change();
    sinon.assert.calledOnce(flow.getParams);
    sinon.assert.calledOnce(flow.loadData);
  });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Say we have a function like this in flow.js which is a web component so all are functions inside a class within this file.

change(){

   this.getParams();
   this.loadData();
}

I want to write a test case that can test change() and confirm whether these two functions have been invoked. I tried many approaches but it dint work. One of the approaches I tried is:

  it('change() test', function () {
     const sandbox = sinon.createSandbox();
     sandbox.spy(el);
     el.change();
     assert(el.change.calledOnce); // output is true
     assert(el.getParams.calledOnce); // output is false
     assert(el.loadData.calledOnce); // output is false
  }

el is the object/webcomponent.

Could you please let me know what is wrong here and what is the right implementation for this scenario ?

Body:
You should add spy to el.getParams() and el.loadData() methods.

E.g.

flow.js:

class Flow {
  change() {
    this.getParams();
    this.loadData();
  }
  getParams() {}
  loadData() {}
}

module.exports = Flow;

flow.test.js:

const Flow = require('./flow');
const sinon = require('sinon');

describe('flow', () => {
  it('should pass', () => {
    const sandbox = sinon.createSandbox();
    const flow = new Flow();
    sandbox.spy(flow, 'getParams');
    sandbox.spy(flow, 'loadData');
    flow.change();
    sinon.assert.calledOnce(flow.getParams);
    sinon.assert.calledOnce(flow.loadData);
  });
});


问:
Xamarin Firebase child non static
Hello I want to define a non static child in my firebase database. This child should be the value entered in the "Name" field of the application (here newUser.Text)

I did this for the first page but I can't access newUser.Text on the other pages. How can I do ?

```<code>public void OnNextPageButtonClicked(object sender, EventArgs e)
{

    _ = firebaseClient.Child("Livret individuel de suivi pédagogique").Child(newUser.Text).PutAsync(new MyDatabaseRecord

    {
        Nom = newUser.Text,
        Prenom = newPrenom.Text,
        Email = newEmail.Text,
        CIS = newCIS.Text,
        Grade = newGrade.Text,
        DateRecrutement = newDateRecrutement.Date.ToString("dd/MM/yyyy"),
        DateNaissance = newDateNaissance.Date.ToString("dd/MM/yyyy"),
        Observations = newObservations.Text,

    });

    newUser.Text = "";
    newPrenom.Text = "";

    newDateNaissance.AutomationId = "";
    newCIS.Text = "";
    newGrade.Text = "";
    newDateRecrutement.AutomationId = "";
    newObservations.Text = "";

     Navigation.PushModalAsync(new page0());

}
</code>```

答:
You could use Property.

Define in Page11:

```<code>public partial class Page11 : ContentPage
{
    public string newUserText { get; set; }
    public Page11()
    {
        InitializeComponent();
    }
}
</code>```

Usage in Page12:

```<code>public partial class Page12 : ContentPage
{

    public Page12()
    {
        InitializeComponent();
        var userText = new Page11().newUserText;
    }
}
</code>```

Title: Xamarin Firebase child non static

Body:
Hello I want to define a non static child in my firebase database. This child should be the value entered in the "Name" field of the application (here newUser.Text)

I did this for the first page but I can't access newUser.Text on the other pages. How can I do ?

public void OnNextPageButtonClicked(object sender, EventArgs e)
{

    _ = firebaseClient.Child("Livret individuel de suivi pédagogique").Child(newUser.Text).PutAsync(new MyDatabaseRecord

    {
        Nom = newUser.Text,
        Prenom = newPrenom.Text,
        Email = newEmail.Text,
        CIS = newCIS.Text,
        Grade = newGrade.Text,
        DateRecrutement = newDateRecrutement.Date.ToString("dd/MM/yyyy"),
        DateNaissance = newDateNaissance.Date.ToString("dd/MM/yyyy"),
        Observations = newObservations.Text,

    });

    newUser.Text = "";
    newPrenom.Text = "";

    newDateNaissance.AutomationId = "";
    newCIS.Text = "";
    newGrade.Text = "";
    newDateRecrutement.AutomationId = "";
    newObservations.Text = "";

     Navigation.PushModalAsync(new page0());

}

Body:
You could use Property.

Define in Page11:

public partial class Page11 : ContentPage
{
    public string newUserText { get; set; }
    public Page11()
    {
        InitializeComponent();
    }
}

Usage in Page12:

public partial class Page12 : ContentPage
{

    public Page12()
    {
        InitializeComponent();
        var userText = new Page11().newUserText;
    }
}


问:
Function ereg_replace() is deprecated - How to clear this bug?
I have written following PHP code:

```<code>$input="menu=1&type=0&";

print $input."<hr>".ereg_replace('/&/', ':::', $input);
</code>```

After running above code, it gives following warning,

Deprecated: Function ereg_replace() is deprecated

How can I resolve this warning.

答:
```<code>print $input."<hr>".ereg_replace('/&/', ':::', $input);
</code>```

becomes

```<code>print $input."<hr>".preg_replace('/&/', ':::', $input);
</code>```

More example :

```<code>$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );
</code>```

is changed to

```<code>$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have written following PHP code:

$input="menu=1&type=0&";

print $input."
".ereg_replace('/&/', ':::', $input);

After running above code, it gives following warning,

Deprecated: Function ereg_replace() is deprecated

How can I resolve this warning.

Body:
print $input."<hr>".ereg_replace('/&/', ':::', $input);

becomes

print $input."<hr>".preg_replace('/&/', ':::', $input);

More example :

$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );

is changed to

$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );


问:
Program runs infinitely on typing ctrl C instead of stopping in c++
I have the following code. It runs infinitely after typing ctrl + c and executes the default section of code.

```<code>// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    while(true){
        cout << "Enter an operator (+, -, *, /): ";
        cin >> oper;
        cout << "Enter two numbers: " << endl;
        cin >> num1 >> num2;

        switch (oper) {
            case '+':
                cout << num1 << " + " << num2 << " = " << num1 + num2;
                break;
            case '-':
                cout << num1 << " - " << num2 << " = " << num1 - num2;
                break;
            case '*':
                cout << num1 << " * " << num2 << " = " << num1 * num2;
                break;
            case '/':
                cout << num1 << " / " << num2 << " = " << num1 / num2;
                break;
            default:
                // operator is doesn't match any case constant (+, -, *, /)
                cout << "Error! The operator is not correct";
                break;
        }
        cout<<endl;
    }
    return 0;
}
</code>```

The result after typing ctrl + c is as shown in the image.

So my question is: is it normal behavior in c++? If it is, then, how may we interpret it?

答:
If you want to capture CTRL-C in windows, you cannot capture it like linux by signal(). signal() does not handle SIGINT correctly in windows. You need to use SetConsoleCtrlHandler for this purpose.

If you don't set handler, application
may decide to ignore CTRL-C. CTRL-BREAK is always a signal, but CTRL-C
maybe be not:

CTRL+BREAK is always treated as a signal, but typical CTRL+C behavior
can be changed in three ways that prevent the handler functions from
being called:

1- The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT mode for a console's input buffer, so CTRL+C is reported as keyboard
input rather than as a signal.

2- Calling SetConsoleCtrlHandler with the NULL and TRUE arguments causes the calling process to ignore CTRL+C signals. This attribute is
inherited by child processes, but it can be enabled or disabled by any
process without affecting existing processes.

3- If a console process is being debugged and CTRL+C signals have not been disabled, the system generates a DBG_CONTROL_C exception. This
exception is raised only for the benefit of the debugger, and an
application should never use an exception handler to deal with it. If
the debugger handles the exception, an application will not notice the
CTRL+C, with one exception: alertable waits will terminate. If the
debugger passes the exception on unhandled, CTRL+C is passed to the
console process and treated as a signal, as previously discussed.

Here is the msdn document.

Body:
I have the following code. It runs infinitely after typing ctrl + c and executes the default section of code.

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    while(true){
        cout << "Enter an operator (+, -, *, /): ";
        cin >> oper;
        cout << "Enter two numbers: " << endl;
        cin >> num1 >> num2;

        switch (oper) {
            case '+':
                cout << num1 << " + " << num2 << " = " << num1 + num2;
                break;
            case '-':
                cout << num1 << " - " << num2 << " = " << num1 - num2;
                break;
            case '*':
                cout << num1 << " * " << num2 << " = " << num1 * num2;
                break;
            case '/':
                cout << num1 << " / " << num2 << " = " << num1 / num2;
                break;
            default:
                // operator is doesn't match any case constant (+, -, *, /)
                cout << "Error! The operator is not correct";
                break;
        }
        cout<<endl;
    }
    return 0;
}

The result after typing ctrl + c is as shown in the image.

So my question is: is it normal behavior in c++? If it is, then, how may we interpret it?


问:
LateError (LateInitializationError: Field 'customTypeSchemas' has not been initialized.) Amplify Plugins Error
I am trying to connect Amplify Api to my project and keep getting an error that reads LateError (LateInitializationError: Field 'customTypeSchemas' has not been initialized.) (Screenshot of the error is provided after the code snippet) which I take to mean that in the code that Amplify provided me there is a line somewhere that has late prefix for customTypeSchemas Field, which I can't find.

This is where I am initializing Amplify.

```<code>@override
void initState() {
  super.initState();
  _configureAmplify();
}

void _configureAmplify() async {
  if (!Amplify.isConfigured) {
    await Amplify.addPlugins([
      AmplifyDataStore(modelProvider: ModelProvider.instance),
      AmplifyAPI(),
    ]);

    try {
      await Amplify.configure(amplifyconfig);
    } catch (e) {
      print(e.toString());
    }
  }
}
</code>```

Screenshot of the error

Here is my pubspec.yaml dependencies

```<code>dependencies:
  amplify_api: ^0.3.2
  amplify_datastore: ^0.3.2
  amplify_flutter: ^0.3.2
  bloc: ^8.0.2
  cupertino_icons: ^1.0.2
  flutter:
    sdk: flutter
  flutter_bloc: ^8.0.1
</code>```

This is what's in the ModelProvider.dart that Amplify downloaded.

```<code>/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// ignore_for_file: public_member_api_docs

import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart';

import 'Todo.dart';

export 'Todo.dart';

class ModelProvider extends ModelProviderInterface {
  @override
  String version = "d960b875068d46ff04d68879d96cc042";
  @override
  List<ModelSchema> modelSchemas = [Todo.schema];
  static final ModelProvider _instance = ModelProvider();

  static ModelProvider get instance => _instance;

  @override
  ModelType getModelTypeByModelName(String modelName) {
    switch (modelName) {
      case "Todo":
        {
          return Todo.classType;
        }
      default:
        {
          throw Exception("Failed to find model in model provider for model name: " + modelName);
        }
    }
  }
}
</code>```

I did accidentally installed amplify_core: ^0.3.2, which I remove and ran flutter clean and, in ios folder, pod cache clean --all.

Steps to reproduce the problem:

Create flutter project

Add Amplify to your project

Add Database plugin

Add Api to your project

Try adding api plugin and run the app in iOS Simulator.

I am relatively new to programming and StackOverflow, so please excuse any mistakes I may have made in this post. Let me know if you need more info or you want to try something out.

Thanks in advance.

答:
I recently observed that error after upgrading to flutter 2.10

I was able to fix it by adding the below override method to my model provider class

  @override
    List<ModelSchema> customTypeSchemas = [];
```
<p>After adding that, your model should look like the one below</p>
<pre class="lang-dart prettyprint-override"><code>   /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// NOTE: This file is generated and may not follow lint rules defined in your app
// Generated files can be excluded from analysis in analysis_options.yaml
// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis

// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code

import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart';
import 'Todo.dart';

export 'Todo.dart';

class ModelProvider implements ModelProviderInterface {
  @override
  String version = "d960b875068d46ff04d68879d96cc042";
  @override
  List<ModelSchema> modelSchemas = [Todo.schema];
  static final ModelProvider _instance = ModelProvider();

  static ModelProvider get instance => _instance;

  ModelType getModelTypeByModelName(String modelName) {
    switch (modelName) {
      case "Todo":
        {
          return Todo.classType;
        }
        break;
      default:
        {
          throw Exception(
              "Failed to find model in model provider for model name: " +
                  modelName);
        }
    }
  }

  @override
  List<ModelSchema> customTypeSchemas = [];
}

</code>```

Body:
I am trying to connect Amplify Api to my project and keep getting an error that reads LateError (LateInitializationError: Field 'customTypeSchemas' has not been initialized.) (Screenshot of the error is provided after the code snippet) which I take to mean that in the code that Amplify provided me there is a line somewhere that has late prefix for customTypeSchemas Field, which I can't find.

This is where I am initializing Amplify.

@override
void initState() {
  super.initState();
  _configureAmplify();
}

void _configureAmplify() async {
  if (!Amplify.isConfigured) {
    await Amplify.addPlugins([
      AmplifyDataStore(modelProvider: ModelProvider.instance),
      AmplifyAPI(),
    ]);

    try {
      await Amplify.configure(amplifyconfig);
    } catch (e) {
      print(e.toString());
    }
  }
}

Screenshot of the error

Here is my pubspec.yaml dependencies

dependencies:
  amplify_api: ^0.3.2
  amplify_datastore: ^0.3.2
  amplify_flutter: ^0.3.2
  bloc: ^8.0.2
  cupertino_icons: ^1.0.2
  flutter:
    sdk: flutter
  flutter_bloc: ^8.0.1

This is what's in the ModelProvider.dart that Amplify downloaded.

/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// ignore_for_file: public_member_api_docs

import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart';

import 'Todo.dart';

export 'Todo.dart';

class ModelProvider extends ModelProviderInterface {
  @override
  String version = "d960b875068d46ff04d68879d96cc042";
  @override
  List<ModelSchema> modelSchemas = [Todo.schema];
  static final ModelProvider _instance = ModelProvider();

  static ModelProvider get instance => _instance;

  @override
  ModelType getModelTypeByModelName(String modelName) {
    switch (modelName) {
      case "Todo":
        {
          return Todo.classType;
        }
      default:
        {
          throw Exception("Failed to find model in model provider for model name: " + modelName);
        }
    }
  }
}

I did accidentally installed amplify_core: ^0.3.2, which I remove and ran flutter clean and, in ios folder, pod cache clean --all.

Steps to reproduce the problem:

Create flutter project

Add Amplify to your project

Add Database plugin

Add Api to your project

Try adding api plugin and run the app in iOS Simulator.

I am relatively new to programming and StackOverflow, so please excuse any mistakes I may have made in this post. Let me know if you need more info or you want to try something out.

Thanks in advance.

Body:
I recently observed that error after upgrading to flutter 2.10

I was able to fix it by adding the below override method to my model provider class

  @override
    List<ModelSchema> customTypeSchemas = [];

After adding that, your model should look like the one below

   /*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
*  http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

// NOTE: This file is generated and may not follow lint rules defined in your app
// Generated files can be excluded from analysis in analysis_options.yaml
// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis

// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code

import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart';
import 'Todo.dart';

export 'Todo.dart';

class ModelProvider implements ModelProviderInterface {
  @override
  String version = "d960b875068d46ff04d68879d96cc042";
  @override
  List<ModelSchema> modelSchemas = [Todo.schema];
  static final ModelProvider _instance = ModelProvider();

  static ModelProvider get instance => _instance;

  ModelType getModelTypeByModelName(String modelName) {
    switch (modelName) {
      case "Todo":
        {
          return Todo.classType;
        }
        break;
      default:
        {
          throw Exception(
              "Failed to find model in model provider for model name: " +
                  modelName);
        }
    }
  }

  @override
  List<ModelSchema> customTypeSchemas = [];
}


问:
How to mark classes as Obsolete on UML
I have a few classes on my UML diagram which should not be used, but still available.
Is there any way to mark these classes as obsolete?

I've seen <> notation somewhere, but can not find how to use it in MS Visio 2003.

And another question. Should these classes be on UML diagram at all? I can imagine answer on this question would be on "per case" basis, but I'm interested in hearing general opinions. And if you put obsolete classes on your UML diagrams, why you did it? or why not?

Thanks!

答:
It's not clear to me what you mean by " should not be used, but still available.". If they need to stay in the diagram but you want to visualize that they are now obsolete you can create a new stereotype <> and use it to annotate the obsolete classes.

If you don't really need them in the diagram then use a version control system for models as duffymo suggested. A list of version control tools for modeling elements can be founde here

Title: How to mark classes as Obsolete on UML


问:
Create custom sections in OctoberCms backend forms
I am trying to create a new layout in octobercms backend and I need to put fields in different areas.

I have followed the example of default.htm and form-with-sidebar.htm to create my own layout and add a custom 'placeholder' to put the controls in.

The layout appears to be working with fields, tabs and secondaryTabs sections but when I add a custom section e.g. controls to the yaml file I am not able to render them in place.

I know I am missing something here, but I cant figure out what.

Here is an example of the yaml file and the layout

yaml

```<code>fields:
    name:
        label: Name
        span: full
        required: 1
        type: text
    section1:
        label: Options
        span: full
        hidden: 1
        type: section
    toolbar:
        span: full
        cssClass: collapse-visible
        path: edit_toolbar
        type: partial

controls:
    fields:
        is_active:
            label: Active
            span: auto
            type: switch
            comment: 'Activate location to make it visible in search and other pages'
        is_focused:
            label: Focus
            span: auto
            type: switch
            comment: 'Display element larger than others'
</code>```

layout.htm

```<code><!DOCTYPE html>
<html lang="<?= App::getLocale() ?>" class="no-js <?= $this->makeLayoutPartial('browser_detector') ?>">
<head>
    <?= $this->makeLayoutPartial('head') ?>
    <?= $this->fireViewEvent('backend.layout.extendHead', ['layout' => 'default.htm']) ?>
</head>
<body class="<?= $this->bodyClass ?>">
<div id="layout-canvas">
    <div class="layout">
        ...

                            <div class="layout-row">
                                <?= Block::placeholder('controls') ?>
                            </div>
        ...

    </div>
</div>

<!-- Flash Messages -->
<div id="layout-flash-messages"><?= $this->makeLayoutPartial('flash_messages') ?></div>

</body>
</html>
</code>```

答:
There is one miss understanding in the forms config_form.yaml.

You are thinking as if you add controls: it will be treated as placeholder but it will not as form can have only definitions about fields

fields : which are outer fields

tabs -> fields : which are primary tab fields

secondaryTabs -> fields : which are second level of tabs after primary tad fields

Now if you want to render these fields in different locations you can, but you need to do it manually.

if you think you need to have a different section for controls just add those fields to the secondaryTabs

fields:
    name:
        label: Name
        span: full
        required: 1
        type: text

secondaryTabs: <- control fields
    fields:
        is_active:
            label: Active
            span: auto
            type: switch
            comment: 'Activate location to make it visible in search and other pages'
```
<blockquote>
<p><code>One tip:</code> If you do not add <code>tab</code> property in <code>field definition</code> (for ex: <code>is_active</code> here), fields will be rendered in the second section but will not create the tab and render in place.</p>
</blockquote>
<p>now to render these <code>control/secondaryTab fields</code></p>
<pre class="lang-php prettyprint-override"><code><div class="layout-row">
    <?= $this->formRenderSecondaryTabs() ?>
    <!-- ^ this will render your `control/secondaryTab fields` -->
</div>
</code>```

same ways you can render other fields of the form.

<?= $this->formRenderOutsideFields() ?> // <- to render main fields -->
<?= $this->formRenderPrimaryTabs() ?>   //
<?= Form::close() ?>
```

if you still have any doubt please comment.

Body:
I am trying to create a new layout in octobercms backend and I need to put fields in different areas.

I have followed the example of default.htm and form-with-sidebar.htm to create my own layout and add a custom 'placeholder' to put the controls in.

The layout appears to be working with fields, tabs and secondaryTabs sections but when I add a custom section e.g. controls to the yaml file I am not able to render them in place.

I know I am missing something here, but I cant figure out what.

Here is an example of the yaml file and the layout

yaml

fields:
    name:
        label: Name
        span: full
        required: 1
        type: text
    section1:
        label: Options
        span: full
        hidden: 1
        type: section
    toolbar:
        span: full
        cssClass: collapse-visible
        path: edit_toolbar
        type: partial

controls:
    fields:
        is_active:
            label: Active
            span: auto
            type: switch
            comment: 'Activate location to make it visible in search and other pages'
        is_focused:
            label: Focus
            span: auto
            type: switch
            comment: 'Display element larger than others'

layout.htm

<!DOCTYPE html>
<html lang="<?= App::getLocale() ?>" class="no-js <?= $this->makeLayoutPartial('browser_detector') ?>">

    <?= $this->makeLayoutPartial('head') ?>
    <?= $this->fireViewEvent('backend.layout.extendHead', ['layout' => 'default.htm']) ?>

<body class="<?= $this->bodyClass ?>">

        ...

                                <?= Block::placeholder('controls') ?>

        ...

<?= $this->makeLayoutPartial('flash_messages') ?>

Body:
There is one miss understanding in the forms config_form.yaml.

You are thinking as if you add controls: it will be treated as placeholder but it will not as form can have only definitions about fields

fields : which are outer fields

tabs -> fields : which are primary tab fields

secondaryTabs -> fields : which are second level of tabs after primary tad fields

Now if you want to render these fields in different locations you can, but you need to do it manually.

if you think you need to have a different section for controls just add those fields to the secondaryTabs

fields:
    name:
        label: Name
        span: full
        required: 1
        type: text

secondaryTabs: <- control fields
    fields:
        is_active:
            label: Active
            span: auto
            type: switch
            comment: 'Activate location to make it visible in search and other pages'

One tip: If you do not add tab property in field definition (for ex: is_active here), fields will be rendered in the second section but will not create the tab and render in place.

now to render these control/secondaryTab fields

<div class="layout-row">
    <?= $this->formRenderSecondaryTabs() ?>
    <!-- ^ this will render your `control/secondaryTab fields` -->
</div>

same ways you can render other fields of the form.

<?= $this->formRenderOutsideFields() ?> // <- to render main fields -->
<?= $this->formRenderPrimaryTabs() ?>   // <!-- <- to render primary tabs fields

just make sure you are rendering fields inside, the form so they can submit values.

<?= Form::open() ?>
<!-- Here -->
<?= Form::close() ?>

if you still have any doubt please comment.


问:
Getting count of distinct column value grouped to another column
My select below gives the following result

```<code>SELECT
    Fruit
  , Lot
  , rank() over (partition by Fruit ORDER BY Lot) as [Rank]
FROM Fruit_Basket
</code>```

Fruit
Lot
Rank

Banana
1140
1

Banana
1150
2

Apple
2630
1

Melon
1140
1

Melon
1140
1

Is there any way of getting a MAX(Rank() over...) or something similar?
I want to know the max count distinct of lots per fruit. Like below:

Count
MultipleLots

3
2

I want to do this without having to make another select or join.
I've been trying stuff like:

```<code>SELECT
    COUNT(Distinct Fruit) <-- Works of course
  , COUNT(DISTINCT Lot) OVER (Partition by Fruit) <-- Many Errors, due to no group by and distinct
  , MAX(rank() over (partition by Fruit ORDER BY Lot)) <-- Windowed functions cannot be used in the context of another windowed function or aggregate
FROM Fruit_Basket
</code>```

The only way I manage to get my result is using a Cross apply, forcing me to make another database search through the same table, which I'd prefer not to.

```<code>SELECT
    COUNT(Distinct Fruit)
  , MAX(lots)
FROM Fruit_Basket f
CROSS APPLY(SELECT COUNT(Distinct Lot) as Lots
  FROM Fruit_Basket fi
  WHERE fi.Fruit = f.Fruit
) CA
</code>```

答:
Don't have a large dataset to test with, but I think this should perform reasonably well and only access your table once.</p>
```<code>WITH cte_DistinctLot AS (
    SELECT Fruit
        ,LotCnt = COUNT(DISTINCT LOT)
    FROM Fruit_Basket
    GROUP BY Fruit
)

SELECT [Count] = COUNT(*)
    ,MaxLotCnt = MAX(LotCnt)
FROM cte_DistinctLot
</code>```

Body:
My select below gives the following result

SELECT
    Fruit
  , Lot
  , rank() over (partition by Fruit ORDER BY Lot) as [Rank]
FROM Fruit_Basket

Fruit
Lot
Rank

Banana
1140
1

Banana
1150
2

Apple
2630
1

Melon
1140
1

Melon
1140
1

Is there any way of getting a MAX(Rank() over...) or something similar?
I want to know the max count distinct of lots per fruit. Like below:

Count
MultipleLots

3
2

I want to do this without having to make another select or join.
I've been trying stuff like:

SELECT
    COUNT(Distinct Fruit) <-- Works of course
  , COUNT(DISTINCT Lot) OVER (Partition by Fruit) <-- Many Errors, due to no group by and distinct
  , MAX(rank() over (partition by Fruit ORDER BY Lot)) <-- Windowed functions cannot be used in the context of another windowed function or aggregate
FROM Fruit_Basket

The only way I manage to get my result is using a Cross apply, forcing me to make another database search through the same table, which I'd prefer not to.

SELECT
    COUNT(Distinct Fruit)
  , MAX(lots)
FROM Fruit_Basket f
CROSS APPLY(SELECT COUNT(Distinct Lot) as Lots
  FROM Fruit_Basket fi
  WHERE fi.Fruit = f.Fruit
) CA

Body:
Don't have a large dataset to test with, but I think this should perform reasonably well and only access your table once.

WITH cte_DistinctLot AS (
    SELECT Fruit
        ,LotCnt = COUNT(DISTINCT LOT)
    FROM Fruit_Basket
    GROUP BY Fruit
)

SELECT [Count] = COUNT(*)
    ,MaxLotCnt = MAX(LotCnt)
FROM cte_DistinctLot


问:
Textfields inside the .map are not lined side by side
So the text fields of name and quantity are not side by side or not in one row after I added the .map. Initially, these two text fields would show in one row, after the .map, it would not be in one row anymore.

```<code><Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
 {colorList.map((singleColor, index) => (
        <div key={index}>
          <Grid item xs={6}>
            <TextField
              label="name"
              name="name"
              type="text"
              id="name"
              required

            />
          </Grid>

          <br />

          <Grid item xs={6}>
            <TextField
              label="qty"
              name="qty"
              type="text"
            />
          </Grid>
        </div>
      ))}

</Grid>
</code>```

答:
This might work:

```<code>       <div className="row" key={index}>
          <Grid className="gridRow" item xs={6}>
            <TextField
              label="name"
              name="name"
              type="text"
              id="name"
              required
            />
          </Grid>

          <br />

          <Grid className="gridRow" item xs={6}>
            <TextField
              label="qty"
              name="qty"
              type="text"
            />
          </Grid>
        </div>
</code>```

and your css classes should be like this:

```<code>.row {
   display: flex;
}

.gridRow {
   display: inline-block;
}
</code>```

Body:
So the text fields of name and quantity are not side by side or not in one row after I added the .map. Initially, these two text fields would show in one row, after the .map, it would not be in one row anymore.

<Grid container rowSpacing={1} columnSpacing={{ xs: 1, sm: 2, md: 3 }}>
 {colorList.map((singleColor, index) => (

          <Grid item xs={6}>
            <TextField
              label="name"
              name="name"
              type="text"
              id="name"
              required

            />
          </Grid>

          <Grid item xs={6}>
            <TextField
              label="qty"
              name="qty"
              type="text"
            />
          </Grid>

      ))}

</Grid>

Body:
This might work:

       <div className="row" key={index}>
          <Grid className="gridRow" item xs={6}>
            <TextField
              label="name"
              name="name"
              type="text"
              id="name"
              required
            />
          </Grid>

          <br />

          <Grid className="gridRow" item xs={6}>
            <TextField
              label="qty"
              name="qty"
              type="text"
            />
          </Grid>
        </div>

and your css classes should be like this:

.row {
   display: flex;
}

.gridRow {
   display: inline-block;
}


问:
Converting GeoJSON into a flat JSON with jq
Let's say I have the following GeoJSON file:

{
  "type": "FeatureCollection",
  "name": "geojson",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "id": 1,
        "value1": 4.7557783e-06,
        "value2": 0
      },
      "geometry": null
    },
    {
      "type": "Feature",
      "properties": {
        "id": 1,
        "value1": 1.4931199e-05,
        "value2": 5
      },
      "geometry": null
    }
  ]
}
```
<p>I know that with the line <code>cat file.geojson | jq '.features[].properties'</code> I can get the following result:</p>
<pre class="lang-json prettyprint-override"><code>{
  "id": 1,
  "value1": 4.7557783e-06,
  "value2": 0
}
{
  "id": 1,
  "value1": 1.4931199e-05,
  "value2": 5
}
</code>```

However, I'd like to have this result inside an array like the following:

[
  {
    "id": 1,
    "value1": 4.7557783e-06,
    "value2": 0
  },
  {
    "id": 1,
    "value1": 1.4931199e-05,
    "value2": 5
  }
]
```

How can I add the brackets [] and the proper commas , with jq to form this last flat JSON file?

答:
You could wrap your whole filter into brackets

jq '[.features[].properties]' file.geojson
```
<p>Demo</p>
<p>Or take advantage of the fact that <code>.features</code> is already an array and just <code>map</code> its contents.</p>
<pre class="lang-sh prettyprint-override"><code>jq '.features | map(.properties)' file.geojson
</code>```

Demo

Both output

[
  {
    "id": 1,
    "value1": 4.7557783e-06,
    "value2": 0
  },
  {
    "id": 1,
    "value1": 1.4931199e-05,
    "value2": 5
  }
]
```

Body:
Let's say I have the following GeoJSON file:

{
  "type": "FeatureCollection",
  "name": "geojson",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "id": 1,
        "value1": 4.7557783e-06,
        "value2": 0
      },
      "geometry": null
    },
    {
      "type": "Feature",
      "properties": {
        "id": 1,
        "value1": 1.4931199e-05,
        "value2": 5
      },
      "geometry": null
    }
  ]
}

I know that with the line cat file.geojson | jq '.features[].properties' I can get the following result:

{
  "id": 1,
  "value1": 4.7557783e-06,
  "value2": 0
}
{
  "id": 1,
  "value1": 1.4931199e-05,
  "value2": 5
}

However, I'd like to have this result inside an array like the following:

[
  {
    "id": 1,
    "value1": 4.7557783e-06,
    "value2": 0
  },
  {
    "id": 1,
    "value1": 1.4931199e-05,
    "value2": 5
  }
]

How can I add the brackets [] and the proper commas , with jq to form this last flat JSON file?

Body:
You could wrap your whole filter into brackets

jq '[.features[].properties]' file.geojson

Demo

Or take advantage of the fact that .features is already an array and just map its contents.

jq '.features | map(.properties)' file.geojson

Demo

Both output

[
  {
    "id": 1,
    "value1": 4.7557783e-06,
    "value2": 0
  },
  {
    "id": 1,
    "value1": 1.4931199e-05,
    "value2": 5
  }
]


问:
Error in If-Else statement for Apple Script to resurface 1 year old notes
I'm trying to create an Apple Script that resurfaces a note from a year ago.

This is my code thus far:

```<code>set today to current date
set day of today to 1
set time of today to 0
set throwback to today - (365 * days)
tell application "Notes"
    tell account "iCloud"
        tell folder "Notes"
            if exists (note whose creation date is throwback) then
                show (every note whose creation date is throwback)
            else
                display dialog "No notes from this day a year ago, check back in tomorrow!"
            end if
        end tell
    end tell
end tell
</code>```

I keep getting a script error that states "Can’t get note whose creation date = date "Monday, February 1, 2021 at 12:00:00 AM"."

But in the case that it cannot get a note, I'd like it to display the dialog written in the code above. When the if statement fails why does it not go through with the else statement?

Thanks!

答:
You have to check for multiple notes (plural)</p>
```<code>if exists (notes whose creation date is throwback) then
</code>```

Body:
I'm trying to create an Apple Script that resurfaces a note from a year ago.

This is my code thus far:

set today to current date
set day of today to 1
set time of today to 0
set throwback to today - (365 * days)
tell application "Notes"
    tell account "iCloud"
        tell folder "Notes"
            if exists (note whose creation date is throwback) then
                show (every note whose creation date is throwback)
            else
                display dialog "No notes from this day a year ago, check back in tomorrow!"
            end if
        end tell
    end tell
end tell

I keep getting a script error that states "Can’t get note whose creation date = date "Monday, February 1, 2021 at 12:00:00 AM"."

But in the case that it cannot get a note, I'd like it to display the dialog written in the code above. When the if statement fails why does it not go through with the else statement?

Thanks!

Body:
You have to check for multiple notes (plural)

if exists (notes whose creation date is throwback) then


问:
How to center navigation bar items CSS
I have a navigation bar that it spanning the entire page's width. I've also added a jQuery script so that it changes to position:fixed after scrolling for a bit, but I don't think that will influence this issue.

My issue is that I can't get the navigation bar
's to center. I've tried countless things I've found on the internet, and even downloaded some templates to splice in. No luck. I'm sure I'm just missing something, but I'd like the
's to go smack-dab in the middle of the navbar, but everything I've tried either makes them slightly off, floats them to the left, or makes them not resize properly.

Here's my HTML:

```<code><!doctype html>

<html lang="en">
    <head>
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="script.js" type="text/javascript"></script>
    </head>

    <body>
        <h1>Blah blah blah</h1>

        <!--START NAVBAR-->
        <div class="nav">
            <ul>
                <li><a>Home</a></li>
                <li><a>Home</a></li>
                <li><a>Home</a></li>
            </ul>
        </div>
        <!--STOP NAVBAR-->

        <div class="content">
            <p>
            Lorem ipsum dolor sit amet...
            </p>
            <p>

            Nullam pellentesque nunc luctus...
            </p><p>
            Donec sodales fermentum orci...
            </p><p>
            Ut venenatis tellus ...
            </p><p>
            Nullam quis molestie nunc...

            </p>
        </div>

    </body>
</code>```

And the CSS:

```<code>body{
background-image:url("woodPatternShadow.png");
background-size:75% auto;
padding:0;
font-family:"Verdana";
}

.nav{
height:40px;
background-color:rgba(0,0,0,0.25);
left:0;
right:0;
box-shadow: inset 0 3px rgba(255, 255, 255, 0.4), inset 0 10px 4px rgba(255, 255, 255, 0.3),inset 0 10px 20px rgba(255,255,255,0.25), inset 0 -15px 30px rgba(28,0,0,0.3);
border:1px solid rgba(0,0,0,0.1);
margin:0;
position:absolute;
}

#fixNav{
position:fixed;
top:0px;
}

.nav ul{
}

.nav ul li{
}

.nav ul li a{
}

.content{
background-color:white;
border-radius:20px;
padding:10px;
width:70%;
margin:100px auto 0;
}
</code>```

The empty selectors are the places where I can't figure it out.

Can someone clear this up for me?

答:
just add this

nav {
    background-color: rgb(0, 0, 0);
    overflow: hidden;
    font-family: consolas;
    align-items: center;
}
nav a {
    text-decoration: none;
    padding: 20px;
    text-align: center;
    float: center;
    color: white;
    margin-left: auto;
    margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav align="center">
        Home
        Videos
        Resources
        Projects
        About Us
    </nav></code>```

Title: How to center navigation bar items CSS

Body:
I have a navigation bar that it spanning the entire page's width. I've also added a jQuery script so that it changes to position:fixed after scrolling for a bit, but I don't think that will influence this issue.

My issue is that I can't get the navigation bar
's to center. I've tried countless things I've found on the internet, and even downloaded some templates to splice in. No luck. I'm sure I'm just missing something, but I'd like the
's to go smack-dab in the middle of the navbar, but everything I've tried either makes them slightly off, floats them to the left, or makes them not resize properly.

Here's my HTML:

<!doctype html>

        <link rel="stylesheet" type="text/css" href="stylesheet.css">

Blah blah blah

Home

Home

Home

            Lorem ipsum dolor sit amet...

            Nullam pellentesque nunc luctus...

            Donec sodales fermentum orci...

            Ut venenatis tellus ...

            Nullam quis molestie nunc...

And the CSS:

body{
background-image:url("woodPatternShadow.png");
background-size:75% auto;
padding:0;
font-family:"Verdana";
}

.nav{
height:40px;
background-color:rgba(0,0,0,0.25);
left:0;
right:0;
box-shadow: inset 0 3px rgba(255, 255, 255, 0.4), inset 0 10px 4px rgba(255, 255, 255, 0.3),inset 0 10px 20px rgba(255,255,255,0.25), inset 0 -15px 30px rgba(28,0,0,0.3);
border:1px solid rgba(0,0,0,0.1);
margin:0;
position:absolute;
}

#fixNav{
position:fixed;
top:0px;
}

.nav ul{
}

.nav ul li{
}

.nav ul li a{
}

.content{
background-color:white;
border-radius:20px;
padding:10px;
width:70%;
margin:100px auto 0;
}

The empty selectors are the places where I can't figure it out.

Can someone clear this up for me?

Body:
just add this

nav {
    background-color: rgb(0, 0, 0);
    overflow: hidden;
    font-family: consolas;
    align-items: center;
}
nav a {
    text-decoration: none;
    padding: 20px;
    text-align: center;
    float: center;
    color: white;
    margin-left: auto;
    margin-right: auto;
}

<nav align="center">
        <a href="#">Home</a>
        <a href="#">Videos</a>
        <a href="#">Resources</a>
        <a href="#">Projects</a>
        <a href="#">About Us</a>
    </nav>


问:
Month and year picker in ionic framework
I am looking for a month and year picker for my ionic app. currently I am using http://ngcordova.com/docs/plugins/datePicker/
But I dont want the day picker in here . How to have only month and year to pick?

I am trying to get something like

答:
This is the answer to the following question.

```<code><ion-datetime displayFormat="MM/YYYY" min="1994-03-14" max="2012-12-09"></ion-datetime>
</code>```

displayFormat="MM/YYYY" you can use this for formating the Callander.

Body:
This is the answer to the following question.

<ion-datetime displayFormat="MM/YYYY" min="1994-03-14" max="2012-12-09"></ion-datetime>

displayFormat="MM/YYYY" you can use this for formating the Callander.


问:
Benchmarking approaches for fft algorithms
I'm currently working on a library that has its own internal fft (Fast Fourier Transform) library which I would like to replace with FFTW. Now, other developers are a bit concerned about the performance issues it might cause. Also the most critical part speed-wise is  the 1D convolution algorithm which deals with half-complex reals. (I'm using fftw's fftw_plan_r2r_1d).

Also, things are a bit more complicated because internally fftw uses different algorithms depending on the size of the transform.

My current idea is to generate a bunch of different length datasets. Then read them in and modify the dataset array for each iteration in a predetermined way before doing the transformation.

Or is there anything else I should know?

答:
Make sure you generate an optimal plan for FFTW for each test case. The PATIENT and EXHAUSTIVE flags can result in faster plans, but they can take a significant amount of time to get there. (Obviously you shouldn't include this time in your benchmark timing as it's one off and cacheable.)

If you only need single precision input/output data then build the single precision version of the FFTW libraries - they can be quite a bit faster then the default double precision version and are plenty accurate enough for most appilcations in e.g. signal processing and image processing.

Also when building the FFTW libraries make sure you enable SIMD if appropriate for your architecture, e.g. SSE on x86 or AltiVec on PowerPC.


问:
c++ getline() isn't waiting for input from console when called multiple times
I'm attempting to get a few user-input parameters from the console, two strings, two ints and a double. The relevant code I'm trying to use is this:

```<code>#include <string>
#include <iostream>
using namespace std;

// ...

string inputString;
unsigned int inputUInt;
double inputDouble;

// ...

cout << "Title: ";
getline(cin, inputString);
tempDVD.setTitle(inputString);

cout << "Category: ";
getline(cin, inputString);
tempDVD.setCategory(inputString);

cout << "Duration (minutes): ";
cin >> inputUInt;
tempDVD.setDuration(inputUInt);

cout << "Year: ";
cin >> inputUInt;
tempDVD.setYear(inputUInt);

cout << "Price: $";
cin >> inputDouble;
tempDVD.setPrice(inputDouble);
</code>```

However, when running the program, instead of waiting for the first inputString to be entered, the code doesn't stop until the second getline() call. Thus the console output looks like this:

Title: Category:

with the cursor appearing after category. If I input now, the program then jumps ahead to the year input, not allowing me to enter more than one string. What's happening here?

答:
The function_______ will return the last read character and will move the inside pointer one with -1 char.

Getline()

Peek()
3.flush()
4.putback()

Body:
I'm attempting to get a few user-input parameters from the console, two strings, two ints and a double. The relevant code I'm trying to use is this:

#include <string>
#include <iostream>
using namespace std;

// ...

string inputString;
unsigned int inputUInt;
double inputDouble;

// ...

cout << "Title: ";
getline(cin, inputString);
tempDVD.setTitle(inputString);

cout << "Category: ";
getline(cin, inputString);
tempDVD.setCategory(inputString);

cout << "Duration (minutes): ";
cin >> inputUInt;
tempDVD.setDuration(inputUInt);

cout << "Year: ";
cin >> inputUInt;
tempDVD.setYear(inputUInt);

cout << "Price: $";
cin >> inputDouble;
tempDVD.setPrice(inputDouble);

However, when running the program, instead of waiting for the first inputString to be entered, the code doesn't stop until the second getline() call. Thus the console output looks like this:

Title: Category:

with the cursor appearing after category. If I input now, the program then jumps ahead to the year input, not allowing me to enter more than one string. What's happening here?


问:
how to change system tablespace's extent_management in oracle
i used oracle 19c.

I'm trying to see the difference between a dictionary of tablespaces, local management.

When the first database was created, it was confirmed that the management of the SYSTEM tablespace was local.

The following query was performed when creating a new tablespace.

```<code>CREATE TABLESPACE TABLESPACE1
DATAFILE
    '/TS_DATAFILE1.dbf'
        SIZE 1024000
        AUTOEXTEND OFF
NOLOGGING
DEFAULT NOCOMPRESS STORAGE (
    INITIAL 10240
    NEXT 10240
    MINEXTENTS 2
    MAXEXTENTS 50
    PCTINCREASE 50
)
ONLINE
EXTENT MANAGEMENT
    DICTIONARY
SEGMENT SPACE MANAGEMENT MANUAL
FLASHBACK OFF;
</code>```

But the following error occurred.

ORA 12913- Cannot create dictionary managed tablespace

I know that the 19c version is created as local by default, and it seems to be necessary to change the SYSTEM tablespace to a dictionary in order to solve the above error.

But I don't know how to change it.
Please advise.

答:
When your system tablespace is already locally managed, you cannot create a tablespace that is dictionary managed.

Also check this info from oracle.

Cause: Attempt to create dictionary managed tablespace in database which has system tablespace as locally managed.

Action: Create a locally managed tablespace.

The extents of a locally managed tablespace are managed efficiently in the tablespace by the Oracle database server itself. Dictionary-managed option is
provided only for backward compatibility.

Body:
i used oracle 19c.

I'm trying to see the difference between a dictionary of tablespaces, local management.

When the first database was created, it was confirmed that the management of the SYSTEM tablespace was local.

The following query was performed when creating a new tablespace.

CREATE TABLESPACE TABLESPACE1
DATAFILE
    '/TS_DATAFILE1.dbf'
        SIZE 1024000
        AUTOEXTEND OFF
NOLOGGING
DEFAULT NOCOMPRESS STORAGE (
    INITIAL 10240
    NEXT 10240
    MINEXTENTS 2
    MAXEXTENTS 50
    PCTINCREASE 50
)
ONLINE
EXTENT MANAGEMENT
    DICTIONARY
SEGMENT SPACE MANAGEMENT MANUAL
FLASHBACK OFF;

But the following error occurred.

ORA 12913- Cannot create dictionary managed tablespace

I know that the 19c version is created as local by default, and it seems to be necessary to change the SYSTEM tablespace to a dictionary in order to solve the above error.

But I don't know how to change it.
Please advise.


问:
CMake make install fails with "error:___ was not declared in this scope"
I'm relatively new to programming and running into a huge problems after deep search without finding a proper solution. I'm working on my own research project which is dependent on CMake package developed by somebody (source code can be found on GitHub).

I’m trying to compile the files using CMake 3.22.2 on Windows 10 64-bit using MinGW32-GCC 6.3.0. However, whenever I try to execute “make install” command, I’m kind of stuck on the following errors.

```<code>[  2%] Building CXX object CMakeFiles/tn93.dir/src/TN93.cpp.obj
[  4%] Building CXX object CMakeFiles/tn93.dir/src/stringBuffer.cc.obj
[  7%] Building CXX object CMakeFiles/tn93.dir/src/tn93_shared.cc.obj
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc: In function 'int readFASTA(FILE*, char&, StringBuffer&, StringBuffer&, Vector&, Vector&, long int&, bool, Vector*, char, double)':
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:717:14: error: 'flockfile' was not declared in this scope
   flockfile(F);
              ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:722:40: error: 'getc_unlocked' was not declared in this scope
         int currentC = getc_unlocked (F);
                                        ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:724:29: error: 'feof_unlocked' was not declared in this scope
         if (feof_unlocked (F))
                             ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:834:35: error: 'funlockfile' was not declared in this scope
                     funlockfile (F);
                                   ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:860:33: error: 'funlockfile' was not declared in this scope
                   funlockfile (F);
                                 ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:874:21: error: 'funlockfile' was not declared in this scope
       funlockfile (F);
                     ^
make[2]: *** [CMakeFiles\tn93.dir\build.make:106: CMakeFiles/tn93.dir/src/tn93_shared.cc.obj] Error 1
make[1]: *** [CMakeFiles\Makefile2:100: CMakeFiles/tn93.dir/all] Error 2
make: *** [Makefile:135: all] Error 2
</code>```

Additional info, here's CMake call:

```<code>C:\Users\MaC\Downloads\New folder\tn93> cmake -G"MinGW Makefiles"
CMake Warning:
  No source or binary directory provided.  Both will be assumed to be the
  same as the current working directory, but note that this warning will
  become a fatal error in future CMake releases.

CMake Deprecation Warning at CMakeLists.txt:1 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.

-- The C compiler identification is GNU 6.3.0
-- The CXX compiler identification is GNU 6.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: C:/MinGW/bin/gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/MinGW/bin/g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Could NOT find OpenMP_C (missing: OpenMP_C_FLAGS OpenMP_C_LIB_NAMES)
-- Could NOT find OpenMP_CXX (missing: OpenMP_CXX_FLAGS OpenMP_CXX_LIB_NAMES)
-- Could NOT find OpenMP (missing: OpenMP_C_FOUND OpenMP_CXX_FOUND)
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/MaC/Downloads/New folder/tn93
</code>```

Here's file tree

```<code>├───CMakeFiles
│   ├───3.22.2
│   │   ├───CompilerIdC
│   │   │   └───tmp
│   │   └───CompilerIdCXX
│   │       └───tmp
│   ├───CMakeTmp
│   ├───fasta_diff.dir
│   │   └───src
│   ├───FindOpenMP
│   ├───NF.dir
│   ├───nucfreqsfasta.dir
│   │   └───src
│   ├───Progress
│   ├───readreduce.dir
│   │   └───src
│   ├───selectreads.dir
│   │   └───src
│   ├───seqcoverage.dir
│   │   └───src
│   ├───ShortestPathTN93.dir
│   │   └───src
│   ├───tn93-cluster.dir
│   │   └───src
│   ├───tn93.dir
│   │   └───src
│   ├───TN93SP.dir
│   └───validate_fasta.dir
│       └───src
├───data
└───src
</code>```

How do I fix this error?

答:
All the undefined/undeclared identifiers are POSIX functions. See e.g. here. They do not exist on Windows, or in C or C++ standards.

The software cannot be compiled as-is on a non-POSIX(-ish) system such as native Windows. It should be easy to run it on WSL or with Cygwin.

Body:
I'm relatively new to programming and running into a huge problems after deep search without finding a proper solution. I'm working on my own research project which is dependent on CMake package developed by somebody (source code can be found on GitHub).

I’m trying to compile the files using CMake 3.22.2 on Windows 10 64-bit using MinGW32-GCC 6.3.0. However, whenever I try to execute “make install” command, I’m kind of stuck on the following errors.

[  2%] Building CXX object CMakeFiles/tn93.dir/src/TN93.cpp.obj
[  4%] Building CXX object CMakeFiles/tn93.dir/src/stringBuffer.cc.obj
[  7%] Building CXX object CMakeFiles/tn93.dir/src/tn93_shared.cc.obj
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc: In function 'int readFASTA(FILE*, char&, StringBuffer&, StringBuffer&, Vector&, Vector&, long int&, bool, Vector*, char, double)':
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:717:14: error: 'flockfile' was not declared in this scope
   flockfile(F);
              ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:722:40: error: 'getc_unlocked' was not declared in this scope
         int currentC = getc_unlocked (F);
                                        ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:724:29: error: 'feof_unlocked' was not declared in this scope
         if (feof_unlocked (F))
                             ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:834:35: error: 'funlockfile' was not declared in this scope
                     funlockfile (F);
                                   ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:860:33: error: 'funlockfile' was not declared in this scope
                   funlockfile (F);
                                 ^
C:\Users\MaC\Downloads\New folder\tn93\src\tn93_shared.cc:874:21: error: 'funlockfile' was not declared in this scope
       funlockfile (F);
                     ^
make[2]: *** [CMakeFiles\tn93.dir\build.make:106: CMakeFiles/tn93.dir/src/tn93_shared.cc.obj] Error 1
make[1]: *** [CMakeFiles\Makefile2:100: CMakeFiles/tn93.dir/all] Error 2
make: *** [Makefile:135: all] Error 2

Additional info, here's CMake call:

C:\Users\MaC\Downloads\New folder\tn93> cmake -G"MinGW Makefiles"
CMake Warning:
  No source or binary directory provided.  Both will be assumed to be the
  same as the current working directory, but note that this warning will
  become a fatal error in future CMake releases.

CMake Deprecation Warning at CMakeLists.txt:1 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.

-- The C compiler identification is GNU 6.3.0
-- The CXX compiler identification is GNU 6.3.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: C:/MinGW/bin/gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/MinGW/bin/g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Could NOT find OpenMP_C (missing: OpenMP_C_FLAGS OpenMP_C_LIB_NAMES)
-- Could NOT find OpenMP_CXX (missing: OpenMP_CXX_FLAGS OpenMP_CXX_LIB_NAMES)
-- Could NOT find OpenMP (missing: OpenMP_C_FOUND OpenMP_CXX_FOUND)
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/MaC/Downloads/New folder/tn93

Here's file tree

├───CMakeFiles
│   ├───3.22.2
│   │   ├───CompilerIdC
│   │   │   └───tmp
│   │   └───CompilerIdCXX
│   │       └───tmp
│   ├───CMakeTmp
│   ├───fasta_diff.dir
│   │   └───src
│   ├───FindOpenMP
│   ├───NF.dir
│   ├───nucfreqsfasta.dir
│   │   └───src
│   ├───Progress
│   ├───readreduce.dir
│   │   └───src
│   ├───selectreads.dir
│   │   └───src
│   ├───seqcoverage.dir
│   │   └───src
│   ├───ShortestPathTN93.dir
│   │   └───src
│   ├───tn93-cluster.dir
│   │   └───src
│   ├───tn93.dir
│   │   └───src
│   ├───TN93SP.dir
│   └───validate_fasta.dir
│       └───src
├───data
└───src

How do I fix this error?


问:
To add a Artifacts deleted nupkg
I have permanently deleted a package from Artifacts.

Is there a way to restore it?

Now if I try to push I am getting this error:

Response status code does not indicate success: 409 (Conflict - The version 3.18.1 of Google.Protobuf has been deleted. It cannot be restored or pushed. (DevOps Activity ID: 014272E1-B940-428D-B3DF-4E67E5890D4B))

答:
To add a Artifacts deleted nupkg

I am afraid there is no such way to restore it.

According to the document Understand immutability of packages:

Once you publish a particular version of a package to a feed, that version number is permanently reserved. You cannot upload a newer revision package with that same version number, or delete it and upload a new package at the same version.

That because many package clients, including NuGet, keep a local cache of packages on your machine. Once a client has cached a particular package@version, it will return that copy on future install/restore requests. If, on the server, you replace package@version (rev 1) with a new package@version (rev 2), the client is unable to tell the difference. This can lead to indeterminate build results from different machines.

So we could not overwrite all packages that have already been uploaded, even we could not delete them and re-uploaded. To resolve this issue, you could try to upload the packages with a new version or create a new feed to save the package.

Title: To add a Artifacts deleted nupkg


问:
android dynamic TableRow with doInBackground not working?
```<code>//////  SeatLayout.java ///////////

public class SeatLayoutActivity  extends Activity
{
    private TableLayout mineField; // table layout to add mines to

    private Block blocks[][]; // blocks for mine field
    private int blockDimension = 24; // width of each block
    private int blockPadding = 2; // padding between blocks

    private int numberOfRowsInMineField = 9;
    private int numberOfColumnsInMineField = 9;

    public ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

         progressDialog = ProgressDialog.show(SeatLayoutActivity.this, "Getting data", "Loading...");
         new GetDataTask(SeatLayoutActivity.this).execute();

          setContentView(R.layout.seatlayout);
    }

     private Boolean isOnline() {
            ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ni = cm.getActiveNetworkInfo();
            if(ni != null && ni.isConnected())
                return true;

            return false;
        }

     private class GetDataTask extends AsyncTask<Void, Void, Integer> {
         private Context ctx;
         public GetDataTask(Context context) {
             ctx = context;
         }

      @Override
      protected Integer doInBackground(Void... params) {

            if(isOnline()){

                mineField = (TableLayout)findViewById(R.id.MineField);
                blocks = new Block[numberOfRowsInMineField + 2][numberOfColumnsInMineField + 2];

                //in feature below table(number of rows and columns) will based on RESET service response

                for (int row = 0; row < numberOfRowsInMineField + 2; row++)
                {
                    for (int column = 0; column < numberOfColumnsInMineField + 2; column++)
                    {
                        blocks[row][column] = new Block(ctx);
                        blocks[row][column].setDefaults();

                    }
                }

                for (int row = 1; row < numberOfRowsInMineField + 1; row++)
                {
                    TableRow tableRow = new TableRow(ctx);
                    tableRow.setLayoutParams(new LayoutParams((blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding));

                    for (int column = 1; column < numberOfColumnsInMineField + 1; column++)
                    {
                        blocks[row][column].setLayoutParams(new LayoutParams(
                                blockDimension + 2 * blockPadding,
                                blockDimension + 2 * blockPadding));
                        blocks[row][column].setPadding(blockPadding, blockPadding, blockPadding, blockPadding);
                        tableRow.addView(blocks[row][column]);
                    }
                    mineField.addView(tableRow,new TableLayout.LayoutParams(
                            (blockDimension + 2 * blockPadding) * numberOfColumnsInMineField, blockDimension + 2 * blockPadding));
                }

            }else{
                Toast.makeText(SeatLayoutActivity.this, "No connection..", Toast.LENGTH_LONG).show();
            }

          return 1;
      }

      @Override
      protected void onPostExecute(Integer result) {

        progressDialog.dismiss();
          super.onPostExecute(result);
      }
  }
}

///Block.java

package com.pxr.tutorial.xmltest;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;

public class Block extends Button
{
    private boolean isCovered; // is block covered yet
    private boolean isMined; // does the block has a mine underneath
    private boolean isFlagged; // is block flagged as a potential mine
    private boolean isQuestionMarked; // is block question marked
    private boolean isClickable; // can block accept click events
    private int numberOfMinesInSurrounding; // number of mines in nearby blocks

    public Block(Context context)
    {
        super(context);
    }

    public Block(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public Block(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    // set default properties for the block
    public void setDefaults()
    {
        isCovered = true;
        isMined = false;
        isFlagged = false;
        isQuestionMarked = false;
        isClickable = true;
        numberOfMinesInSurrounding = 0;

        this.setBackgroundResource(R.drawable.square_blue);
        setBoldFont();
    }

    // mark the block as disabled/opened
    // update the number of nearby mines
    public void setNumberOfSurroundingMines(int number)
    {
        this.setBackgroundResource(R.drawable.square_grey);

        updateNumber(number);
    }

    // set mine icon for block
    // set block as disabled/opened if false is passed
    public void setMineIcon(boolean enabled)
    {
        this.setText("M");

        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
            this.setTextColor(Color.RED);
        }
        else
        {
            this.setTextColor(Color.BLACK);
        }
    }

    // set mine as flagged
    // set block as disabled/opened if false is passed
    public void setFlagIcon(boolean enabled)
    {
        this.setText("F");

        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
            this.setTextColor(Color.RED);
        }
        else
        {
            this.setTextColor(Color.BLACK);
        }
    }

    // set mine as question mark
    // set block as disabled/opened if false is passed
    public void setQuestionMarkIcon(boolean enabled)
    {
        this.setText("?");

        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
            this.setTextColor(Color.RED);
        }
        else
        {
            this.setTextColor(Color.BLACK);
        }
    }

    // set block as disabled/opened if false is passed
    // else enable/close it
    public void setBlockAsDisabled(boolean enabled)
    {
        if (!enabled)
        {
            this.setBackgroundResource(R.drawable.square_grey);
        }
        else
        {
            this.setBackgroundResource(R.drawable.square_blue);
        }
    }

    // clear all icons/text
    public void clearAllIcons()
    {
        this.setText("");
    }

    // set font as bold
    private void setBoldFont()
    {
        this.setTypeface(null, Typeface.BOLD);
    }

    // uncover this block
    public void OpenBlock()
    {
        // cannot uncover a mine which is not covered
        if (!isCovered)
            return;

        setBlockAsDisabled(false);
        isCovered = false;

        // check if it has mine
        if (hasMine())
        {
            setMineIcon(false);
        }
        // update with the nearby mine count
        else
        {
            setNumberOfSurroundingMines(numberOfMinesInSurrounding);
        }
    }

    // set text as nearby mine count
    public void updateNumber(int text)
    {
        if (text != 0)
        {
            this.setText(Integer.toString(text));

            // select different color for each number
            // we have already skipped 0 mine count
            switch (text)
            {
                case 1:
                    this.setTextColor(Color.BLUE);
                    break;
                case 2:
                    this.setTextColor(Color.rgb(0, 100, 0));
                    break;
                case 3:
                    this.setTextColor(Color.RED);
                    break;
                case 4:
                    this.setTextColor(Color.rgb(85, 26, 139));
                    break;
                case 5:
                    this.setTextColor(Color.rgb(139, 28, 98));
                    break;
                case 6:
                    this.setTextColor(Color.rgb(238, 173, 14));
                    break;
                case 7:
                    this.setTextColor(Color.rgb(47, 79, 79));
                    break;
                case 8:
                    this.setTextColor(Color.rgb(71, 71, 71));
                    break;
                case 9:
                    this.setTextColor(Color.rgb(205, 205, 0));
                    break;
            }
        }
    }

    // set block as a mine underneath
    public void plantMine()
    {
        isMined = true;
    }

    // mine was opened
    // change the block icon and color
    public void triggerMine()
    {
        setMineIcon(true);
        this.setTextColor(Color.RED);
    }

    // is block still covered
    public boolean isCovered()
    {
        return isCovered;
    }

    // does the block have any mine underneath
    public boolean hasMine()
    {
        return isMined;
    }

    // set number of nearby mines
    public void setNumberOfMinesInSurrounding(int number)
    {
        numberOfMinesInSurrounding = number;
    }

    // get number of nearby mines
    public int getNumberOfMinesInSorrounding()
    {
        return numberOfMinesInSurrounding;
    }

    // is block marked as flagged
    public boolean isFlagged()
    {
        return isFlagged;
    }

    // mark block as flagged
    public void setFlagged(boolean flagged)
    {
        isFlagged = flagged;
    }

    // is block marked as a question mark
    public boolean isQuestionMarked()
    {
        return isQuestionMarked;
    }

    // set question mark for the block
    public void setQuestionMarked(boolean questionMarked)
    {
        isQuestionMarked = questionMarked;
    }

    // can block receive click event
    public boolean isClickable()
    {
        return isClickable;
    }

    // disable block for receive click events
    public void setClickable(boolean clickable)
    {
        isClickable = clickable;
    }
}
</code>```

答: First thing is that this code will not compile.. because your trying to do UI related stuff in Background thread which has nothing to do with the UI.. adding view and showing toast should be done in UI thread, i mean in postExecute()


问:
Copy values from a sheet to another sheet when checkbox is checked using Google Script
I have an onEdit function for my Google Sheet where when a checkbox in column X of the source sheet is checked, it will copy the values of the cells in column Y and Z, then paste them into column A and B of the destination sheet. It worked fine previously but it suddenly stopped working and I can't seem to find the problem. I've tried adding a trigger for it to my Script Editor project as well, but nothing happens when I check the checkbox, and there is no error message. I'm quite new to this so any help is much appreciated.

Here's the code that I've been using:

```<code>function onEdit(e) {
  const src = e.source.getActiveSheet();
  const r = e.range;
  if(src.getName() !="Source" || r.columnStart != 24 || r.rowStart == 1,2) return;
  const dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Destination");

src.getRange(r.rowStart,25,1,2).copyTo((dest.getRange(dest.getLastRow()+1,1,1,2)),SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
}
</code>```

答:
I believe your goal is as follows.

When the ckeckbox of the column "X" is checked, you want to copy the values of columns "Y" and "Z" from "Source" sheet to "Destination" sheet.

Although, unfortunately, I cannot understand the script of It worked fine previously, when your showing script is modified, how about the following modification?

Modified script:

function onEdit(e) {
  const src = e.source.getActiveSheet();
  const r = e.range;
  if (src.getName() != "Source" || r.columnStart != 24 || r.rowStart <= 2 || !r.isChecked()) return;
  const dest = e.source.getSheetByName("Destination");
  src.getRange(r.rowStart, 25, 1, 2).copyTo((dest.getRange(dest.getLastRow() + 1, 1, 1, 2)), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}
```

I thought that you wanted to do r.rowStart == 1,2 as r.rowStart <= 2.

In order to check the checkbox, isChecked() is used.

Reference:

isChecked()

Body:
I have an onEdit function for my Google Sheet where when a checkbox in column X of the source sheet is checked, it will copy the values of the cells in column Y and Z, then paste them into column A and B of the destination sheet. It worked fine previously but it suddenly stopped working and I can't seem to find the problem. I've tried adding a trigger for it to my Script Editor project as well, but nothing happens when I check the checkbox, and there is no error message. I'm quite new to this so any help is much appreciated.

Here's the code that I've been using:

function onEdit(e) {
  const src = e.source.getActiveSheet();
  const r = e.range;
  if(src.getName() !="Source" || r.columnStart != 24 || r.rowStart == 1,2) return;
  const dest = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Destination");

src.getRange(r.rowStart,25,1,2).copyTo((dest.getRange(dest.getLastRow()+1,1,1,2)),SpreadsheetApp.CopyPasteType.PASTE_VALUES,false);
}

Body:
I believe your goal is as follows.

When the ckeckbox of the column "X" is checked, you want to copy the values of columns "Y" and "Z" from "Source" sheet to "Destination" sheet.

Although, unfortunately, I cannot understand the script of It worked fine previously, when your showing script is modified, how about the following modification?

Modified script:

function onEdit(e) {
  const src = e.source.getActiveSheet();
  const r = e.range;
  if (src.getName() != "Source" || r.columnStart != 24 || r.rowStart <= 2 || !r.isChecked()) return;
  const dest = e.source.getSheetByName("Destination");
  src.getRange(r.rowStart, 25, 1, 2).copyTo((dest.getRange(dest.getLastRow() + 1, 1, 1, 2)), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
}

I thought that you wanted to do r.rowStart == 1,2 as r.rowStart <= 2.

In order to check the checkbox, isChecked() is used.

Reference:

isChecked()


问:
How can i install pygame on my internet not connected computer?
i'm trying to install pygame package on my computer which one is not connected to internet.

(env : windows10, python 3.9(anaconda))

so i downloaded a "pygame-2.1.2.tar" file from www.pypi.org and then tried to install it

from cmd with "python setup.py install" commend.

then it shows error message like below

```<code>    ===============================================================================

    (base) C:\pythonpackage\pygame-2.1.2>python setup.py install

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using WINDOWS configuration...

    Making dir :prebuilt_downloads:
    Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip
    d561079ec622b0bab5a9e02976f5d540b0622da

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/CompileWindows
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 174, in
    _new_conn
        conn = connection.create_connection(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\connection.py", line 73,
    in create_connection
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
      File "C:\ProgramData\Anaconda3\lib\socket.py", line 954, in getaddrinfo
        for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    socket.gaierror: [Errno 11002] getaddrinfo failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 699,
    in urlopen
        httplib_response = self._make_request(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 382,
    in _make_request
        self._validate_conn(conn)
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 1010,
    in _validate_conn
        conn.connect()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 358, in
    connect
        conn = self._new_conn()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 186, in
    _new_conn
        raise NewConnectionError(
    urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at
    0x00000237AF075250>: Failed to establish a new connection: [Errno 11002] getaddrinfo
    failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 439, in
    send
        resp = conn.urlopen(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 755,
    in urlopen
        retries = retries.increment(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\retry.py", line 574, in
    increment
        raise MaxRetryError(_pool, url, error or ResponseError(cause))
    urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\pythonpackage\pygame-2.1.2\setup.py", line 359, in <module>
        buildconfig.config.main(AUTO_CONFIG)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config.py", line 225, in main
        deps = CFG.main(**kwds)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config_win.py", line 497, in main
        and download_win_prebuilt.ask(**download_kwargs):
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 290, in
    ask
        update(x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 273, in
    update
        download_prebuilts(download_dir, x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 124, in
    download_prebuilts
        download_sha1_unzip(url, checksum, temp_dir, 1)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 47, in
    download_sha1_unzip
        response = requests.get(url)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 75, in get
        return request('get', url, params=params, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 61, in request
        return session.request(method=method, url=url, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 542, in
    request
        resp = self.send(prep, **send_kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 655, in
    send
        r = adapter.send(request, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 516, in
    send
        raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    ===============================================================================
</code>```

please let me know how to install pygame on offline environment.

i need your help!! please~~

答:
Solution 1 (It works for me; simple but tricky)

My first suggestion is just using .whl file. You can download pygame.whl, which is another type of installation file, from another computer and move the two files to the computer with no internect connection.

You can download the files here:

.whl file for Window & Python3.9 (for example,
pygame-2.1.2-cp39-cp39-win_amd64.whl):

https://pypi.org/project/pygame/#files

Actually, .whl is a zipfile. You can unzip the .whl file then you can see three folders: pygame, pygame-2.1.2.data, and pygame-2.1.2.dist-info. You just need pygame folder.

You can copy the folder and paste it to your python project. Then you can simply import pygame. I just tried this way and it works for me. (I even tried to run an example game)

Solution 2

Another suggestion is to download pip and pygame.whl from another computer and move the two files to the computer with no internect connection.

You can download the files here:

pip (for example, pip-22.0.3.tar.gz): https://pypi.org/project/pip/#files

.whl file for Window & Python3.9 (for example,
pygame-2.1.2-cp39-cp39-win_amd64.whl):

https://pypi.org/project/pygame/#files

After downloading and moving the two files to the computer with no internect connection, you first unzip the pip-22.0.3.tar.gz and install pip by tying following command inside of the pip folder (pip also has setup.py file):

```<code>python setup.py install
</code>```

Now, pip has been installed. Then, install using the .whl file using pip in the folder that .whl file exist.

```<code>python -m pip install pygame-2.1.2-cp39-cp39-win_amd64.whl
</code>```

I hope it help you emjoy pygame.

Body:
i'm trying to install pygame package on my computer which one is not connected to internet.

(env : windows10, python 3.9(anaconda))

so i downloaded a "pygame-2.1.2.tar" file from www.pypi.org and then tried to install it

from cmd with "python setup.py install" commend.

then it shows error message like below

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

    (base) C:\pythonpackage\pygame-2.1.2>python setup.py install

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using WINDOWS configuration...

    Making dir :prebuilt_downloads:
    Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip
    d561079ec622b0bab5a9e02976f5d540b0622da

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/CompileWindows
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 174, in
    _new_conn
        conn = connection.create_connection(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\connection.py", line 73,
    in create_connection
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
      File "C:\ProgramData\Anaconda3\lib\socket.py", line 954, in getaddrinfo
        for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    socket.gaierror: [Errno 11002] getaddrinfo failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 699,
    in urlopen
        httplib_response = self._make_request(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 382,
    in _make_request
        self._validate_conn(conn)
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 1010,
    in _validate_conn
        conn.connect()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 358, in
    connect
        conn = self._new_conn()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 186, in
    _new_conn
        raise NewConnectionError(
    urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at
    0x00000237AF075250>: Failed to establish a new connection: [Errno 11002] getaddrinfo
    failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 439, in
    send
        resp = conn.urlopen(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 755,
    in urlopen
        retries = retries.increment(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\retry.py", line 574, in
    increment
        raise MaxRetryError(_pool, url, error or ResponseError(cause))
    urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\pythonpackage\pygame-2.1.2\setup.py", line 359, in <module>
        buildconfig.config.main(AUTO_CONFIG)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config.py", line 225, in main
        deps = CFG.main(**kwds)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config_win.py", line 497, in main
        and download_win_prebuilt.ask(**download_kwargs):
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 290, in
    ask
        update(x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 273, in
    update
        download_prebuilts(download_dir, x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 124, in
    download_prebuilts
        download_sha1_unzip(url, checksum, temp_dir, 1)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 47, in
    download_sha1_unzip
        response = requests.get(url)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 75, in get
        return request('get', url, params=params, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 61, in request
        return session.request(method=method, url=url, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 542, in
    request
        resp = self.send(prep, **send_kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 655, in
    send
        r = adapter.send(request, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 516, in
    send
        raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

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

please let me know how to install pygame on offline environment.

i need your help!! please~~

Body:
Solution 1 (It works for me; simple but tricky)

My first suggestion is just using .whl file. You can download pygame.whl, which is another type of installation file, from another computer and move the two files to the computer with no internect connection.

You can download the files here:

.whl file for Window & Python3.9 (for example,
pygame-2.1.2-cp39-cp39-win_amd64.whl):

https://pypi.org/project/pygame/#files

Actually, .whl is a zipfile. You can unzip the .whl file then you can see three folders: pygame, pygame-2.1.2.data, and pygame-2.1.2.dist-info. You just need pygame folder.

You can copy the folder and paste it to your python project. Then you can simply import pygame. I just tried this way and it works for me. (I even tried to run an example game)

Solution 2

Another suggestion is to download pip and pygame.whl from another computer and move the two files to the computer with no internect connection.

You can download the files here:

pip (for example, pip-22.0.3.tar.gz): https://pypi.org/project/pip/#files

.whl file for Window & Python3.9 (for example,
pygame-2.1.2-cp39-cp39-win_amd64.whl):

https://pypi.org/project/pygame/#files

After downloading and moving the two files to the computer with no internect connection, you first unzip the pip-22.0.3.tar.gz and install pip by tying following command inside of the pip folder (pip also has setup.py file):

python setup.py install

Now, pip has been installed. Then, install using the .whl file using pip in the folder that .whl file exist.

python -m pip install pygame-2.1.2-cp39-cp39-win_amd64.whl

I hope it help you emjoy pygame.