问:
Error when trying to render component in react-testing-library - got an object
I'm trying to setup some integration tests of some react components that are connected to our redux store.

Our general pattern is a const (instead of a component) which is "connect"ed with redux to the store (I think this is just background to the issue, as I have the same problem with a normal component).

I am following https://testing-library.com/docs/example-react-redux

I get this error

```<code>   console.error node_modules/react/cjs/react.development.js:172
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

  Check your code at feedback.test.js:32.
console.error node_modules/react-dom/cjs/react-dom.development.js:19814
  The above error occurred in the <Provider> component:
      in Provider (at feedback.test.js:26)
</code>```

This is my test

```<code>import React from 'react';
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import {render, getByTitle, fireEvent} from '@testing-library/react'
//import '@testing-library/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'

import {FeedbackContainer} from '../feedbackContainer'
import {defaultState, reducer} from '../../../../redux/modules/feedback'

function renderWithRedux(
  component,
  {
    initalState, store = createStore(reducer, defaultState)
  } = {}
) {
  return {
    ...render(<Provider store={store}>{component}</Provider>)
  }
}

it('increments the counter', () => {
  console.log(<FeedbackContainer/>)
  const {container} = renderWithRedux(<FeedbackContainer />) <-- line 32
})
</code>```

My container component looks like this:

```<code>import { connect } from 'react-redux';
import { Feedback } from './feedback';
import { compose, lifecycle, withHandlers } from 'recompose';
import { actions } from '../../../redux/modules/feedback';

export const mapStateToProps = (state, ownProps) => ({
// snipped state maps
});

export const mapDispatchToProps = {
// snipped functions
};

const enhance = compose(
  connect(mapStateToProps, mapDispatchToProps),
  withHandlers({
    sendFeedbackHandler: props => () => props.sendFeedback(props),
    handleResize: props => () => props.setWindowSize(),
  }),
  lifecycle({
    componentDidMount() {
      const {handleResize} = this.props
      window.addEventListener('resize',handleResize);
    },
    componentWillUnmount() {
      this.props.clearFeedback();
      const {handleResize} = this.props
      window.removeEventListener('resize', handleResize);
    },
  }),
);

export const FeedbackContainer = enhance(Feedback);
</code>```

The feedback.js looks like this:

```<code>import React from 'react';
import ReactStars from 'react-stars';

export const Feedback = (props) => {

    const ratingChanged = (rating) => {
      props.setRating(rating);
    }

    const {sendFeedbackHandler} = props

    var title = null;
    switch (props.type) {
      case "REF":
        title = "Rate this FAQ"
        break;
      default:
        title = "Rate my experience"
        break
    }

    var feebackLayout;
    var buttonClassNames = "btn btn-success btn-cons pull-right";
    if (props.apertureWidth > 768) {
      buttonClassNames += " margin-right-0px ";
      feebackLayout = (
        <div>
          <h5 className="light semi-bold text-center" style={{"margin":"0px"}}>
            {title}
          </h5>
          <div style={{"textAlign":"center"}}>
            <div data-test-id='feedback-stars' className="center" style={{"display":"inline-block","float":"none"}}>
              <ReactStars
                value={props.rating}
                count={5}
                onChange={ratingChanged}
                size={24}
                color2={'#ffd700'}
                half={false}
              />
            </div>
          </div>
        </div>
      )
    } else {
      buttonClassNames += " margin-right-14px ";
      title = "Rate this:"
      feebackLayout = (
        <div style={{"textAlign":"center"}}>
          <h5 className="light semi-bold text-center"
           style={{"margin":"0px","display":"inline","verticalAlign":"middle","paddingRight":"10px"}}>
            {title}
          </h5>
          <div style={{"textAlign":"center","display":"inline-block","verticalAlign":"middle"}}>
            <ReactStars
              value={props.rating}
              count={5}
              onChange={ratingChanged}
              size={24}
              color2={'#ffd700'}
              half={false}
            />
          </div>
        </div>
      )
    }

    return (
      <div className="card card-default feedbackCard" style={{"height": "100%","borderTopRightRadius": "2px", "borderTopLeftRadius": "2px"}}>
        <div className="card-block" style={{padding: '20px 20px 20px 20px'}}>
          <div hidden={props.feedbackSubmitted}>
            {feebackLayout}
            <div hidden={props.feedbackHidden}
             style={{"paddingTop": props.apertureWidth > 768 ? "0px" : "10px"}}>
              <div>
                <textarea
                  data-test-id='feedback-text'
                  className="form-control"
                  style={{"height":"unset"}}
                  placeholder="Add any comments"
                  rows={2}
                  onChange={event => props.setFeedback(event.target.value)}
                />
              </div>
              <div style={{paddingTop: "5px"}}>
                <button
                  data-test-id='feedback-submit'
                  className={buttonClassNames}
                  onClick={sendFeedbackHandler}
                >
                  {props.buttonText}
                </button>
              </div>
            </div>
          </div>
          <div hidden={!props.feedbackSubmitted}>
            <h5 className="light semi-bold text-center">
              {props.feedbackSubmittedMessage}
            </h5>
          </div>
        </div>
      </div>
    )
};
</code>```

If I change my test to use the underlying Feedback component rather than the container it doesn't crash (but then I don't think the store will be correctly connected as mapstatetoprops isn't going to be called.

If I console.log the components in my test they both return objects from what I can see so I don't quite understand the error.

FeedbackContainer:

```<code>{ '$$typeof': Symbol(react.element),
        type:
         { mapStateToProps: [Function],
           mapDispatchToProps: [Function: mapDispatchToProps],
           reactComponent: { [Function: WithHandlers] displayName: 'withHandlers(lifecycle(Component))' },
           mockDispatch:
            { [Function: mockConstructor]
              _isMockFunction: true,
              getMockImplementation: [Function],
              mock: [Getter/Setter],
              mockClear: [Function],
              mockReset: [Function],
              mockReturnValueOnce: [Function],
              mockReturnValue: [Function],
              mockImplementationOnce: [Function],
              mockImplementation: [Function],
              mockReturnThis: [Function],
              mockRestore: [Function] } },
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }
</code>```

Feedback:

```<code>{ '$$typeof': Symbol(react.element),
        type: [Function],
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }
</code>```

From some reading I think this could be down to some version compatabilites, this is what I have in my package.json:

```<code>"jest": "^21.2.1",
"@testing-library/jest-dom": "^4.1.0",
"@testing-library/react": "^9.1.4",
"react": "^16.8.6",
"react-dom": "^16.0.0",
"react-redux": "^5.0.5",
"redux": "^3.7.2",
"redux-saga": "^0.15.6",
</code>```

Where am I going wrong?!

答:
Please see my answer here: What is wrong with react-testing-library render function? It returns an error on certain objects</p>
```<code>expect(() =>
        render(
            <AddAssessmentFormModal
                recordDetailView={<RaDeathDecisionEditView />}
                addRecord={(record: any) => addAssessment(record)}
            />,
            {
                wrapper: () => <AppWrapper store={store} />,
            }
        )
    ).not.toThrow();
</code>```

Body:
I'm trying to setup some integration tests of some react components that are connected to our redux store.

Our general pattern is a const (instead of a component) which is "connect"ed with redux to the store (I think this is just background to the issue, as I have the same problem with a normal component).

I am following https://testing-library.com/docs/example-react-redux

I get this error

   console.error node_modules/react/cjs/react.development.js:172
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

  Check your code at feedback.test.js:32.
console.error node_modules/react-dom/cjs/react-dom.development.js:19814
  The above error occurred in the <Provider> component:
      in Provider (at feedback.test.js:26)

This is my test

import React from 'react';
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import {render, getByTitle, fireEvent} from '@testing-library/react'
//import '@testing-library/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'

import {FeedbackContainer} from '../feedbackContainer'
import {defaultState, reducer} from '../../../../redux/modules/feedback'

function renderWithRedux(
  component,
  {
    initalState, store = createStore(reducer, defaultState)
  } = {}
) {
  return {
    ...render(<Provider store={store}>{component}</Provider>)
  }
}

it('increments the counter', () => {
  console.log(<FeedbackContainer/>)
  const {container} = renderWithRedux(<FeedbackContainer />) <-- line 32
})

My container component looks like this:

import { connect } from 'react-redux';
import { Feedback } from './feedback';
import { compose, lifecycle, withHandlers } from 'recompose';
import { actions } from '../../../redux/modules/feedback';

export const mapStateToProps = (state, ownProps) => ({
// snipped state maps
});

export const mapDispatchToProps = {
// snipped functions
};

const enhance = compose(
  connect(mapStateToProps, mapDispatchToProps),
  withHandlers({
    sendFeedbackHandler: props => () => props.sendFeedback(props),
    handleResize: props => () => props.setWindowSize(),
  }),
  lifecycle({
    componentDidMount() {
      const {handleResize} = this.props
      window.addEventListener('resize',handleResize);
    },
    componentWillUnmount() {
      this.props.clearFeedback();
      const {handleResize} = this.props
      window.removeEventListener('resize', handleResize);
    },
  }),
);

export const FeedbackContainer = enhance(Feedback);

The feedback.js looks like this:

import React from 'react';
import ReactStars from 'react-stars';

export const Feedback = (props) => {

    const ratingChanged = (rating) => {
      props.setRating(rating);
    }

    const {sendFeedbackHandler} = props

    var title = null;
    switch (props.type) {
      case "REF":
        title = "Rate this FAQ"
        break;
      default:
        title = "Rate my experience"
        break
    }

    var feebackLayout;
    var buttonClassNames = "btn btn-success btn-cons pull-right";
    if (props.apertureWidth > 768) {
      buttonClassNames += " margin-right-0px ";
      feebackLayout = (

            {title}

              <ReactStars
                value={props.rating}
                count={5}
                onChange={ratingChanged}
                size={24}
                color2={'#ffd700'}
                half={false}
              />

      )
    } else {
      buttonClassNames += " margin-right-14px ";
      title = "Rate this:"
      feebackLayout = (

            {title}

            <ReactStars
              value={props.rating}
              count={5}
              onChange={ratingChanged}
              size={24}
              color2={'#ffd700'}
              half={false}
            />

      )
    }

    return (

            {feebackLayout}

 768 ? "0px" : "10px"}}>

                <textarea
                  data-test-id='feedback-text'
                  className="form-control"
                  style={{"height":"unset"}}
                  placeholder="Add any comments"
                  rows={2}
                  onChange={event => props.setFeedback(event.target.value)}
                />

                <button
                  data-test-id='feedback-submit'
                  className={buttonClassNames}
                  onClick={sendFeedbackHandler}
                >
                  {props.buttonText}
                </button>

              {props.feedbackSubmittedMessage}

    )
};

If I change my test to use the underlying Feedback component rather than the container it doesn't crash (but then I don't think the store will be correctly connected as mapstatetoprops isn't going to be called.

If I console.log the components in my test they both return objects from what I can see so I don't quite understand the error.

FeedbackContainer:

{ '$$typeof': Symbol(react.element),
        type:
         { mapStateToProps: [Function],
           mapDispatchToProps: [Function: mapDispatchToProps],
           reactComponent: { [Function: WithHandlers] displayName: 'withHandlers(lifecycle(Component))' },
           mockDispatch:
            { [Function: mockConstructor]
              _isMockFunction: true,
              getMockImplementation: [Function],
              mock: [Getter/Setter],
              mockClear: [Function],
              mockReset: [Function],
              mockReturnValueOnce: [Function],
              mockReturnValue: [Function],
              mockImplementationOnce: [Function],
              mockImplementation: [Function],
              mockReturnThis: [Function],
              mockRestore: [Function] } },
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }

Feedback:

{ '$$typeof': Symbol(react.element),
        type: [Function],
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }

From some reading I think this could be down to some version compatabilites, this is what I have in my package.json:

"jest": "^21.2.1",
"@testing-library/jest-dom": "^4.1.0",
"@testing-library/react": "^9.1.4",
"react": "^16.8.6",
"react-dom": "^16.0.0",
"react-redux": "^5.0.5",
"redux": "^3.7.2",
"redux-saga": "^0.15.6",

Where am I going wrong?!

Body:
Please see my answer here: What is wrong with react-testing-library render function? It returns an error on certain objects

expect(() =>
        render(
            <AddAssessmentFormModal
                recordDetailView={<RaDeathDecisionEditView />}
                addRecord={(record: any) => addAssessment(record)}
            />,
            {
                wrapper: () => <AppWrapper store={store} />,
            }
        )
    ).not.toThrow();


来源: stackexchange

问:
In C# string how to replace two chararacters ignoring a number
I am editing a serialized string becuase when deserilized it gives a parse error.
so from a long Serialized string I want to edit "myVar\": \"0.2 mm" with "myVar\": \"0.2"
if I use the follwoing code it works

```<code>string NewString = Serializedstring.Replace($"myVar\": \"0.2 mm", $"myVar\": \"0.2")
</code>```

but my 0.2 is a varible that may change with every occurance. so all I want is to remove mm from the string "myVar\": \"0.2 mm"

答:
If your JSON is coming in with two different formats, rather than trying to hack the JSON string into something usable, it is much safer to use a custom JsonConverter. For example:

```<code>public class MillimetreJsonConverter : JsonConverter<double>
{
    public override double Read(ref Utf8JsonReader reader, Type typeToConvert,
        JsonSerializerOptions options)
    {
        // First try to get a double, if it works then simply return it
        if(reader.TryGetDouble(out var val))
        {
            return val;
        }

        // Otherwise we get the string value e.g. "0.2 mm" and
        // do some simple string manipulation on it
        var value = reader.GetString()!;
        value = value.Replace(" mm", "");

        if(double.TryParse(value, out var result))
        {
            return result;
        }

        // If we get here, perhaps we should throw an exception?
        return 0;
    }

    public override void Write(Utf8JsonWriter writer, double value,
        JsonSerializerOptions options)
    {
        // You can fill this in if you need it
        throw new NotImplementedException();
    }
}
</code>```

Now you can modify the class to deserialise into, assuming your JSON looks like this {"myVar": "0.2 mm"},:

```<code>public class Foo
{
    [JsonConverter(typeof(MillimetreJsonConverter))]
    public double myVar { get; set; }
}
</code>```

Finally, it's simple to deserialise:

```<code>var foo = JsonSerializer.Deserialize<Foo>(json);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am editing a serialized string becuase when deserilized it gives a parse error.
so from a long Serialized string I want to edit "myVar\": \"0.2 mm" with "myVar\": \"0.2"
if I use the follwoing code it works

string NewString = Serializedstring.Replace($"myVar\": \"0.2 mm", $"myVar\": \"0.2")

but my 0.2 is a varible that may change with every occurance. so all I want is to remove mm from the string "myVar\": \"0.2 mm"

Body:
If your JSON is coming in with two different formats, rather than trying to hack the JSON string into something usable, it is much safer to use a custom JsonConverter. For example:

public class MillimetreJsonConverter : JsonConverter<double>
{
    public override double Read(ref Utf8JsonReader reader, Type typeToConvert,
        JsonSerializerOptions options)
    {
        // First try to get a double, if it works then simply return it
        if(reader.TryGetDouble(out var val))
        {
            return val;
        }

        // Otherwise we get the string value e.g. "0.2 mm" and
        // do some simple string manipulation on it
        var value = reader.GetString()!;
        value = value.Replace(" mm", "");

        if(double.TryParse(value, out var result))
        {
            return result;
        }

        // If we get here, perhaps we should throw an exception?
        return 0;
    }

    public override void Write(Utf8JsonWriter writer, double value,
        JsonSerializerOptions options)
    {
        // You can fill this in if you need it
        throw new NotImplementedException();
    }
}

Now you can modify the class to deserialise into, assuming your JSON looks like this {"myVar": "0.2 mm"},:

public class Foo
{
    [JsonConverter(typeof(MillimetreJsonConverter))]
    public double myVar { get; set; }
}

Finally, it's simple to deserialise:

var foo = JsonSerializer.Deserialize<Foo>(json);


问:
MongoDB group by and SUM by array
I'm new in mongoDB.

This is one example of record from collection:

```<code>  {
    supplier: 1,
    type: "sale",
    items: [
      {
        "_id": ObjectId("60ee82dd2131c5032342070f"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420710"),
        "itemBuySum": 10,

      },
      {
        "_id": ObjectId("60ee82dd2131c50323420713"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420714"),
        "itemBuySum": 20
      }
    ]
  }
</code>```

I need to group by TYPE field and get the SUM. This is output I need:

```<code>{
    supplier: 1,
    sales: 90,
    returns: 170
}
</code>```

please check Mongo playground for better understand. Thank you!

答:
$match - Filter documents.

$group - Group by type and add item into data array which leads to the result like:

```<code>[
  [/* data 1 */],
  [/* data 2 */]
]
</code>```

$project - Decorate output document.

3.1. First $reduce is used to flatten the nested array to a single array (from Result (2)) via $concatArrays.

3.2. Second $reduce is used to aggregate $sum the itemBuySum.

```<code>db.collection.aggregate({
  $match: {
    supplier: 1
  },

},
{
  "$group": {
    "_id": "$type",
    "supplier": {
      $first: "$supplier"
    },
    "data": {
      "$push": "$items"
    }
  }
},
{
  "$project": {
    _id: 0,
    "supplier": "$supplier",
    "type": "$_id",
    "returns": {
      "$reduce": {
        "input": {
          "$reduce": {
            input: "$data",
            initialValue: [],
            in: {
              "$concatArrays": [
                "$$value",
                "$$this"
              ]
            }
          }
        },
        "initialValue": 0,
        "in": {
          $sum: [
            "$$value",
            "$$this.itemBuySum"
          ]
        }
      }
    }
  }
})
</code>```

Sample Mongo Playground

Title: MongoDB group by and SUM by array

Body:
I'm new in mongoDB.

This is one example of record from collection:

  {
    supplier: 1,
    type: "sale",
    items: [
      {
        "_id": ObjectId("60ee82dd2131c5032342070f"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420710"),
        "itemBuySum": 10,

      },
      {
        "_id": ObjectId("60ee82dd2131c50323420713"),
        "itemBuySum": 10
      },
      {
        "_id": ObjectId("60ee82dd2131c50323420714"),
        "itemBuySum": 20
      }
    ]
  }

I need to group by TYPE field and get the SUM. This is output I need:

{
    supplier: 1,
    sales: 90,
    returns: 170
}

please check Mongo playground for better understand. Thank you!

Body:
$match - Filter documents.

$group - Group by type and add item into data array which leads to the result like:

[
  [/* data 1 */],
  [/* data 2 */]
]

$project - Decorate output document.

3.1. First $reduce is used to flatten the nested array to a single array (from Result (2)) via $concatArrays.

3.2. Second $reduce is used to aggregate $sum the itemBuySum.

db.collection.aggregate({
  $match: {
    supplier: 1
  },

},
{
  "$group": {
    "_id": "$type",
    "supplier": {
      $first: "$supplier"
    },
    "data": {
      "$push": "$items"
    }
  }
},
{
  "$project": {
    _id: 0,
    "supplier": "$supplier",
    "type": "$_id",
    "returns": {
      "$reduce": {
        "input": {
          "$reduce": {
            input: "$data",
            initialValue: [],
            in: {
              "$concatArrays": [
                "$$value",
                "$$this"
              ]
            }
          }
        },
        "initialValue": 0,
        "in": {
          $sum: [
            "$$value",
            "$$this.itemBuySum"
          ]
        }
      }
    }
  }
})

Sample Mongo Playground


问:
Is there a way to save the cutting planes from SCIP?
I am working on using SCIP to generate cutting planes for my project. I am doing so using a C++ code directly with default plugins included, modified from scip/examples/MIPsolver/src/cppmain. However the array of cutting planes is not saved. The program will be run using the command

```<code>./scipplanes [problem file]
</code>```

The affected part of my program is shown below:

```<code>/*******************
    * Problem Presolving *
    *******************/

   /* Presolve problem */
   std::cout << "=============" << std::endl;
   std::cout << "Presolve problem" << std::endl;
   std::cout << "=============" << std::endl;
   SCIP_CALL( SCIPpresolve(scip) ); //Presolve to simplify the problem
   SCIP_CALL( SCIPsetRealParam(scip, "limits/time", 60) ); //Limit of solving time in seconds

   /*************************
    * Obtain cutting planes *
    *************************/
   std::cout << "=============" << std::endl;
   std::cout << "Obtaining cutting planes" << std::endl;
   std::cout << "=============" << std::endl;

   SCIP_ROW** allcuts; //Because SCIPgetCuts outputs this kind of data (memory address/pointer)
   int n_cuts; //For for loop iteration

   SCIP_CALL( SCIPsolve(scip) );
   allcuts = SCIPgetCuts(scip); /*Documentation says that this outputs the array of cuts currently stored in the separation storage,
                                   in the form of a memory address of pointer of SCIP_ROW** */
   std::cout << "allcuts is " << allcuts << std::endl;
   n_cuts = SCIPgetNCuts(scip);
   std::cout << "n_cuts is " << n_cuts << std::endl;

</code>```

When I ran my code, I obtain n_cuts = 0, but the table of statistics shows :

```<code>time | node  | left  |LP iter|LP it/n|mem/heur|mdpt |vars |cons |rows |cuts |sepa|confs|strbr|  dualbound   | primalbound  |  gap   | compl.
60.0s|     1 |     0 | 33295 |     - |   333M |   0 |1164 |  39k|  39k| 120 | 10 |  19 |   0 | 0.000000e+00 |      --      |    Inf | unknown
</code>```

There are 120 cuts. I have double checked by running the SCIP binary and using presolve and optimize with a time limit of 60s. The results are the same when display statistics is used.

I have also tried to iterate through allcuts by doing SCIPprintRow(scip, *allcuts, NULL); , but got a segmentation fault.

Thus, I have no idea why the cutting planes are not saved. Would it be possible to offer me some advice on how to solve this problem? Thank you.

答:
I'm pretty sure that all cuts will be freed after the solve is finished (and in any case, SCIP will remove rows from time to time). If you want all the cuts that were used at any point during the solve, you should write an event handler (with event type SCIP_EVENTTYPE_ROWEVENT) that you can use to print the rows with SCIPprintRow)

There is an example of how to write your own event handler in the examples subdirectory.

Body:
I am working on using SCIP to generate cutting planes for my project. I am doing so using a C++ code directly with default plugins included, modified from scip/examples/MIPsolver/src/cppmain. However the array of cutting planes is not saved. The program will be run using the command

./scipplanes [problem file]

The affected part of my program is shown below:

/*******************
    * Problem Presolving *
    *******************/

   /* Presolve problem */
   std::cout << "=============" << std::endl;
   std::cout << "Presolve problem" << std::endl;
   std::cout << "=============" << std::endl;
   SCIP_CALL( SCIPpresolve(scip) ); //Presolve to simplify the problem
   SCIP_CALL( SCIPsetRealParam(scip, "limits/time", 60) ); //Limit of solving time in seconds

   /*************************
    * Obtain cutting planes *
    *************************/
   std::cout << "=============" << std::endl;
   std::cout << "Obtaining cutting planes" << std::endl;
   std::cout << "=============" << std::endl;

   SCIP_ROW** allcuts; //Because SCIPgetCuts outputs this kind of data (memory address/pointer)
   int n_cuts; //For for loop iteration

   SCIP_CALL( SCIPsolve(scip) );
   allcuts = SCIPgetCuts(scip); /*Documentation says that this outputs the array of cuts currently stored in the separation storage,
                                   in the form of a memory address of pointer of SCIP_ROW** */
   std::cout << "allcuts is " << allcuts << std::endl;
   n_cuts = SCIPgetNCuts(scip);
   std::cout << "n_cuts is " << n_cuts << std::endl;

When I ran my code, I obtain n_cuts = 0, but the table of statistics shows :

time | node  | left  |LP iter|LP it/n|mem/heur|mdpt |vars |cons |rows |cuts |sepa|confs|strbr|  dualbound   | primalbound  |  gap   | compl.
60.0s|     1 |     0 | 33295 |     - |   333M |   0 |1164 |  39k|  39k| 120 | 10 |  19 |   0 | 0.000000e+00 |      --      |    Inf | unknown

There are 120 cuts. I have double checked by running the SCIP binary and using presolve and optimize with a time limit of 60s. The results are the same when display statistics is used.

I have also tried to iterate through allcuts by doing SCIPprintRow(scip, *allcuts, NULL); , but got a segmentation fault.

Thus, I have no idea why the cutting planes are not saved. Would it be possible to offer me some advice on how to solve this problem? Thank you.


问:
why we need to pass Boolean value to the method
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?</p>

```<code>RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }
</code>```

答:
hmm you need to pass the boolean value because the signature of the method ask for one

and it return "nothing" since it's declared as void, it's a method, not a function / property

ContentLicense: CC BY-SA 3.0

Body:
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?

RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }


问:
Upgrading Entity Framework 4.3.1 to 5.0.0 beta 1 gives binding redirects error
My solution uses Entity Framework 4.3.1. I want to upgrade to 5.0.0 beta-1. The package manager gives the following output:

```<code>PM> Install-Package -IncludePrerelease EntityFramework
You are downloading EntityFramework from Microsoft, the license agreement to which is   available at http://go.microsoft.com/fwlink/?LinkId=242870. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'EntityFramework 5.0.0-beta1'.
Successfully removed 'EntityFramework 4.3.1' from PROJECTNAME.
Successfully added 'EntityFramework 5.0.0-beta1' to PROJECTNAME.
Failed to generate binding redirects for 'PROJECTNAME'. 'object' does not contain a definition for 'References'
Successfully uninstalled 'EntityFramework 4.3.1'.
</code>```

It looks like the upgrade completed succesfully, but I wonder how I could have prevented this error.

答:
You should enable automatic binding redirection manually. To do this:

In Visual Studio, in Solution Explorer, right-click the project and choose "Unload Project".

Add the following element to the property group (under the  tag) in XML code:

```<code><AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</code>```

The following shows an example project file with the element inserted:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{123334}</ProjectGuid>
    ...
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  ...
</Project>
</code>```

Right click the project and choose "Reload Project".

Compile your app.

List item

Install EntityFramework.

Body:
My solution uses Entity Framework 4.3.1. I want to upgrade to 5.0.0 beta-1. The package manager gives the following output:

PM> Install-Package -IncludePrerelease EntityFramework
You are downloading EntityFramework from Microsoft, the license agreement to which is   available at http://go.microsoft.com/fwlink/?LinkId=242870. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'EntityFramework 5.0.0-beta1'.
Successfully removed 'EntityFramework 4.3.1' from PROJECTNAME.
Successfully added 'EntityFramework 5.0.0-beta1' to PROJECTNAME.
Failed to generate binding redirects for 'PROJECTNAME'. 'object' does not contain a definition for 'References'
Successfully uninstalled 'EntityFramework 4.3.1'.

It looks like the upgrade completed succesfully, but I wonder how I could have prevented this error.

Body:
You should enable automatic binding redirection manually. To do this:

In Visual Studio, in Solution Explorer, right-click the project and choose "Unload Project".

Add the following element to the property group (under the  tag) in XML code:

<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

The following shows an example project file with the element inserted:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{123334}</ProjectGuid>
    ...
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  </PropertyGroup>
  ...
</Project>

Right click the project and choose "Reload Project".

Compile your app.

List item

Install EntityFramework.


问:
Git push error pre-receive hook declined
I have run gitlabhq rails server on virtual machine, following 1-6 steps from this tutorial https://github.com/gitlabhq/gitlab-recipes/blob/master/install/centos/README.md and starts rails server executing command sudo -u git -H bundle exec rails s -e production. After that I created user, using admin tools and created new project under this user. Then I'm trying to push the existing project to this repo as always. But in the last step, git push origin master fails with the error

[remote rejected] master -> master (pre-receive hook declined)

Additional info:

1) I haven't activated user (project owner) via email activation link, because I haven't configured post service on server-side and I didn't find instructions how to do that in this manual.

2) Gitlab server generates tips how to push project to repo and there is not repositories/ in path. I mean it generates git@mygitlabhost:user/repo.git instead of git@mygitlabhost:repositories/user/repo.git which is correct.

3) When i tried to debug it, I opened pre-receive script inside repo on server and tried to output variables (there is 3 of them): refs = ARGF.read, key_id  = ENV['GL_ID'] and repo_path = Dir.pwd and found, that key_id is always empty. Maybe the problem is here... If so, please give me suggestions on how to fix that. Thanks

答:
If you are facing issue like

! [remote rejected] master -> master (pre-receive hook declined)

its beacuse master is protected, you can do 2 steps

To remove the protection, follow these steps –

Go to project Settings.

Click on Repository tab.

Open Protected Branches.

Find your master branch and click on Unprotect.

Or else

We can switch branches from master to main

git checkout -b main

git branch -D master

git push heroku main

Happy Hacking!!!


问:
Call is not going to fallback method of Resilience4 Circuit breaker
I am using Resilience4j Circuit breaker version: '1.4.0 with Spring boot version 2.0.6 and my problem is - fallback method is not working. the call is not going to the fallback method.
Below is my code :

```<code>@Override
@CircuitBreaker(name="mainService",fallbackMethod = "callFallback")
public JSONObject callService(JSONObject rawRequest) throws TimeoutException {
      ...
       throw new TimeoutException("Time occured while calling
       service");
      ...
}
</code>```

-- and fallback method :

```<code>private JSONObject callFallback(JSONObject rawRequest,Throwable t){

    System.out.println("Inside fallback method callNsFallback,
        cause"+t.toString());

        logger.info("Inside fallback method callFallback,
        cause - {}",t.toString());

    return rawRequest;
}
</code>```

--Configurations in application.yml

```<code>resilience4j:
circuitbreaker:
    configs:
    default:
        registerHealthIndicator: true
        ringBufferSizeInClosedState: 5
        ringBufferSizeInHalfOpenState: 3
        slidingWindowSize: 10
        minimumNumberOfCalls: 5
        permittedNumberOfCallsInHalfOpenState: 3
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenState: 1s
        failureRateThreshold: 50
        eventConsumerBufferSize: 10
        recordExceptions:
        - java.util.concurrent.TimeoutException
    instances:
    mainService:
        baseConfig: default
</code>```

答:
The possible reasons could be you are missing some required dependencies. Here I am sharing the dependencies and the yaml configuration which were working for me.

pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-spring-boot2</artifactId>
            <version>1.7.1</version>
        </dependency>
    </dependencies>
</code>```

application.yml

```<code>resilience4j:
  circuitbreaker:
    instances:
      menu-service:
        registerHealthIndicator: true
        eventConsumerBufferSize: 10
        automaticTransitionFromOpenToHalfOpenEnabled: true
        failureRateThreshold: 50
        minimumNumberOfCalls: 5
        permittedNumberOfCallsInHalfOpenState: 1
        slidingWindowSize: 10
        waitDurationInOpenState: 2s
        slidingWindowType: COUNT_BASED

management:
  health:
    circuitbreakers:
      enabled: true
  endpoints:
    web:
      exposure:
        include: health
  endpoint:
    health:
      show-details: always

</code>```

Body:
I am using Resilience4j Circuit breaker version: '1.4.0 with Spring boot version 2.0.6 and my problem is - fallback method is not working. the call is not going to the fallback method.
Below is my code :

@Override
@CircuitBreaker(name="mainService",fallbackMethod = "callFallback")
public JSONObject callService(JSONObject rawRequest) throws TimeoutException {
      ...
       throw new TimeoutException("Time occured while calling
       service");
      ...
}

-- and fallback method :

private JSONObject callFallback(JSONObject rawRequest,Throwable t){

    System.out.println("Inside fallback method callNsFallback,
        cause"+t.toString());

        logger.info("Inside fallback method callFallback,
        cause - {}",t.toString());

    return rawRequest;
}

--Configurations in application.yml

resilience4j:
circuitbreaker:
    configs:
    default:
        registerHealthIndicator: true
        ringBufferSizeInClosedState: 5
        ringBufferSizeInHalfOpenState: 3
        slidingWindowSize: 10
        minimumNumberOfCalls: 5
        permittedNumberOfCallsInHalfOpenState: 3
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenState: 1s
        failureRateThreshold: 50
        eventConsumerBufferSize: 10
        recordExceptions:
        - java.util.concurrent.TimeoutException
    instances:
    mainService:
        baseConfig: default

Body:
The possible reasons could be you are missing some required dependencies. Here I am sharing the dependencies and the yaml configuration which were working for me.

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-spring-boot2</artifactId>
            <version>1.7.1</version>
        </dependency>
    </dependencies>

application.yml

resilience4j:
  circuitbreaker:
    instances:
      menu-service:
        registerHealthIndicator: true
        eventConsumerBufferSize: 10
        automaticTransitionFromOpenToHalfOpenEnabled: true
        failureRateThreshold: 50
        minimumNumberOfCalls: 5
        permittedNumberOfCallsInHalfOpenState: 1
        slidingWindowSize: 10
        waitDurationInOpenState: 2s
        slidingWindowType: COUNT_BASED

management:
  health:
    circuitbreakers:
      enabled: true
  endpoints:
    web:
      exposure:
        include: health
  endpoint:
    health:
      show-details: always


问:
Can Git and iCloud Drive be effectively used together?
In the same flavor as this question, are there any possible complications that can arise when using the two services together?</p>

答:
TL;DR assuming you're using macOS, you can create a sparse disk image with your repo inside and store this image on iCloud Drive safely

Probably not the answer you're looking for, but I think there is an approach that works quite nice for archive or infrequent access storage of your git repo.

The idea is to create a sparse or sparse bundle disk image using Disk Utility.app. You can put a very large size that will represent the maximum available disk space on the disk image. The actual image file size will only use up as much space as actually used on the inside.

Store this sparse or sparse bundle on iCloud Drive, and all you need to do to access your repo is mount the image whenever needed, then work inside of it. This way, iCloud Drive will only have to sync a single binary file (the image), rather than each separate file of the git repository.

The only drawback is that the sparse or sparse bundle size will not decrease when you delete content inside. You may "reclaim" the free space using hdiutil: hdiutil compact my-special-repo.sparseimage.

I've been doing this for a critical local repository I do not wish to host on a remote server, yet had to make sure I didn't lose it while still being usable and up-to-date in case of hardware loss. Little reminder that important data must always be backed up in multiple places.

Here are the steps for those looking for a synthesised walkthrough:

Using Disk Utility.app, create a new Blank Image

Set a size large enough to hold your repo, it will be the maximum space available

Example: an empty 2GB sparse image only uses 8.4MB on the disk

Select sparse disk image or sparse bundle disk image under Image Format

The other settings are at your discretion, I recommend leaving default unless you need to access this image on a Mac that does not support APFS.

The image should be mounted automatically after the creation, if that's not the case mount it manually

Put your git repo inside the mounted image

Eject the image and move it to iCloud Drive

Enjoy your git repo synced across your Macs

Bonus step

The image will not reduce in size even if you delete files inside. If you need to reclaim empty space, use hdiutil compact my-special-repo.sparseimage


问:
Why files from static not shows on page?
I made for test such simple project in django

I've created views

from django.shortcuts import render

```<code>def home(request):
    return render(request, 'app1/home.html', {})
</code>```

Further i've created url

```<code>from courseshop import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home')
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

I add some things in settings for static

```<code>import os

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = []

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code>```

And i've made template home.html

```<code>{% load static %}
<!DOCTYPE html>
<html>
    <head>
        <title>Мой сайт</title>
        <meta http-equiv="Content-type" content="text/html; " charset="utf-8">
    </head>
    <body>
        <h1 align="center">Привет всему миру!</h1>

        <p>Регистр (цифровая техника) — последовательное или параллельное логическое устройство, используемое для хранения n-разрядных двоичных чисел и выполнения преобразований над ними.</p>

        <img src="{% static '/Python/django/courseshop/app1/static/app1/images/stars.jpeg' %}"
        <hr>
    </body>
</html>
</code>```

And this is my templates settings

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_
</code>```

And i don't see image stars on my page. Why? Please, help me

答:
plz add templates name in settings.py file

TEMPLATES = [
{

```<code>    'DIRS': [BASE_DIR / 'templates'],
    ...
},
</code>```

]

plz check all path

.html img path
views.py

Body:
I made for test such simple project in django

I've created views

from django.shortcuts import render

def home(request):
    return render(request, 'app1/home.html', {})

Further i've created url

from courseshop import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
from app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home')
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I add some things in settings for static

import os

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = []

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

And i've made template home.html

{% load static %}
<!DOCTYPE html>

        <title>Мой сайт</title>
        <meta http-equiv="Content-type" content="text/html; " charset="utf-8">

Привет всему миру!

Регистр (цифровая техника) — последовательное или параллельное логическое устройство, используемое для хранения n-разрядных двоичных чисел и выполнения преобразований над ними.

        <img src="{% static '/Python/django/courseshop/app1/static/app1/images/stars.jpeg' %}"

And this is my templates settings

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_

And i don't see image stars on my page. Why? Please, help me

Body:
plz add templates name in settings.py file

TEMPLATES = [
{

    'DIRS': [BASE_DIR / 'templates'],
    ...
},

]

plz check all path

.html img path
views.py


问:
Cypress sees undefined when reffering to an aliased text value
My test results in adding a row to the table. In afterEach hook I wanted to add a method to delete the newest row after the test ran so I wrote this piece of code:

```<code>deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then( firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)
    })
}
</code>```

With 'then' I'm saving a table element to later use to find and operate on the elements inside it. I wanted to first save the value of the newest row in the table that was added after the test ran successfully, then delete and as the last step make sure that the row with the ID that was deleted is actually gone from the table. The problem is that cypress test runner assertions marks it green because it sees that value of  is not equal to 'undefined' and not, let's say 3794.

答:
Breaking up the steps might work better.

deleteTheNewestRequest() {
  cy.get('table#return-request-list')
    .find('tr').eq(1)
    .as('firstRow')               // save row ref for delete
    .find('td').eq(0)
    .invoke('text').as('rowId')   // save rowId text for check

  cy.get('@firstRow').find('a[title="Delete"]').click()
  cy.get('button.btn-delete-return-request').click()

  cy.get('@rowId').then(rowId => {
    cy.contains('tr', rowId).should('not.exist')  // "standard" non-existence check
  })
}
```

Ref Test if element does not exist

I would check if .find('tr').eq(1) is the first row, perhaps it should be .find('tr').eq(0)?

Body:
My test results in adding a row to the table. In afterEach hook I wanted to add a method to delete the newest row after the test ran so I wrote this piece of code:

deleteTheNewestRequest() {
    cy.get('table#return-request-list').find('tr').eq(1).then( firstRow => {
        cy.wrap(firstRow).find('td').eq(0).invoke('text').as('rowId')
        cy.wrap(firstRow).find('a[title="Delete"]').click()
        cy.get('button.btn-delete-return-request').click()
        cy.wrap(firstRow).find('td').first().should('not.have.text', this.rowId)
    })
}

With 'then' I'm saving a table element to later use to find and operate on the elements inside it. I wanted to first save the value of the newest row in the table that was added after the test ran successfully, then delete and as the last step make sure that the row with the ID that was deleted is actually gone from the table. The problem is that cypress test runner assertions marks it green because it sees that value of  is not equal to 'undefined' and not, let's say 3794.

Body:
Breaking up the steps might work better.

deleteTheNewestRequest() {
  cy.get('table#return-request-list')
    .find('tr').eq(1)
    .as('firstRow')               // save row ref for delete
    .find('td').eq(0)
    .invoke('text').as('rowId')   // save rowId text for check

  cy.get('@firstRow').find('a[title="Delete"]').click()
  cy.get('button.btn-delete-return-request').click()

  cy.get('@rowId').then(rowId => {
    cy.contains('tr', rowId).should('not.exist')  // "standard" non-existence check
  })
}

Ref Test if element does not exist

I would check if .find('tr').eq(1) is the first row, perhaps it should be .find('tr').eq(0)?


问:
Rotate twice from two origin
I have a css div I want first to rotate at 180deg from the center origin and then rotate from -45deg from the "new" bottom left corner.
But I don't manage to apply two different rotations

https://imgur.com/a/9GSToEx -> So you can better understand

CSS

.player1{
    background-color: blueviolet;
    transform-origin: center;
    transform: rotate(180deg);
    transform-origin: bottom left;
    transform: rotate(45deg);
}

```
<h2>HTML</h2>
<pre class="lang-html prettyprint-override"><code><div class="player1">
            <div class="questionSpace"></div>
        </div>
</code>```

Thank you ^^

答:
Hmm. Your code is wrong, because this rules have conflict and last rule have more priority;

```<code>transform: rotate(180deg);
...
transform: rotate(45deg);
</code>```

You need to use @keyframes

for example:

```<code>@rotate {
  0% {
    transform: rotate(0);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
   transform-origin: left;
   transform: rotate(45deg);
  }
 }
</code>```

and then you need to use animation: rotate;

Title: Rotate twice from two origin

Body:
I have a css div I want first to rotate at 180deg from the center origin and then rotate from -45deg from the "new" bottom left corner.
But I don't manage to apply two different rotations

https://imgur.com/a/9GSToEx -> So you can better understand

CSS

.player1{
    background-color: blueviolet;
    transform-origin: center;
    transform: rotate(180deg);
    transform-origin: bottom left;
    transform: rotate(45deg);
}

HTML

Thank you ^^

Body:
Hmm. Your code is wrong, because this rules have conflict and last rule have more priority;

transform: rotate(180deg);
...
transform: rotate(45deg);

You need to use @keyframes

for example:

@rotate {
  0% {
    transform: rotate(0);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
   transform-origin: left;
   transform: rotate(45deg);
  }
 }

and then you need to use animation: rotate;


问:
How many processors should be used with multiprocessing.Pool?
I am trying to use multiprocessing.Pool to run my code in parallel. To instantiate Pool, you have to set the number of processes. I am trying to figure out how many I should set for this. I understand this number shouldn't be more than the number of cores you have but I've seen different ways to determine what your system has available.

2 Methods:

multiprocessing.cpu_count()

len(os.sched_getaffinity(0))

I'm a little confused; what is the difference between the two and which should be implemented with Pool? I am working on a remote cluster, with the first, it outputs that there are 128 cpu, but the second gives 10.

答:
First of all, keep in mind that cpu_count() returns the number of virtual CPUs (this can be larger than the number of physical CPUs in case each CPU supports multiple threads. To see the number of physical CPUs use:

```<code>psutil.cpu_count(logical=False)
</code>```

Anyway, with psutil.cpu_count() you get the actual number of virtual CPUs, that is also the maximum possible number of concurrent threads you can have on your system.

With

```<code>os.sched_getaffinity(0) # same as the default os.sched_getaffinity()
</code>```

(where 0 is the current process) you get the number of CPUs available to the current process. You can change that with:

```<code>os.sched_setaffinity(0,[1,2,3])
</code>```

Here for instance you tell the process to use 3 CPUs, namely: 1, 2, and 3.

Note that if you set Pool to use the maximum available number of CPUs you won't have the maximum parallelism anyway, since some CPUs will always be busy with operating the system. Similarly in a multi-user environment you are likely not going to achieve the parallelism set by the number of threads in the pool.

Scheduling engines like SLURM or YARN can guarantee that a process gets a certain number of CPUs and therefore the desired parallelism.

Body:
First of all, keep in mind that cpu_count() returns the number of virtual CPUs (this can be larger than the number of physical CPUs in case each CPU supports multiple threads. To see the number of physical CPUs use:

psutil.cpu_count(logical=False)

Anyway, with psutil.cpu_count() you get the actual number of virtual CPUs, that is also the maximum possible number of concurrent threads you can have on your system.

With

os.sched_getaffinity(0) # same as the default os.sched_getaffinity()

(where 0 is the current process) you get the number of CPUs available to the current process. You can change that with:

os.sched_setaffinity(0,[1,2,3])

Here for instance you tell the process to use 3 CPUs, namely: 1, 2, and 3.

Note that if you set Pool to use the maximum available number of CPUs you won't have the maximum parallelism anyway, since some CPUs will always be busy with operating the system. Similarly in a multi-user environment you are likely not going to achieve the parallelism set by the number of threads in the pool.

Scheduling engines like SLURM or YARN can guarantee that a process gets a certain number of CPUs and therefore the desired parallelism.


问:
Take the number from two different functions and add them together in another function (Unique to Google Apps Script)
I am trying to create a simple function that will add one number to another to get a total amount, seems easy right? Thats what I thought although I am new to javascript and I believe Google Apps Script could also playing with me.

Here is a stripped down code of that exact function that is WORKING with manually inputted figures.

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Calculator - V1</title>
  </head>
  <body>

    <script>

      function showHourlyRate() {
        var oneFunc = 1
        console.log(oneFunc) //result is 5.00
        // alert(oneFunc);
        return oneFunc
      };

      function showMileageRate() {
        var twoFunc = 1
        console.log(twoFunc) //result is 5.00
        // alert(twoFunc);
        return twoFunc
      };
      function showCombinedFigure() {
        var twoFunc = showHourlyRate() + showMileageRate()
        alert(twoFunc);
      };

      document.addEventListener("DOMContentLoaded", showCombinedFigure);
    </script>
  </body>

</html>
</code>```

That takes the showHourlyRate and showMileageRate figures and adds them together to make 2, perfect.

I need to get those figures from a Google Sheets doc so (using google apps script application to code) I have 3 files, one is the default Code.gs file. I have then created a functions.gs file and an index.html file.

Here's my Code.gs file

```<code>function doGet(e) {
  var htmlOutput =  HtmlService.createTemplateFromFile('index');

  return htmlOutput.evaluate();
}
</code>```

I believe you need this in order for it all to run and it basically just says to use the index.html file.

Here's my functions.gs file

```<code>function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("643876537465743653456").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? 0 : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

function getMileageRate() {
  const sheet = SpreadsheetApp.openById("643876537465743653456").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Mileage");

  return filteredData.length === 0 ? 0 : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}
</code>```

This is where I get the google sheets information, it finds the doc by ID, then finds the sheet by name, selects the rows I want to search then filters the results based on my chosen word.

Finally my html code:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Calculator - V1</title>
  </head>
  <body>
    <script>

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();
      }

      function showHourlyRate(hourlyRate) {
        var oneFunc = hourlyRate
        console.log(oneFunc) //result is 5.00
        //alert(oneFunc);
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        console.log(twoFunc) //result is 5.00
        //alert(twoFunc);
        return twoFunc
      };
      function showCombinedFigure() {
        var twoFunc = showHourlyRate() + showMileageRate()
        alert(twoFunc);
      };

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);
      document.addEventListener("DOMContentLoaded", showCombinedFigure);
    </script>
  </body>

</html>
</code>```

Now it no longer works. The alerts for the showHourlyRate() and showMileageRate() work (when activated) and shows the correct figures. The alert for showCombinedFigure() no longer works, I get a NAN error, if I remove '+ showMileageRate()' like so:

```<code>      function showCombinedFigure() {
        var twoFunc = showHourlyRate() + showMileageRate()
        alert(twoFunc);
      };
</code>```

I get undefined error.

I'm not exactly sure what this function does but is this the culprit? I followed a guide to get me to the point of reading the data from the sheets doc but now I need to move further along.

```<code>      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();
      }
</code>```

答:
The values returned by showMileageRate and showHourlyRate aren't being stored anywhere, you'll want to change your functions to store them globally:

```<code><script>
      let oneFunc
      let twoFunc

      function afterSidebarLoads() {
        // get mileage rate
        google.script.run.withSuccessHandler(mileageRateHandler).getMileageRate()

      }

      function mileageRateHandler(mileageRate) {
        // set gloabal oneFunc
        oneFunc = mileageRate

        // get hourly rate
        google.script.run.withSuccessHandler(hourlyRateHandler).getHourlyRate()
      }

      function hourlyRateHandler(hourlyRate) {
        // set global twoFunc
        twoFunc = hourlyRate

        // call showCombinedFigure after both Apps Script methods have completed
        showCombinedFigure()
      }

      function showCombinedFigure() {
        var result = oneFunc + twoFunc
        alert(result);
      };

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);
  </script>
</code>```

Also you need to make sure that showCombinedFigure runs only after the Apps Script functions have returned, as google.script.run is an asynchronous function and returns after the DOMContentLoaded event is fired.

Body:
I am trying to create a simple function that will add one number to another to get a total amount, seems easy right? Thats what I thought although I am new to javascript and I believe Google Apps Script could also playing with me.

Here is a stripped down code of that exact function that is WORKING with manually inputted figures.

<!DOCTYPE html>

    <title>Calculator - V1</title>

That takes the showHourlyRate and showMileageRate figures and adds them together to make 2, perfect.

I need to get those figures from a Google Sheets doc so (using google apps script application to code) I have 3 files, one is the default Code.gs file. I have then created a functions.gs file and an index.html file.

Here's my Code.gs file

function doGet(e) {
  var htmlOutput =  HtmlService.createTemplateFromFile('index');

  return htmlOutput.evaluate();
}

I believe you need this in order for it all to run and it basically just says to use the index.html file.

Here's my functions.gs file

function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("643876537465743653456").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? 0 : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

function getMileageRate() {
  const sheet = SpreadsheetApp.openById("643876537465743653456").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Mileage");

  return filteredData.length === 0 ? 0 : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

This is where I get the google sheets information, it finds the doc by ID, then finds the sheet by name, selects the rows I want to search then filters the results based on my chosen word.

Finally my html code:

<!DOCTYPE html>

    <title>Calculator - V1</title>

Now it no longer works. The alerts for the showHourlyRate() and showMileageRate() work (when activated) and shows the correct figures. The alert for showCombinedFigure() no longer works, I get a NAN error, if I remove '+ showMileageRate()' like so:

      function showCombinedFigure() {
        var twoFunc = showHourlyRate() + showMileageRate()
        alert(twoFunc);
      };

I get undefined error.

I'm not exactly sure what this function does but is this the culprit? I followed a guide to get me to the point of reading the data from the sheets doc but now I need to move further along.

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();
      }

Body:
The values returned by showMileageRate and showHourlyRate aren't being stored anywhere, you'll want to change your functions to store them globally:

<script>
      let oneFunc
      let twoFunc

      function afterSidebarLoads() {
        // get mileage rate
        google.script.run.withSuccessHandler(mileageRateHandler).getMileageRate()

      }

      function mileageRateHandler(mileageRate) {
        // set gloabal oneFunc
        oneFunc = mileageRate

        // get hourly rate
        google.script.run.withSuccessHandler(hourlyRateHandler).getHourlyRate()
      }

      function hourlyRateHandler(hourlyRate) {
        // set global twoFunc
        twoFunc = hourlyRate

        // call showCombinedFigure after both Apps Script methods have completed
        showCombinedFigure()
      }

      function showCombinedFigure() {
        var result = oneFunc + twoFunc
        alert(result);
      };

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);
  </script>

Also you need to make sure that showCombinedFigure runs only after the Apps Script functions have returned, as google.script.run is an asynchronous function and returns after the DOMContentLoaded event is fired.


答:
In that particular case the parameter is not used.  However it may not be safe to remove it from the method signature.  It might be there specifically to change the signature in order to avoid a naming clash with another method.

Bad form really, but sometimes necessary.

Personally I'd try to remove it.  If it doesn't compile when you remove it because of a clash with a similarly named method, I'd leave it there, but make the parameter default (if you are using C# 4).  I say leave it there because someone may be using reflection to reference it.

If you know that reflection isn't used in the application, right-click refactor the method name in Visual Studio and rename it, this will rename all references too (but not literal references for reflection).  Then remove the parameter.

Title: why we need to pass Boolean value to the method


问:
How to delete an Elastic IP Address in AWS
I can't seem to delete it in AWS, It was not showing any options like delete or disassociate.

AWS is charging me every month for Elastic IP address usage. I'm not even using them.

Please help me, how to remove the EIP address.

答:
if Associate address, Release address, and Disassociate address all are greyed out for you, and you see association id in the details pane, it probably is still assigned to VPC/NAT Gateway or some service. delete that service first, then you'll be able to release the IP.

It was assigned to NAT gateway in my case, which I deleted but still it was not letting me release the IP. I had to delete VPC.


问:
Viewing complex objects in debugger
Is it possible to construct custom views for complex objects?

Specifically I want to view the inner workings of a CGPath.

I've found the "view variable as" option with right clicking the variable in the debug view, and I've seen ways to view (eg) strings &tc with it, but I haven't found anything that helps me in this case.

答:
po path in the debugger will print out all of the path's elements. UIBezierPath has quick look support in the debugger, where you can hit space and view a drawing of it, but you have a CGPath. It seems that quick look support is not enabled for CF classes like CGPath.

But you're not stuck. If you right-click the variables list in the debugger (as shown here), and choose add expression, you can create a local UIBezierPath by typing this in the expression field:

```<code>UIBezierPath(cgPath: path)
</code>```

or, if your debugger is in an Objective-C context:

```<code>[UIBezierPath bezierPathWithCGPath: path]
</code>```

Your expression then shows up in the list, and you can press the space bar to see a visual representation.

This example shows how I have it set up in an Objective-C project:

Quick-looking the path shows this:

If po path isn't showing you any components (moveto, curveto etc) in the debugger, then I think you have an empty path, and your problem lies elsewhere. If otherPath is nil, then I get an invalid expression in the debugger when creating the bezier path.

Title: Viewing complex objects in debugger

Body:
po path in the debugger will print out all of the path's elements. UIBezierPath has quick look support in the debugger, where you can hit space and view a drawing of it, but you have a CGPath. It seems that quick look support is not enabled for CF classes like CGPath.

But you're not stuck. If you right-click the variables list in the debugger (as shown here), and choose add expression, you can create a local UIBezierPath by typing this in the expression field:

UIBezierPath(cgPath: path)

or, if your debugger is in an Objective-C context:

[UIBezierPath bezierPathWithCGPath: path]

Your expression then shows up in the list, and you can press the space bar to see a visual representation.

This example shows how I have it set up in an Objective-C project:

Quick-looking the path shows this:

If po path isn't showing you any components (moveto, curveto etc) in the debugger, then I think you have an empty path, and your problem lies elsewhere. If otherPath is nil, then I get an invalid expression in the debugger when creating the bezier path.


问:
grep Howto extract a link only from a webseite
I was searching a lot, but nothing really helped me to find a solution to my question. I am still learning regex and have some success, but in this case I can't get to the solution I want.

I am writing scripts to actualize installation packets for our installation-server. It shall download the newest setup.exe and pack a new package, so it can deployed to the clients.

I try to download a website and to find the right link in it:

```<code>wget --no-check-certificate https://www.thunderbird.net/en-US/thunderbird/all/ -q -O- | grep -o https://download\.mozilla\.org/\?product=thunderbird-.*-SSL\&os=win64\&lang=de
</code>```

It shall ignore the version-number and it works well on my way to the final solution. The result is:

```<code>https://download.mozilla.org/?product=thunderbird-91.6.0-SSL&os=win64&lang=de
https://download.mozilla.org/?product=thunderbird-91.6.0-msi-SSL&os=win64&lang=de
</code>```

But what I need is just the https://download.mozilla.org/?product=thunderbird-91.6.0-SSL&os=win64&lang=de

I know I can regex the "91.6.0" but how correctly and what if the 91 becomes a >100 and what if one version is the 95.4.0.2 (for example) ?

Thanks for help.

Denise

答:
You may exclude a hyphen in between thunderbird- and -SSL with a [^-]* negated bracket expression:

https://download\.mozilla\.org/\?product=thunderbird-[^-]*-SSL\&os=win64\&lang=de
```
<p>See the regex demo.</p>
<p>You may also match digits or dots only with <code>[0-9.]*</code>:</p>
<pre class="lang-none prettyprint-override"><code>https://download\.mozilla\.org/\?product=thunderbird-[0-9.]*-SSL\&os=win64\&lang=de
</code>```

See this regex demo.

Body:
I was searching a lot, but nothing really helped me to find a solution to my question. I am still learning regex and have some success, but in this case I can't get to the solution I want.

I am writing scripts to actualize installation packets for our installation-server. It shall download the newest setup.exe and pack a new package, so it can deployed to the clients.

I try to download a website and to find the right link in it:

wget --no-check-certificate https://www.thunderbird.net/en-US/thunderbird/all/ -q -O- | grep -o https://download\.mozilla\.org/\?product=thunderbird-.*-SSL\&os=win64\&lang=de

It shall ignore the version-number and it works well on my way to the final solution. The result is:

https://download.mozilla.org/?product=thunderbird-91.6.0-SSL&os=win64&lang=de
https://download.mozilla.org/?product=thunderbird-91.6.0-msi-SSL&os=win64&lang=de

But what I need is just the https://download.mozilla.org/?product=thunderbird-91.6.0-SSL&os=win64&lang=de

I know I can regex the "91.6.0" but how correctly and what if the 91 becomes a >100 and what if one version is the 95.4.0.2 (for example) ?

Thanks for help.

Denise

Body:
You may exclude a hyphen in between thunderbird- and -SSL with a [^-]* negated bracket expression:

https://download\.mozilla\.org/\?product=thunderbird-[^-]*-SSL\&os=win64\&lang=de

See the regex demo.

You may also match digits or dots only with [0-9.]*:

https://download\.mozilla\.org/\?product=thunderbird-[0-9.]*-SSL\&os=win64\&lang=de

See this regex demo.


答:
when you want to use static files in your template, you should add load static in the beggining of your template and use it like this:</p>
```<code>{% load static %}
<img src="{% static 'app1/images/stars.jpg' %}"
</code>```

Title: Why files from static not shows on page?

Body:
when you want to use static files in your template, you should add load static in the beggining of your template and use it like this:

{% load static %}
<img src="{% static 'app1/images/stars.jpg' %}"


问:
How to resize and reshape UIImage without causing any distortion?
I am using the clearbit api to get and display company logos in my app. This works great except that all of the logos are different size, and I want them all to be displayed as a square.

Does anybody know how to take a rectangular image and add extra pixels to it of a given color until it becomes square with the logo at the center?

This question seemed to answer it, but it is outdated. I also thought that the top answer on this question would work, but the code didn't work. Any help would be very much appreciated, thank you!

答:
```<code>import UIKit

extension UIImage {
    func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {
        // Determine the scale factor that preserves aspect ratio
        let widthRatio = targetSize.width / size.width
        let heightRatio = targetSize.height / size.height

        let scaleFactor = min(widthRatio, heightRatio)

        // Compute the new image size that preserves aspect ratio
        let scaledImageSize = CGSize(
            width: size.width * scaleFactor,
            height: size.height * scaleFactor
        )

        // Draw and return the resized UIImage
        let renderer = UIGraphicsImageRenderer(
            size: scaledImageSize
        )

        let scaledImage = renderer.image { _ in
            self.draw(in: CGRect(
                origin: .zero,
                size: scaledImageSize
            ))
        }

        return scaledImage
    }
}
</code>```


问:
How to use python to workout a simple mathematical problem in python with random operations
This is my code for a calculator that randomly selects a operation and number in between 1-10 and then with that number and operation works out the answer.

https://i.stack.imgur.com/Nys19.png

Now heres what happens when I run the code and put in a number. It dosen't workout the question it tells you the question. How do I make it answer the question.

https://i.stack.imgur.com/dLmaJ.png

Thank You if you help me

答:
You need to tell python to do something with each type of operation.

e.g.

```<code>operations = ['+','-']
operation = random.choice(operations)

if operation == '+':
    answer = mynumber + yournumber

if operation == '-':
    answer = mynumber - yournumber;

print(mynumber,operation,yournumber,'=',answer)
</code>```

You would need an if statement for each operation.

A more compact and flexible approach (although more advanced) would be to have a dictionary of operations and functions that are performed for each of those operations.  Then we randomly choose an operation and send the two variables to the relevant function.  You could do this with normal functions or lambda functions like below:

```<code>ops = {'+':(lambda x,y:x+y),'-':(lambda x,y:x-y)}

op = random.choice(list(ops.keys()))

print(yournumber,op,mynumber,"=",ops[op](yournumber,mynumber))
</code>```

As long as you have operations that take two inputs, you can extend the list of operations infinitely without having to change the rest of the code at all.   You could then extend some of the functions to do things like error checking (check we're not dividing by zero) etc.

Body:
You need to tell python to do something with each type of operation.

e.g.

operations = ['+','-']
operation = random.choice(operations)

if operation == '+':
    answer = mynumber + yournumber

if operation == '-':
    answer = mynumber - yournumber;

print(mynumber,operation,yournumber,'=',answer)

You would need an if statement for each operation.

A more compact and flexible approach (although more advanced) would be to have a dictionary of operations and functions that are performed for each of those operations.  Then we randomly choose an operation and send the two variables to the relevant function.  You could do this with normal functions or lambda functions like below:

ops = {'+':(lambda x,y:x+y),'-':(lambda x,y:x-y)}

op = random.choice(list(ops.keys()))

print(yournumber,op,mynumber,"=",ops[op](yournumber,mynumber))

As long as you have operations that take two inputs, you can extend the list of operations infinitely without having to change the rest of the code at all.   You could then extend some of the functions to do things like error checking (check we're not dividing by zero) etc.


问:
Javascript - Display a different content if a checkbox is active
I'm trying to set up something in JQuery but at the moment I'm not really sure I'm doing it right.

To keep it simple, I would like to display 4 checkboxes. These checkboxes serve as filters. For the example, let's say the first checkbox is spring, the second is summer, the third is autumn and the fourth is winter.

When I check the "summer" box I would like some text to be displayed. If I tick the autumn one, another text is displayed. Basically, I would like to display different texts depending on what is ticked.

```<code><script type="text/javascript">
    function ShowHideDiv(winter) {
        var winter_list = document.getElementById("winter_list");
        winter_list.style.display = winter.checked ? "block" : "none";
    }
</script>
<script type="text/javascript">
    function ShowHideDiv(summer) {
        var summer_list = document.getElementById("summer_list");
        summer_list.style.display = summer.checked ? "block" : "none";
    }
</script>

<label for="checkWinter">
    <input type="checkbox" id="winter" onclick="ShowHideDiv(winter)" />
    Winter
</label>
<label for="checkSummer">
    <input type="checkbox" id="summer" onclick="ShowHideDiv(summer)" />
    Summer
</label>
<hr />

<!-- For Winter -->
<div id="winter_list" style="display: none">
<p>Text come here</p>
</div>

<!-- For Summer -->
<div id="summer_list" style="display: none">
<p>Text come here for summer</p>
</div>
</code>```

If possible: Can we make it possible to tick more than one box?

I've been following tutorials on StackOverflow but so far without much success, as I haven't found anything in the genre of my same request.

Thanks

答:
First, give all your checkboxes an id.
You can then add data-target to the display texts for easy selection. Try this

    <input type="checkbox" id="winter" onchange="ShowHideDiv(this)" />
    Winter

    <input type="checkbox" id="summer" onchange="ShowHideDiv(this)" />
    Summer

Text come here

Text come here for summer

```

Body:
I'm trying to set up something in JQuery but at the moment I'm not really sure I'm doing it right.

To keep it simple, I would like to display 4 checkboxes. These checkboxes serve as filters. For the example, let's say the first checkbox is spring, the second is summer, the third is autumn and the fourth is winter.

When I check the "summer" box I would like some text to be displayed. If I tick the autumn one, another text is displayed. Basically, I would like to display different texts depending on what is ticked.

    <input type="checkbox" id="winter" onclick="ShowHideDiv(winter)" />
    Winter

    <input type="checkbox" id="summer" onclick="ShowHideDiv(summer)" />
    Summer

Text come here

Text come here for summer

If possible: Can we make it possible to tick more than one box?

I've been following tutorials on StackOverflow but so far without much success, as I haven't found anything in the genre of my same request.

Thanks

Body:
First, give all your checkboxes an id.
You can then add data-target to the display texts for easy selection. Try this

<label for="winter">
    <input type="checkbox" id="winter" onchange="ShowHideDiv(this)" />
    Winter
</label>
<label for="summer">
    <input type="checkbox" id="summer" onchange="ShowHideDiv(this)" />
    Summer
</label>
<hr />

<!-- Display text -->
<div>
    <p style="display: none" data-target="#winter">Text come here</p>
    <p style="display: none" data-target="#summer">Text come here for summer</p>
</div>

<script type="text/javascript">
    function ShowHideDiv(elem) {
        var target = document.querySelector('[data-target="#'+elem.id+'"]');
        target.style.display = elem.checked ? 'block' : 'none';
    }
</script>


问:
How to access the DOM element of some external library in a parent component where it is used in Angular
I need to manipulate the styling and visibility of a button that is present in one of the external library component. For better understanding below is the scenario.

parent.component.html
<child-component></child-component>

child.component.html
<external-component></external-component>

So the button is present in an external library component which I need to manipulate in the parent component.

Note: The button does not have any template reference variable and since it is present in external library I can not add it in its html.

Is there any way this can be done?
Thanks in advance :-)

答:
In the component file add the following code

```<code>import { ElementRef } from '@angular/core';

@Component({
   selector: 'app-my-contract',
   templateUrl: './my.component.html',
   styleUrls: ['./my-contract.component.css']
})
export class MbpContractComponent implements OnInit {
@ViewChild('myInput') myInputVariable: ElementRef
</code>```

}

In your code you can use like

```<code>this.myInputVariable.nativeElement.disabled = true;
</code>```

Or you can use any properties on that element

Body:
In the component file add the following code

import { ElementRef } from '@angular/core';

@Component({
   selector: 'app-my-contract',
   templateUrl: './my.component.html',
   styleUrls: ['./my-contract.component.css']
})
export class MbpContractComponent implements OnInit {
@ViewChild('myInput') myInputVariable: ElementRef

}

In your code you can use like

this.myInputVariable.nativeElement.disabled = true;

Or you can use any properties on that element


问:
How to map two keys to a single member in JSON struct. (with Marshal/Unmarshal)
I have a situation where my API return []byte {"name":"Windows"} on Windows and {"myName":"Linux"} on Linux, both are reporting OS Name but the key (name/MyName) is changed based on OS. How to Marshal/Unmarshal it to a JSON struct. Where I have single ember that can hold OS Name.

```<code>type OsName struct {
    Name   string `json:"name"` //I want to map Myname as well to this member.
}
</code>```

Note: above question is not about how to get OS name, its about how to map 2 different keys to a single Json member.

答:
Probably not the best solution, but you can write an adapter that typecasts the struct in base to the OS:

type OsName struct {
    Name string `json:"name"`
}

type LinuxOsName struct {
    Name string `json:"myName"`
}

func adapt(o OsName) interface{} {
    if o.Name == "Linux" {
        l := LinuxOsName(o)
        return &l
    }
    return &o
}

func print(o OsName) {
    b, err := json.Marshal(adapt(o))
    if err != nil {
        fmt.Printf("Error: %s\n", err)
    }
    fmt.Println(string(b))
}

```

https://go.dev/play/p/_M1orrGIP9p.go

Body:
I have a situation where my API return []byte {"name":"Windows"} on Windows and {"myName":"Linux"} on Linux, both are reporting OS Name but the key (name/MyName) is changed based on OS. How to Marshal/Unmarshal it to a JSON struct. Where I have single ember that can hold OS Name.

type OsName struct {
    Name   string `json:"name"` //I want to map Myname as well to this member.
}

Note: above question is not about how to get OS name, its about how to map 2 different keys to a single Json member.

Body:
Probably not the best solution, but you can write an adapter that typecasts the struct in base to the OS:

type OsName struct {
    Name string `json:"name"`
}

type LinuxOsName struct {
    Name string `json:"myName"`
}

func adapt(o OsName) interface{} {
    if o.Name == "Linux" {
        l := LinuxOsName(o)
        return &l
    }
    return &o
}

func print(o OsName) {
    b, err := json.Marshal(adapt(o))
    if err != nil {
        fmt.Printf("Error: %s\n", err)
    }
    fmt.Println(string(b))
}

https://go.dev/play/p/_M1orrGIP9p.go


问:
Installation failed with message Failed to create install session with 'cmd package install-create -r -t -S 1647504'
I am getting an error message while trying to run an apk through android studio 3.4.1

Installation failed with message Failed to create install session with 'cmd package install-create -r -t -S 1647504'.
It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing.

i have tried cleaning the project, rebuilding the project and unchecking the instant run option as well, none of them seems to have worked

答:
I fixed this problem by "wipe data".
for fix this problem go to AVD manager and select your Simulator and then select "wipe data" from dropdown menu</p>


问:
java.lang.ClassCastException: CommonsMultipartFile cannot be cast to oracle.sql.BFILE
I am working on a screen which will upload a file to oracle table as BFILE type. I am using spring3 and hibernate3.

The BO class look like:

```<code>@Entity
@Table(name="abc_manuals")
public class ManualBo implements Serializable {

/* Persistent Fields */
@Id
@Column(name="id", nullable=false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long  mId;

@Column(name="guide")
@Type(type="com.bo.entity.BFILEType")
private BFILE guide;

public Long getMlId() {
    return mlId;
}
public void setMId(Long manualId) {
    this.mId = mId;
}

public BFILE getGuide() {
    return guide;
}
public void setGuide(BFILE guide) {
    guide = guide;
}

}
</code>```

I have defined a BFILE userType:

```<code>public class BFILEType implements UserType, Serializable {

@SuppressWarnings("unused")
private static final String MARK_EMPTY = "<EmptyString/>";
private static final int[] TYPES = { OracleTypes.BFILE  };

public int[] sqlTypes() {
    return TYPES;
}

@SuppressWarnings("rawtypes")
public Class returnedClass() {
    return BFILE.class;
}

public boolean equals(Object x, Object y) {
    if (x==y) return true;
    if (x==null || y==null) return false;
    return x.equals(y);
}

public Object deepCopy(Object x) {
    return x;
}

public boolean isMutable() { return false; }

   public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws
   HibernateException, SQLException {
    BFILE bfile = (BFILE)rs.getObject(names[0]);
    return bfile;
}

public void nullSafeSet(PreparedStatement st, Object value, int index) throws
     HibernateException, SQLException {
    if(value==null)
        st.setObject(index, null);
    else
        st.setObject(index, value, OracleTypes.BFILE);
}

public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return deepCopy(arg0);
}

public Serializable disassemble(Object value) {
    return (Serializable) deepCopy(value);
}

public int hashCode(Object arg0) throws HibernateException {
    return arg0.hashCode();
}

public Object replace(Object arg0, Object arg1, Object arg2) throws
     HibernateException {
    return deepCopy(arg0);
}
</code>```

}

Problem is when I am trying to setFile in controller

manual.setGuide((oracle.sql.BFILE) form.getFile());

it is compiling well but when I upload file from screen it is giving following exception

java.lang.ClassCastException: org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to oracle.sql.BFILE

How to solve this?

Solved :

I tried :

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        if (value == null) {
            st.setObject(index, null);
        } else {

```<code>        OracleConnection oc = (OracleConnection) st.getConnection();
        OraclePreparedStatement opst = (OraclePreparedStatement) st;

        OracleCallableStatement ocs = (OracleCallableStatement) oc.prepareCall("{? = call BFILENAME('" + directory + "', '"+ filename + "')}");

        ocs.registerOutParameter(1, OracleTypes.BFILE);
        ocs.execute();
        BFILE bfile = ocs.getBFILE(1);
        opst.setBFILE(index, bfile);
    }
}
</code>```

and its working fine.

Thanks!

答: CommonsMultipartFile represents multipart form request, i.e. a collection of fields. You have to extract your file from the field, i.e. call getFileItem() or getInputStream() to extract the file content.

Body:
I am working on a screen which will upload a file to oracle table as BFILE type. I am using spring3 and hibernate3.

The BO class look like:

@Entity
@Table(name="abc_manuals")
public class ManualBo implements Serializable {

/* Persistent Fields */
@Id
@Column(name="id", nullable=false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long  mId;

@Column(name="guide")
@Type(type="com.bo.entity.BFILEType")
private BFILE guide;

public Long getMlId() {
    return mlId;
}
public void setMId(Long manualId) {
    this.mId = mId;
}

public BFILE getGuide() {
    return guide;
}
public void setGuide(BFILE guide) {
    guide = guide;
}

}

I have defined a BFILE userType:

public class BFILEType implements UserType, Serializable {

@SuppressWarnings("unused")
private static final String MARK_EMPTY = "<EmptyString/>";
private static final int[] TYPES = { OracleTypes.BFILE  };

public int[] sqlTypes() {
    return TYPES;
}

@SuppressWarnings("rawtypes")
public Class returnedClass() {
    return BFILE.class;
}

public boolean equals(Object x, Object y) {
    if (x==y) return true;
    if (x==null || y==null) return false;
    return x.equals(y);
}

public Object deepCopy(Object x) {
    return x;
}

public boolean isMutable() { return false; }

   public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws
   HibernateException, SQLException {
    BFILE bfile = (BFILE)rs.getObject(names[0]);
    return bfile;
}

public void nullSafeSet(PreparedStatement st, Object value, int index) throws
     HibernateException, SQLException {
    if(value==null)
        st.setObject(index, null);
    else
        st.setObject(index, value, OracleTypes.BFILE);
}

public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return deepCopy(arg0);
}

public Serializable disassemble(Object value) {
    return (Serializable) deepCopy(value);
}

public int hashCode(Object arg0) throws HibernateException {
    return arg0.hashCode();
}

public Object replace(Object arg0, Object arg1, Object arg2) throws
     HibernateException {
    return deepCopy(arg0);
}

}

Problem is when I am trying to setFile in controller

manual.setGuide((oracle.sql.BFILE) form.getFile());

it is compiling well but when I upload file from screen it is giving following exception

java.lang.ClassCastException: org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to oracle.sql.BFILE

How to solve this?

Solved :

I tried :

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        if (value == null) {
            st.setObject(index, null);
        } else {

        OracleConnection oc = (OracleConnection) st.getConnection();
        OraclePreparedStatement opst = (OraclePreparedStatement) st;

        OracleCallableStatement ocs = (OracleCallableStatement) oc.prepareCall("{? = call BFILENAME('" + directory + "', '"+ filename + "')}");

        ocs.registerOutParameter(1, OracleTypes.BFILE);
        ocs.execute();
        BFILE bfile = ocs.getBFILE(1);
        opst.setBFILE(index, bfile);
    }
}

and its working fine.

Thanks!


问:
Configuration with name 'integrationTestCompile' not found
when trying to upgrade my gradle version from 5.x to 7.x, getting below error

```<code>
* What went wrong:
Configuration with name 'integrationTestCompile' not found.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

</code>```

Below is my code

```<code>sourceSets {
    create("integrationTest") {
        compileClasspath += sourceSets.main.get().output
        runtimeClasspath += sourceSets.main.get().output
        runtimeClasspath += sourceSets.test.get().output
    }
}

val integrationTestCompile: Configuration by configurations.getting {
    extendsFrom(configurations.testImplementation.get())
}
val integrationTestRuntimeOnly: Configuration by configurations.getting {
    extendsFrom(configurations.testRuntimeOnly.get())
}

tasks {
    val integrationTest by creating(Test::class) {
        description = "Running integration tests."
        group = "verification"

        testClassesDirs = sourceSets["integrationTest"].output.classesDirs
        classpath = sourceSets["integrationTest"].runtimeClasspath
        shouldRunAfter("test")
    }
}
</code>```

Using gradle with kotlin.

How to fix this?

答:
In below way you can create integrationTest task in gradle latest version

```<code>configurations {
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntimeOnly.extendsFrom runtimeOnly
}

sourceSets {
    integrationTest {
        compileClasspath += sourceSets.main.output
        compileClasspath += configurations['testRuntimeClasspath']
        runtimeClasspath += compileClasspath
    }
}

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath

    mustRunAfter test
}
</code>```

Body:
when trying to upgrade my gradle version from 5.x to 7.x, getting below error

* What went wrong:
Configuration with name 'integrationTestCompile' not found.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

Below is my code

sourceSets {
    create("integrationTest") {
        compileClasspath += sourceSets.main.get().output
        runtimeClasspath += sourceSets.main.get().output
        runtimeClasspath += sourceSets.test.get().output
    }
}

val integrationTestCompile: Configuration by configurations.getting {
    extendsFrom(configurations.testImplementation.get())
}
val integrationTestRuntimeOnly: Configuration by configurations.getting {
    extendsFrom(configurations.testRuntimeOnly.get())
}

tasks {
    val integrationTest by creating(Test::class) {
        description = "Running integration tests."
        group = "verification"

        testClassesDirs = sourceSets["integrationTest"].output.classesDirs
        classpath = sourceSets["integrationTest"].runtimeClasspath
        shouldRunAfter("test")
    }
}

Using gradle with kotlin.

How to fix this?

Body:
In below way you can create integrationTest task in gradle latest version

configurations {
    integrationTestImplementation.extendsFrom testImplementation
    integrationTestRuntimeOnly.extendsFrom runtimeOnly
}

sourceSets {
    integrationTest {
        compileClasspath += sourceSets.main.output
        compileClasspath += configurations['testRuntimeClasspath']
        runtimeClasspath += compileClasspath
    }
}

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath

    mustRunAfter test
}