问:
jest mocking and setting up default behavior
There is a function I need to unit test:

```<code>const readiness = require("./readiness");

function stopProcessNewRequests(){
    readiness.setNotReady();
}

</code>```

Here is my "readiness" file:

```<code>const state = require("./state");
const hooks = require("./hooks");

function setReady(){
    state.ready = true;
    hooks.notifyHook(state.ready);
}

function setNotReady(){
    state.ready = false;
    hooks.notifyHook(state.ready);
}

module.exports = {
    setReady, setNotReady
};
</code>```

and finally, the state.js file:

```<code>
exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;
</code>```

As you can see, there are multiple chained imports, how do I mock them? I need my state file to be of certain values in order to check if it actually changes.
Here's what I have, but state does not seem to change, and the test fails.

```<code>describe('Testing processing new requests:', ()=> {
        test('should stop processing new requests:', ()=> {
            // jest.mock('../lib/grpc/readiness',);
            jest.mock('../lib/grpc/state');

            const state = require("../lib/grpc/state");
            const { stopProcessNewRequests } = require('../lib/grpc/requestsManager');

            state.ready = true;

            stopProcessNewRequests();

            expect(state.ready).toBeFalsy();
        })
    })
</code>```

答:
It is best not to test across modules. Which means for testing requestsManager module, you should mock readiness module, not indirectly module state and hooks. Besides, jest.mock should NOT be used in function scope, it should be used in module scope.

E.g.

readiness.js:

const state = require('./state');
const hooks = require('./hooks');

function setReady() {
  state.ready = true;
  hooks.notifyHook(state.ready);
}

function setNotReady() {
  state.ready = false;
  hooks.notifyHook(state.ready);
}

module.exports = {
  setReady,
  setNotReady,
};
```

<p><code>hooks.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>function notifyHook() {}

module.exports = { notifyHook };
</code>```

requestsManager.js:

const readiness = require('./readiness');

function stopProcessNewRequests() {
  readiness.setNotReady();
}

module.exports = { stopProcessNewRequests };
```

<p><code>state.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;
</code>```

Below are test files:

requestsManager.test.js:

const { stopProcessNewRequests } = require('./requestsManager');
const readiness = require('./readiness');

describe('62057531', () => {
  it('should pass', () => {
    const setNotReadyMock = jest.spyOn(readiness, 'setNotReady').mockReturnValueOnce();
    stopProcessNewRequests();
    expect(setNotReadyMock).toBeCalledTimes(1);
  });
});
```

<p><code>readiness.test.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>const { setNotReady, setReady } = require('./readiness');
const hooks = require('./hooks');
const state = require('./state');

describe('62057531', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should set state to not ready', () => {
    jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
    setNotReady();
    expect(hooks.notifyHook).toBeCalledWith(false);
    expect(state.ready).toBeFalsy();
  });

  it('should set state to ready', () => {
    jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
    setReady();
    expect(hooks.notifyHook).toBeCalledWith(true);
    expect(state.ready).toBeTruthy();
  });
});
</code>```

Unit test results with coverage report:

 PASS  stackoverflow/62057531/requestsManager.test.js (14.294s)
  62057531
    ✓ should pass (6ms)

 PASS  stackoverflow/62057531/readiness.test.js
  62057531
    ✓ should set state to not ready (5ms)
    ✓ should set state to ready (1ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files           |     100 |      100 |      75 |     100 |
 hooks.js           |     100 |      100 |       0 |     100 |
 readiness.js       |     100 |      100 |     100 |     100 |
 requestsManager.js |     100 |      100 |     100 |     100 |
 state.js           |     100 |      100 |     100 |     100 |
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 2 passed, 2 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        17.288s, estimated 21s
```

Body:
There is a function I need to unit test:

const readiness = require("./readiness");

function stopProcessNewRequests(){
    readiness.setNotReady();
}

Here is my "readiness" file:

const state = require("./state");
const hooks = require("./hooks");

function setReady(){
    state.ready = true;
    hooks.notifyHook(state.ready);
}

function setNotReady(){
    state.ready = false;
    hooks.notifyHook(state.ready);
}

module.exports = {
    setReady, setNotReady
};

and finally, the state.js file:

exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;

As you can see, there are multiple chained imports, how do I mock them? I need my state file to be of certain values in order to check if it actually changes.
Here's what I have, but state does not seem to change, and the test fails.

describe('Testing processing new requests:', ()=> {
        test('should stop processing new requests:', ()=> {
            // jest.mock('../lib/grpc/readiness',);
            jest.mock('../lib/grpc/state');

            const state = require("../lib/grpc/state");
            const { stopProcessNewRequests } = require('../lib/grpc/requestsManager');

            state.ready = true;

            stopProcessNewRequests();

            expect(state.ready).toBeFalsy();
        })
    })

Body:
It is best not to test across modules. Which means for testing requestsManager module, you should mock readiness module, not indirectly module state and hooks. Besides, jest.mock should NOT be used in function scope, it should be used in module scope.

E.g.

readiness.js:

const state = require('./state');
const hooks = require('./hooks');

function setReady() {
  state.ready = true;
  hooks.notifyHook(state.ready);
}

function setNotReady() {
  state.ready = false;
  hooks.notifyHook(state.ready);
}

module.exports = {
  setReady,
  setNotReady,
};

hooks.js:

function notifyHook() {}

module.exports = { notifyHook };

requestsManager.js:

const readiness = require('./readiness');

function stopProcessNewRequests() {
  readiness.setNotReady();
}

module.exports = { stopProcessNewRequests };

state.js:

exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;

Below are test files:

requestsManager.test.js:

const { stopProcessNewRequests } = require('./requestsManager');
const readiness = require('./readiness');

describe('62057531', () => {
  it('should pass', () => {
    const setNotReadyMock = jest.spyOn(readiness, 'setNotReady').mockReturnValueOnce();
    stopProcessNewRequests();
    expect(setNotReadyMock).toBeCalledTimes(1);
  });
});

readiness.test.js:

const { setNotReady, setReady } = require('./readiness');
const hooks = require('./hooks');
const state = require('./state');

describe('62057531', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should set state to not ready', () => {
    jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
    setNotReady();
    expect(hooks.notifyHook).toBeCalledWith(false);
    expect(state.ready).toBeFalsy();
  });

  it('should set state to ready', () => {
    jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
    setReady();
    expect(hooks.notifyHook).toBeCalledWith(true);
    expect(state.ready).toBeTruthy();
  });
});

Unit test results with coverage report:

 PASS  stackoverflow/62057531/requestsManager.test.js (14.294s)
  62057531
    ✓ should pass (6ms)

 PASS  stackoverflow/62057531/readiness.test.js
  62057531
    ✓ should set state to not ready (5ms)
    ✓ should set state to ready (1ms)

--------------------|---------|----------|---------|---------|-------------------
File                | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files           |     100 |      100 |      75 |     100 |
 hooks.js           |     100 |      100 |       0 |     100 |
 readiness.js       |     100 |      100 |     100 |     100 |
 requestsManager.js |     100 |      100 |     100 |     100 |
 state.js           |     100 |      100 |     100 |     100 |
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 2 passed, 2 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        17.288s, estimated 21s


来源: stackexchange

问:
Generating binary entries array in python
I would like to generate an array as follows:

```<code>[[0,0,0],
 [0,0,1],
 [0,1,0],
 [0,1,1],
 [1,0,0],
 [1,0,1],
 [1,1,0]
 [1,1,1]]
</code>```

I tried to achieve this by setting 3 for loops, but I wish to go further to 4, 5, and higher bit-numbers, so the last method would not scale easly to these numbers.

Is there any simple way for doing this?

ContentLicense: CC BY-SA 4.0

Body:
I would like to generate an array as follows:

[[0,0,0],
 [0,0,1],
 [0,1,0],
 [0,1,1],
 [1,0,0],
 [1,0,1],
 [1,1,0]
 [1,1,1]]

I tried to achieve this by setting 3 for loops, but I wish to go further to 4, 5, and higher bit-numbers, so the last method would not scale easly to these numbers.

Is there any simple way for doing this?

Body:
I can't figure out why you want this, but here goes:

For 3:

>>> [[int(x) for x in "{0:03b}".format(y)] for y in range(8)]
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
>>>

For 5:

>>> [[int(x) for x in "{0:05b}".format(y)] for y in range(32)]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 1, 0], [0, 0, 1, 1, 1], [0, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 1], [0, 1, 1, 0, 0], [0, 1, 1, 0, 1], [0, 1, 1, 1, 0], [0, 1, 1, 1, 1], [1, 0, 0, 0, 0], [1, 0, 0, 0, 1], [1, 0, 0, 1, 0], [1, 0, 0, 1, 1], [1, 0, 1, 0, 0], [1, 0, 1, 0, 1], [1, 0, 1, 1, 0], [1, 0, 1, 1, 1], [1, 1, 0, 0, 0], [1, 1, 0, 0, 1], [1, 1, 0, 1, 0], [1, 1, 0, 1, 1], [1, 1, 1, 0, 0], [1, 1, 1, 0, 1], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1]]
>>>

Matching your formatting is harder.


问:
Calculating percentages with GROUP BY query
I have a table with 3 columns which looks like this:

```<code>File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
00003    2        2
00004    3        5
00005    4        3
00005    3        2
00006    2        3
Etc.
</code>```

I want to generate a query that outputs the following (for each user and rating, display the number of files as well as percentage of files):

```<code>User    Rating   Count   Percentage
-----------------------------------
1       1         3      .18
1       2         6      .35
1       3         8      .47
2       5         12     .75
2       3         4      .25
</code>```

With Postgresql, I know how to create a query that includes the first 3 columns using the following query, but I can't figure out how to calculate percentage within the GROUP BY:

```<code>SELECT
    User,
    Rating,
    Count(*)
FROM
    Results
GROUP BY
    User, Rating
ORDER BY
    User, Rating
</code>```

Here I want the percentage calculation to apply to each user/rating group.

答:
Alternatively, you can do the old-school way — arguably easier to grok:

```<code>select usr.User                   as User   ,
       usr.Rating                 as Rating ,
       usr.N                      as N      ,
       (100.0 * usr.N) / total.N as Pct
from ( select User, Rating , count(*) as N
       from Results
       group by User , Rating
     ) usr
join ( select User , count(*) as N
       from Results
       group by User
     ) total on total.User = usr.User
order by usr.User, usr.Rating
</code>```

Cheers!

ContentLicense: CC BY-SA 3.0

Body:
I have a table with 3 columns which looks like this:

File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
00003    2        2
00004    3        5
00005    4        3
00005    3        2
00006    2        3
Etc.

I want to generate a query that outputs the following (for each user and rating, display the number of files as well as percentage of files):

User    Rating   Count   Percentage
-----------------------------------
1       1         3      .18
1       2         6      .35
1       3         8      .47
2       5         12     .75
2       3         4      .25

With Postgresql, I know how to create a query that includes the first 3 columns using the following query, but I can't figure out how to calculate percentage within the GROUP BY:

SELECT
    User,
    Rating,
    Count(*)
FROM
    Results
GROUP BY
    User, Rating
ORDER BY
    User, Rating

Here I want the percentage calculation to apply to each user/rating group.

Body:
Alternatively, you can do the old-school way — arguably easier to grok:

select usr.User                   as User   ,
       usr.Rating                 as Rating ,
       usr.N                      as N      ,
       (100.0 * usr.N) / total.N as Pct
from ( select User, Rating , count(*) as N
       from Results
       group by User , Rating
     ) usr
join ( select User , count(*) as N
       from Results
       group by User
     ) total on total.User = usr.User
order by usr.User, usr.Rating

Cheers!


问:
What is Amazon Lex inbuilt slot type for description or notes?
I have configured my AWS Lex bot to 'Schedule A Meeting' and 'Add Notes' tasks.

While meeting scheduling I have a slot 'Meeting Description' where user can add single word to a sentence. Similarly for adding notes I have 'Notes'.

For this slot I am not finding any inbuilt slot type like 'AMAZON.Description' or anything which can store a word or a sentence. I tried with 'AMAZON.VideoGame', 'AMAZON.FoodEstablishment' etc. But found intermittent issue with those. Some times they work and some times they don't.

Does any body know what type of slot type I can use for my case? Please share.

答:
You will want to use a Custom SlotType if you want to catch an input of anything.

When you "train" this SlotType by giving it values, you should include a wide variety, such as numbers, single letters, single words, phrases, and whole sentences.

Even that won't always catch what you want though. So even better than that, is to use your Lambda Function to parse and validate the entire input yourself. And most likely, just set your slot value to be the entire input string.

For example:

User: "Add to my notes"

  Bot: "Ok, what would you like me to save in your notes?"

  User: "Buy more toilet paper."

Now the user expects the entire phrase to be in the note. You will have to use utterances in your Custom SlotType like this:

I want to {note}

  Go {note}

  Buy {note}

  {note}

Those utterances will sometimes leave out some words and in the example, place only "more toilet paper" without the "buy" as your slot value. This is why you will want to parse the entire input yourself. So in Lambda you can get the entire input from inputTranscript.

```<code>userInput = event.inputTranscript            // "Buy more toilet paper"
slotNote = event.currentIntent.slots.note    // "more toilet paper"
</code>```

Then you can compare those two and do some fancy validation yourself, or just save the user input directly into the note slot.

```<code>userInput = event.inputTranscript            // "Buy more toilet paper"
event.currentIntent.slots.note = userInput   // overwrites note slot value with correct full user input.
</code>```

Body:
You will want to use a Custom SlotType if you want to catch an input of anything.

When you "train" this SlotType by giving it values, you should include a wide variety, such as numbers, single letters, single words, phrases, and whole sentences.

Even that won't always catch what you want though. So even better than that, is to use your Lambda Function to parse and validate the entire input yourself. And most likely, just set your slot value to be the entire input string.

For example:

User: "Add to my notes"

  Bot: "Ok, what would you like me to save in your notes?"

  User: "Buy more toilet paper."

Now the user expects the entire phrase to be in the note. You will have to use utterances in your Custom SlotType like this:

I want to {note}

  Go {note}

  Buy {note}

  {note}

Those utterances will sometimes leave out some words and in the example, place only "more toilet paper" without the "buy" as your slot value. This is why you will want to parse the entire input yourself. So in Lambda you can get the entire input from inputTranscript.

userInput = event.inputTranscript            // "Buy more toilet paper"
slotNote = event.currentIntent.slots.note    // "more toilet paper"

Then you can compare those two and do some fancy validation yourself, or just save the user input directly into the note slot.

userInput = event.inputTranscript            // "Buy more toilet paper"
event.currentIntent.slots.note = userInput   // overwrites note slot value with correct full user input.


问:
Input type number doesn't render the value from edit mode
I have a form which have input field type number.
So, when i try to edit that form it shows all the value from the database.
But in Input type field it doesn't show any value . Even if there is value when i inspect but it doesnt show in browser.

```<code> <input type="number" value="@if(!empty($salary->salary)){{$salary->salary}} @endif" name="salary" class="form-control" id="inputsalary" placeholder="salary">
</code>```

value inside input type number it doesn't show in browser

答:
Try this:

```<code><input type="number" value="{{ $salary->salary ? $salary->salary : ''}}" name="salary" class="form-control" id="inputsalary" placeholder="salary">
</code>```

Hope it helps.

Body:
I have a form which have input field type number.
So, when i try to edit that form it shows all the value from the database.
But in Input type field it doesn't show any value . Even if there is value when i inspect but it doesnt show in browser.

 <input type="number" value="@if(!empty($salary->salary)){{$salary->salary}} @endif" name="salary" class="form-control" id="inputsalary" placeholder="salary">

value inside input type number it doesn't show in browser

Body:
Try this:

<input type="number" value="{{ $salary->salary ? $salary->salary : ''}}" name="salary" class="form-control" id="inputsalary" placeholder="salary">

Hope it helps.


问:
C ++ How to change the value of 4 bits in a 32 bit number
I have a 32-bit register that I need to manipulate. But I only need to change bits 12-15, and leave the rest of the bits unchanged.

I want to overwrite whatever is in bits 12-15 with 0x2 or 0b0010.

How can I do this in C++?

Here is an example code I have been trying.

```<code>#include <iostream>
#include <bitset>

using namespace std;

int main() {
    uint32_t x = 0x4D00D0F0;

    x |= 0x2 << 12; // shifting 0x2 12 bits to the left

    return 0;
}
</code>```

My solution only seems to shift a 1 to bit 13, why is that?

Can I shift an entire 4-bit hex number?

Bottom line, I want x = 0x4D0020F0

答:
In general x = (x & ~mask) | (y & mask) copies the bits in mask position from y to x.

In OP's case mask = 0xF000 and y = 0x2000.

Body:
I have a 32-bit register that I need to manipulate. But I only need to change bits 12-15, and leave the rest of the bits unchanged.

I want to overwrite whatever is in bits 12-15 with 0x2 or 0b0010.

How can I do this in C++?

Here is an example code I have been trying.

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    uint32_t x = 0x4D00D0F0;

    x |= 0x2 << 12; // shifting 0x2 12 bits to the left

    return 0;
}

My solution only seems to shift a 1 to bit 13, why is that?

Can I shift an entire 4-bit hex number?

Bottom line, I want x = 0x4D0020F0


问:
How do I read the property values of a JSON error object using Combine in Swift?
All of my API endpoints return a response which looks something like this in Postman:

```<code>{
    "statusCode": 401,
    "error": "Unauthorized",
    "message": "Missing authentication"
}
</code>```

What I would like to do is make the request, and have access to these properties in Swift. There will be some cases where I use the error message property's value in the front of the app. This will be determined by the statusCode returned.

What I have right now is this:

```<code>    private var cancellable: AnyCancellable?
    let url = URL(string: "http://abc336699.com/create")
    self.cancellable = URLSession.shared.dataTaskPublisher(for: url!)
      .map { $0.data }
</code>```

Prior to this, I tried tryMap, but the type of error it returned didn't give me the flexibility I wanted. I then moved on and tried Almofire, but it seemed like an over kill for what I want to do.

I wanted to check what is being returned in the response I get, but I get the following error:

```<code>Cannot assign value of type 'Publishers.Map<URLSession.DataTaskPublisher, Data>' to type 'AnyCancellable'
</code>```

I want simple access to my response errors so I can integrate the API throughout the app using combine.

答:
I am not sure from where you will be getting your data as in JSON response there is no Key for data. Before writing below code my understanding was that you want to check error and statusCode from the mentioned JSON response and then move forward with your business logic. The below code is to give you a vague idea of how we can do that.

```<code>    enum CustomError: Error {

    case custom(_ error: String)
    case unknownStatusCode
    case errorOccurred
}

let url = URL(string: "http://abc336699.com/create")

    func load() -> AnyPublisher<Data,CustomError> {
    URLSession.shared.dataTaskPublisher(for: url!)
        .map(\.data)
        .tryMap { (data) -> Data in
            let genericModel = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]

            if let statusCode = genericModel?["statusCode"] as? String {
                switch statusCode {
                case "200":
                    guard let data = genericModel?["message"] as? Data else {
                        throw CustomError.custom("Parsing error")
                    }
                    return data
                default:
                    if let error = genericModel?["error"] as? String {
                        throw CustomError.custom(error)
                    } else {
                        throw CustomError.unknownError
                    }
                }
            }
            throw CustomError.errorOccurred
    }
    .decode(type: YourCustomDecodableModel.self, decoder: JSONDecoder())
    .mapError({ $0 as? CustomError ?? CustomError.errorOccurred })
    .eraseToAnyPublisher()
}
</code>```

Body:
All of my API endpoints return a response which looks something like this in Postman:

{
    "statusCode": 401,
    "error": "Unauthorized",
    "message": "Missing authentication"
}

What I would like to do is make the request, and have access to these properties in Swift. There will be some cases where I use the error message property's value in the front of the app. This will be determined by the statusCode returned.

What I have right now is this:

    private var cancellable: AnyCancellable?
    let url = URL(string: "http://abc336699.com/create")
    self.cancellable = URLSession.shared.dataTaskPublisher(for: url!)
      .map { $0.data }

Prior to this, I tried tryMap, but the type of error it returned didn't give me the flexibility I wanted. I then moved on and tried Almofire, but it seemed like an over kill for what I want to do.

I wanted to check what is being returned in the response I get, but I get the following error:

Cannot assign value of type 'Publishers.Map<URLSession.DataTaskPublisher, Data>' to type 'AnyCancellable'

I want simple access to my response errors so I can integrate the API throughout the app using combine.

Body:
I am not sure from where you will be getting your data as in JSON response there is no Key for data. Before writing below code my understanding was that you want to check error and statusCode from the mentioned JSON response and then move forward with your business logic. The below code is to give you a vague idea of how we can do that.

    enum CustomError: Error {

    case custom(_ error: String)
    case unknownStatusCode
    case errorOccurred
}

let url = URL(string: "http://abc336699.com/create")

    func load() -> AnyPublisher<Data,CustomError> {
    URLSession.shared.dataTaskPublisher(for: url!)
        .map(\.data)
        .tryMap { (data) -> Data in
            let genericModel = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]

            if let statusCode = genericModel?["statusCode"] as? String {
                switch statusCode {
                case "200":
                    guard let data = genericModel?["message"] as? Data else {
                        throw CustomError.custom("Parsing error")
                    }
                    return data
                default:
                    if let error = genericModel?["error"] as? String {
                        throw CustomError.custom(error)
                    } else {
                        throw CustomError.unknownError
                    }
                }
            }
            throw CustomError.errorOccurred
    }
    .decode(type: YourCustomDecodableModel.self, decoder: JSONDecoder())
    .mapError({ $0 as? CustomError ?? CustomError.errorOccurred })
    .eraseToAnyPublisher()
}


问:
Sign In Google with Android not working error while connecting
Hi i am having a problem with my the google connexion.  Every time that the code is executed it goes in to the catch. I dont know why. I followed the steps from the Google tutorial and saw manyq questions related to that on stack but still not help me to solve this issue. Whe the code is runned it goes in to the catch and it shows the toast that i made. " error while .. ". </p>

<p>Here is what it looks like. I am posting the whole code for the authentification so everyone can analyze it and give me a solution if possible . </p>

```<code>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient= GoogleSignIn.getClient(this,gso);

        signInButton=(SignInButton)findViewById(R.id.googleButton);
        signInButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }
        });
        //pour google
        mAuthStateListener=new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser mFireBaseUser=mFirebaseAuth.getCurrentUser();
                if(mFireBaseUser != null){
                    Toast.makeText(LoginActivity.this,"you are logged in",Toast.LENGTH_SHORT).show();
                    Intent i= new Intent(LoginActivity.this, PrayersEvents.class);
                    startActivity(i);
                }
                else{
                    Toast.makeText(LoginActivity.this,"please login",Toast.LENGTH_SHORT).show();
                }
            }
        };
        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email=emailId.getText().toString();
                String pwd=password.getText().toString();
                if (email.isEmpty()) {
                    emailId.setError("Please enter email");
                    emailId.requestFocus();
                }
                else if(pwd.isEmpty()){
                    password.setError("Please enter your password");
                    password.requestFocus();
                }
                else if(email.isEmpty() || pwd.isEmpty()){
                    Toast.makeText(LoginActivity.this,"Fields are empty!",Toast.LENGTH_SHORT).show();
                }
                else if(!(email.isEmpty() && pwd.isEmpty())){
                    mFirebaseAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(!task.isSuccessful()){
                                Toast.makeText(LoginActivity.this,"Login error!",Toast.LENGTH_SHORT).show();

                            }
                            else{
                                Intent intoHome=new Intent(LoginActivity.this, PrayersEvents.class);
                                startActivity(intoHome);
                            }
                        }
                    });
                }
                else{
                    Toast.makeText(LoginActivity.this,"Error ocurred!",Toast.LENGTH_SHORT).show();

                }
            }
        });
        tvSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intoSignUp=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intoSignUp);
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();

        GoogleSignInAccount account=GoogleSignIn.getLastSignedInAccount(this);
        if(account !=null){
            startActivity(new Intent(LoginActivity.this, CreateEvent.class));
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                Log.d("MON_TAG", account.toString());
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Toast.makeText(getApplicationContext(),"error while logging in",Toast.LENGTH_SHORT).show();

                Log.w("errorMsg","Google sign in failed", e);
                // ...
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {//acct means account
        Log.d("MON_TAG", "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mFirebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d("MON_TAG", "signInWithCredential:success");
                            FirebaseUser user = mFirebaseAuth.getCurrentUser();
                            startActivity(new Intent(LoginActivity.this, CreateEvent.class));
                            Toast.makeText(getApplicationContext(),"You are now connected",Toast.LENGTH_SHORT).show();
                        } else {
                            GoogleSignInAccount account=GoogleSignIn.getLastSignedInAccount(getApplicationContext());
                            if(account !=null){
                                startActivity(new Intent(LoginActivity.this, CreateEvent.class));
                            }
                            // If sign in fails, display a message to the user.
                            Toast.makeText(getApplicationContext(),"Could not log in user",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

</code>```

答:
I think you didn't instanciate the GoogleApiClient object..

try this code .. it worked for me ..

```<code>//a constant for detecting the login intent result
    private static final int RC_SIGN_IN = 234;

    //Tag for the logs optional
    private static final String TAG = "YoussefIslem";

    //creating a GoogleSignInClient object
    GoogleSignInClient mGoogleSignInClient;

    GoogleApiClient googleApiClient;

    CallbackManager mCallbackManager;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.web_client_id))
                .requestEmail()
                .build();

        googleApiClient =new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();

        //Then we will get the GoogleSignInClient object from GoogleSignIn class
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        findViewById(R.id.googleContinue).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
}

 private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        //getting the auth credential
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

        //Now using firebase we are signing in the user here
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();

                            Toast.makeText(MainActivity.this, "User Signed In", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                            startActivity(intent);
                            finish();

                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();

                        }

                        // ...
                    }
                });
    }

    //this method is called on click
    private void signIn() {
        //getting the google signin intent
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        googleApiClient.clearDefaultAccountAndReconnect();

        //starting the activity for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //if the requestCode is the Google Sign In code that we defined at starting
        if (requestCode == RC_SIGN_IN) {

            //Getting the GoogleSignIn Task
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                //Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);

                //authenticating with firebase
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Toast.makeText(MainActivity.this,"I'm here"+ e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
}
</code>```

Body:
Hi i am having a problem with my the google connexion.  Every time that the code is executed it goes in to the catch. I dont know why. I followed the steps from the Google tutorial and saw manyq questions related to that on stack but still not help me to solve this issue. Whe the code is runned it goes in to the catch and it shows the toast that i made. " error while .. ".

Here is what it looks like. I am posting the whole code for the authentification so everyone can analyze it and give me a solution if possible .

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient= GoogleSignIn.getClient(this,gso);

        signInButton=(SignInButton)findViewById(R.id.googleButton);
        signInButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }
        });
        //pour google
        mAuthStateListener=new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser mFireBaseUser=mFirebaseAuth.getCurrentUser();
                if(mFireBaseUser != null){
                    Toast.makeText(LoginActivity.this,"you are logged in",Toast.LENGTH_SHORT).show();
                    Intent i= new Intent(LoginActivity.this, PrayersEvents.class);
                    startActivity(i);
                }
                else{
                    Toast.makeText(LoginActivity.this,"please login",Toast.LENGTH_SHORT).show();
                }
            }
        };
        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email=emailId.getText().toString();
                String pwd=password.getText().toString();
                if (email.isEmpty()) {
                    emailId.setError("Please enter email");
                    emailId.requestFocus();
                }
                else if(pwd.isEmpty()){
                    password.setError("Please enter your password");
                    password.requestFocus();
                }
                else if(email.isEmpty() || pwd.isEmpty()){
                    Toast.makeText(LoginActivity.this,"Fields are empty!",Toast.LENGTH_SHORT).show();
                }
                else if(!(email.isEmpty() && pwd.isEmpty())){
                    mFirebaseAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if(!task.isSuccessful()){
                                Toast.makeText(LoginActivity.this,"Login error!",Toast.LENGTH_SHORT).show();

                            }
                            else{
                                Intent intoHome=new Intent(LoginActivity.this, PrayersEvents.class);
                                startActivity(intoHome);
                            }
                        }
                    });
                }
                else{
                    Toast.makeText(LoginActivity.this,"Error ocurred!",Toast.LENGTH_SHORT).show();

                }
            }
        });
        tvSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intoSignUp=new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intoSignUp);
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();

        GoogleSignInAccount account=GoogleSignIn.getLastSignedInAccount(this);
        if(account !=null){
            startActivity(new Intent(LoginActivity.this, CreateEvent.class));
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                Log.d("MON_TAG", account.toString());
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Toast.makeText(getApplicationContext(),"error while logging in",Toast.LENGTH_SHORT).show();

                Log.w("errorMsg","Google sign in failed", e);
                // ...
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {//acct means account
        Log.d("MON_TAG", "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mFirebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d("MON_TAG", "signInWithCredential:success");
                            FirebaseUser user = mFirebaseAuth.getCurrentUser();
                            startActivity(new Intent(LoginActivity.this, CreateEvent.class));
                            Toast.makeText(getApplicationContext(),"You are now connected",Toast.LENGTH_SHORT).show();
                        } else {
                            GoogleSignInAccount account=GoogleSignIn.getLastSignedInAccount(getApplicationContext());
                            if(account !=null){
                                startActivity(new Intent(LoginActivity.this, CreateEvent.class));
                            }
                            // If sign in fails, display a message to the user.
                            Toast.makeText(getApplicationContext(),"Could not log in user",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

Body:
I think you didn't instanciate the GoogleApiClient object..

try this code .. it worked for me ..

//a constant for detecting the login intent result
    private static final int RC_SIGN_IN = 234;

    //Tag for the logs optional
    private static final String TAG = "YoussefIslem";

    //creating a GoogleSignInClient object
    GoogleSignInClient mGoogleSignInClient;

    GoogleApiClient googleApiClient;

    CallbackManager mCallbackManager;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.web_client_id))
                .requestEmail()
                .build();

        googleApiClient =new GoogleApiClient.Builder(this)
                .enableAutoManage(this,this)
                .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                .build();

        //Then we will get the GoogleSignInClient object from GoogleSignIn class
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        findViewById(R.id.googleContinue).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                signIn();
            }
        });
}

 private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

        //getting the auth credential
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

        //Now using firebase we are signing in the user here
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();

                            Toast.makeText(MainActivity.this, "User Signed In", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                            startActivity(intent);
                            finish();

                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();

                        }

                        // ...
                    }
                });
    }

    //this method is called on click
    private void signIn() {
        //getting the google signin intent
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        googleApiClient.clearDefaultAccountAndReconnect();

        //starting the activity for result
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //if the requestCode is the Google Sign In code that we defined at starting
        if (requestCode == RC_SIGN_IN) {

            //Getting the GoogleSignIn Task
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                //Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);

                //authenticating with firebase
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                Toast.makeText(MainActivity.this,"I'm here"+ e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
}


问:
I can not connect to Postgres DB with Strapi on Heroku
Trying to deploy Strapi on Heroku with Postgres as described here

https://strapi.io/documentation/v3.x/deployment/heroku.html

But I get this error

```<code>error: no pg_hba.conf entry for host "84.212.51.43", user "ssqqeaz***", database "d6gtu***", SSL off
</code>```

I use Heroku Postgres add-on.

My database config:

```<code>module.exports = ({ env }) => ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: 'postgres',
        host: env('DATABASE_HOST', '127.0.0.1'),
        port: env.int('DATABASE_PORT', 27017),
        database: env('DATABASE_NAME', 'strapi'),
        username: env('DATABASE_USERNAME', ''),
        password: env('DATABASE_PASSWORD', ''),
      },
      options: {
        ssl: true
      },
    },
  },
});

</code>```

Why? Please help!

答: try to change ssl : true into ssl : false

Body:
Trying to deploy Strapi on Heroku with Postgres as described here

https://strapi.io/documentation/v3.x/deployment/heroku.html

But I get this error

error: no pg_hba.conf entry for host "84.212.51.43", user "ssqqeaz***", database "d6gtu***", SSL off

I use Heroku Postgres add-on.

My database config:

module.exports = ({ env }) => ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'bookshelf',
      settings: {
        client: 'postgres',
        host: env('DATABASE_HOST', '127.0.0.1'),
        port: env.int('DATABASE_PORT', 27017),
        database: env('DATABASE_NAME', 'strapi'),
        username: env('DATABASE_USERNAME', ''),
        password: env('DATABASE_PASSWORD', ''),
      },
      options: {
        ssl: true
      },
    },
  },
});

Why? Please help!


问:
Add svg dynamically in bmpnjs
I am using the Bpmn-JS viewer library to display BPMN 2.0, I need only the viewer (I don't need an editor). I have an XML to draw.

I want to add balloons with a number in task dynamically (I get the number from an API related to each task)

How can I draw those balloons dynamically? Can I do it with the library?

Example:

答:
I can use overlay

```<code>viewer = new BpmnViewer();
viewer.attachTo('#container');
viewer.importXML(...)
</code>```

I can add overlays associated to task by id

```<code>const number = 4;
overlays = this.viewer.get('overlays');
overlays.add('taskId', {
   position: {
      top:0,
      right:0
   },
   html: `<div class='circle'>${number}</div>`
});
</code>```

Title: Add svg dynamically in bmpnjs

Body:
I can use overlay

viewer = new BpmnViewer();
viewer.attachTo('#container');
viewer.importXML(...)

I can add overlays associated to task by id

const number = 4;
overlays = this.viewer.get('overlays');
overlays.add('taskId', {
   position: {
      top:0,
      right:0
   },
   html: `<div class='circle'>${number}</div>`
});


问:
How do I launch a webpage from a XUL app within XULRunner?
What is the XULRunner equivalent of the following button handler?

```<code>function launch_page() {
    var win = Components.classes['@mozilla.org/appshell/window-mediator;1']
        .getService(Components.interfaces.nsIWindowMediator)
        .getMostRecentWindow('navigator:browser');
    win.openUILinkIn('http://www.google.com', 'window');
}
</code>```

This does not do anything in my XUL app that's installed to Program Files using XULRunner --install-app ./foo.xpi.

Is there any way for my XUL app to launch the user's default browser to display a web page on a button click?

答:
This works for now:

```<code>// first construct an nsIURI object using the ioservice
var ioservice = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);

var uriToOpen = ioservice.newURI("http://www.google.com/", null, null);

var extps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
    .getService(Components.interfaces.nsIExternalProtocolService);

// now, open it!
extps.loadURI(uriToOpen, null);
</code>```

Anybody got a more standard way?

Body:
What is the XULRunner equivalent of the following button handler?

function launch_page() {
    var win = Components.classes['@mozilla.org/appshell/window-mediator;1']
        .getService(Components.interfaces.nsIWindowMediator)
        .getMostRecentWindow('navigator:browser');
    win.openUILinkIn('http://www.google.com', 'window');
}

This does not do anything in my XUL app that's installed to Program Files using XULRunner --install-app ./foo.xpi.

Is there any way for my XUL app to launch the user's default browser to display a web page on a button click?

Body:
This works for now:

// first construct an nsIURI object using the ioservice
var ioservice = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);

var uriToOpen = ioservice.newURI("http://www.google.com/", null, null);

var extps = Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
    .getService(Components.interfaces.nsIExternalProtocolService);

// now, open it!
extps.loadURI(uriToOpen, null);

Anybody got a more standard way?


问:
Import community SwiftUI package with 13.0 target in iOS 10+ project
I'm working on a iOS project that need to support iOS 10+. I would like to build some new features with SwiftUI and make them only available for our iOS 13+ users by using @available(iOS 13.0, *).
 This works fine as long as I use only out of the box components.

However, when importing a community-made SwiftUI component that is targeted iOS 13 and up I get the following error:

```<code>Compiling for iOS 10.0, but module 'SwiftUIPager' has a minimum deployment target of iOS 13.0:
DerivedData/MyApp-qbarasdasdaasdbsp/Build/Products/Debug-iphonesimulator/SwiftUIPager.swiftmodule/x86_64-apple-ios-simulator.swiftmodule
</code>```

This makes sense because the module has set iOS 13+ as the SupportedPlatform. I've suggested the author to lower the target to iOS 10 and add @available(iOS 13.0, *)'s everywhere but of course that is also not ideal because it renders the SupportedPlatform attribute of SPM useless.

Is there a way of including packages like this in a project that wants to support lower a lower target than the package supports? Is this a flaw on the design of the Swift package manifest file?

答:
Here is a working solution. Tested with Xcode 11.4 / iOS 13.4

1) Create iOS framework target (let's name it ModernProxy for reference) with deployment target > 13.0 and make it dependent on modern SwiftUI based package (ModernLibrary in this demo), as on example below

2) Make your legacy target embed modern framework, as on example below

3) In ModelProxy framework create controller class with default non-argument init that wraps SwiftUI root UIHostingController with view from external package, as on example below

```<code>import SwiftUI
import ModernLibrary // SwiftUI based external package

public class ModernProxyController: UIHostingController<ModernView> {
    public init() {
        super.init(rootView: ModernView())
    }

    @objc required dynamic init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

and make this controller as framework's principal class (actually in more complex case the principal class can play some factory role to return many controllers by protocol, but here is one for simplicity)

4) In your main target ViewController (that one where you want to inject SwiftUI modern view) load dynamically proxy framework bundle and instantiate controller via principal class, as on below example

```<code>class ViewController : UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // ... any other code here

        if #available(iOS 13.0, *) {
            if let proxyClass = Bundle(identifier: "com.Testing.ModernProxy")?.principalClass as? UIViewController.Type {
                let controller = proxyClass.init()
                self.addChild(controller)
                controller.view.translatesAutoresizingMaskIntoConstraints = false
                view.addSubview(controller.view)
                // ... add any needed constraints
            }
        } else {
            // Fallback on earlier versions
        }
    }

    // ... other controller code here
</code>```

Body:
I'm working on a iOS project that need to support iOS 10+. I would like to build some new features with SwiftUI and make them only available for our iOS 13+ users by using @available(iOS 13.0, *).
 This works fine as long as I use only out of the box components.

However, when importing a community-made SwiftUI component that is targeted iOS 13 and up I get the following error:

Compiling for iOS 10.0, but module 'SwiftUIPager' has a minimum deployment target of iOS 13.0:
DerivedData/MyApp-qbarasdasdaasdbsp/Build/Products/Debug-iphonesimulator/SwiftUIPager.swiftmodule/x86_64-apple-ios-simulator.swiftmodule

This makes sense because the module has set iOS 13+ as the SupportedPlatform. I've suggested the author to lower the target to iOS 10 and add @available(iOS 13.0, *)'s everywhere but of course that is also not ideal because it renders the SupportedPlatform attribute of SPM useless.

Is there a way of including packages like this in a project that wants to support lower a lower target than the package supports? Is this a flaw on the design of the Swift package manifest file?

Body:
Here is a working solution. Tested with Xcode 11.4 / iOS 13.4

1) Create iOS framework target (let's name it ModernProxy for reference) with deployment target > 13.0 and make it dependent on modern SwiftUI based package (ModernLibrary in this demo), as on example below

2) Make your legacy target embed modern framework, as on example below

3) In ModelProxy framework create controller class with default non-argument init that wraps SwiftUI root UIHostingController with view from external package, as on example below

import SwiftUI
import ModernLibrary // SwiftUI based external package

public class ModernProxyController: UIHostingController<ModernView> {
    public init() {
        super.init(rootView: ModernView())
    }

    @objc required dynamic init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

and make this controller as framework's principal class (actually in more complex case the principal class can play some factory role to return many controllers by protocol, but here is one for simplicity)

4) In your main target ViewController (that one where you want to inject SwiftUI modern view) load dynamically proxy framework bundle and instantiate controller via principal class, as on below example

class ViewController : UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // ... any other code here

        if #available(iOS 13.0, *) {
            if let proxyClass = Bundle(identifier: "com.Testing.ModernProxy")?.principalClass as? UIViewController.Type {
                let controller = proxyClass.init()
                self.addChild(controller)
                controller.view.translatesAutoresizingMaskIntoConstraints = false
                view.addSubview(controller.view)
                // ... add any needed constraints
            }
        } else {
            // Fallback on earlier versions
        }
    }

    // ... other controller code here


问:
Keep getting the error MissingTranslationId

Note: This question is exclusively related to the library
  react-localize-redux but I cannot create a tag for it yet.

I want to use the allLanguages format. So I created a .json file named global.json that looks like this:

```<code>{
    "header": {
        "toggleNavigation": [
            "Cambiar navegación",
            "Toggle navigation"
        ],
        "home": [
            "Inicio",
            "Home"
        ],
        "company": [
            "Compañía",
            "Company"
        ]
    }
}
</code>```

I decided to implement everything in my Root component as follows:

```<code>...
import allTranslations from "../translations/global.json";
...

class Root extends Component {

  constructor(props) {
    super(props);

    this.props.initialize({
      languages: [
        { name: "Spanish", code: "es" },
        { name: "English", code: "en" }
      ],
      translation: allTranslations,
      options: {
        renderToStaticMarkup
      }
    });

    this.props.addTranslation(allTranslations); // just to make sure it's loading the json dictionary

    this.props.setActiveLanguage("es"); // Although Spanish was added first in the list of languages, I want to make sure the active language is Spanish
  }

  render() {
    const { store, history } = this.props;
    return (
      <LocalizeProvider>
        <Provider store={store}>
          <ConnectedRouter history={history}>
            <App />
          </ConnectedRouter>
        </Provider>
      </LocalizeProvider>
    );
  }
}

Root.propTypes = {
   ...
};

export default withLocalize(Root);
</code>```

Then, in a stateless controller named Header, I want to make use of the localize through the Translate component of the library.

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { Translate } from "react-localize-redux";

const Header = (props) => {

    return (
        <div className="header-container">
...
...
                        <ul className="nav navbar-nav navbar-right">
                            <li className="menu-item">
                               <a href="#one-page-home">
                                    <Translate id="header.home" />
                                </a>
                            </li>
                        </ul>
...
...
        </div>
    );
};

Header.propTypes = {
    ...
};

export default Header;
</code>```

I'm getting the error: Missing TranslationId: header.home for language: ${ languagecode }

I've followed the documentation but I don't know what I am doing wrong.

Any help? Something wrong that a more versed user of this great library can see at a first glance?

react version 16.4.2 and react-localize-redux version 3.4.1

答:
Maybe, at least was my case, I didn't wrap the whole render with <LocalizeProvider>

```<code>ReactDom.render(
<Provider store={store}>
    <LocalizeProvider initialize={{
        languages: [
        { name: "English", code: "en" },
        { name: "Spanish", code: "es" }
        ],
        translation: { home: ['hello', 'alo'] },
        options: {
        defaultLanguage: "en",
            renderToStaticMarkup: renderToStaticMarkup
        }
    }}>
        <BrowserRouter>
            <Switch>
            <Route exact path="/login" children={(props) => <Login {...props} /> } />
            <Route exact path="/dashboard" children={(props) => <Dashboard {...props} /> } />
            <Route exact path="/" children={(props) => <Home {...props} />} />
            </Switch>
        </BrowserRouter>
    </LocalizeProvider>
</Provider>, document.getElementById('root')
);
</code>```

Instead of this:

```<code>ReactDom.render(
<Provider store={store}>
    <LocalizeProvider initialize={{
        languages: [
        { name: "English", code: "en" },
        { name: "Spanish", code: "es" }
        ],
        translation: { home: ['hello', 'alo'] },
        options: {
        defaultLanguage: "en",
            renderToStaticMarkup: renderToStaticMarkup
        }
    }}>
        <BrowserRouter>
            <Switch>
            <Route exact path="/login" children={(props) => <Login {...props} /> } />
            <Route exact path="/dashboard" children={(props) => <Dashboard {...props} /> } />
            <Route exact path="/" children={(props) => <Home {...props} />} />
            </Switch>
        </BrowserRouter>
    </LocalizeProvider>
</Provider>, document.getElementById('root')
);
</code>```

Body:
Note: This question is exclusively related to the library
  react-localize-redux but I cannot create a tag for it yet.

I want to use the allLanguages format. So I created a .json file named global.json that looks like this:

{
    "header": {
        "toggleNavigation": [
            "Cambiar navegación",
            "Toggle navigation"
        ],
        "home": [
            "Inicio",
            "Home"
        ],
        "company": [
            "Compañía",
            "Company"
        ]
    }
}

I decided to implement everything in my Root component as follows:

...
import allTranslations from "../translations/global.json";
...

class Root extends Component {

  constructor(props) {
    super(props);

    this.props.initialize({
      languages: [
        { name: "Spanish", code: "es" },
        { name: "English", code: "en" }
      ],
      translation: allTranslations,
      options: {
        renderToStaticMarkup
      }
    });

    this.props.addTranslation(allTranslations); // just to make sure it's loading the json dictionary

    this.props.setActiveLanguage("es"); // Although Spanish was added first in the list of languages, I want to make sure the active language is Spanish
  }

  render() {
    const { store, history } = this.props;
    return (
      <LocalizeProvider>
        <Provider store={store}>
          <ConnectedRouter history={history}>
            <App />
          </ConnectedRouter>
        </Provider>
      </LocalizeProvider>
    );
  }
}

Root.propTypes = {
   ...
};

export default withLocalize(Root);

Then, in a stateless controller named Header, I want to make use of the localize through the Translate component of the library.

import React from 'react';
import PropTypes from 'prop-types';
import { Translate } from "react-localize-redux";

const Header = (props) => {

    return (

...
...

                                    <Translate id="header.home" />

...
...

    );
};

Header.propTypes = {
    ...
};

export default Header;

I'm getting the error: Missing TranslationId: header.home for language: ${ languagecode }

I've followed the documentation but I don't know what I am doing wrong.

Any help? Something wrong that a more versed user of this great library can see at a first glance?

react version 16.4.2 and react-localize-redux version 3.4.1

Body:
Maybe, at least was my case, I didn't wrap the whole render with <LocalizeProvider>

ReactDom.render(
<Provider store={store}>
    <LocalizeProvider initialize={{
        languages: [
        { name: "English", code: "en" },
        { name: "Spanish", code: "es" }
        ],
        translation: { home: ['hello', 'alo'] },
        options: {
        defaultLanguage: "en",
            renderToStaticMarkup: renderToStaticMarkup
        }
    }}>
        <BrowserRouter>
            <Switch>
            <Route exact path="/login" children={(props) => <Login {...props} /> } />
            <Route exact path="/dashboard" children={(props) => <Dashboard {...props} /> } />
            <Route exact path="/" children={(props) => <Home {...props} />} />
            </Switch>
        </BrowserRouter>
    </LocalizeProvider>
</Provider>, document.getElementById('root')
);

Instead of this:

ReactDom.render(
<Provider store={store}>
    <LocalizeProvider initialize={{
        languages: [
        { name: "English", code: "en" },
        { name: "Spanish", code: "es" }
        ],
        translation: { home: ['hello', 'alo'] },
        options: {
        defaultLanguage: "en",
            renderToStaticMarkup: renderToStaticMarkup
        }
    }}>
        <BrowserRouter>
            <Switch>
            <Route exact path="/login" children={(props) => <Login {...props} /> } />
            <Route exact path="/dashboard" children={(props) => <Dashboard {...props} /> } />
            <Route exact path="/" children={(props) => <Home {...props} />} />
            </Switch>
        </BrowserRouter>
    </LocalizeProvider>
</Provider>, document.getElementById('root')
);


问:
Session not created: This version of ChromeDriver only supports Chrome version 81
My current Browser version in 83.0.4103.61. I have updated Chrome driver to 83.0.4103.3900 from NuGet Package Manager.  Getting error "Session not created: This version of ChromeDriver only supports Chrome version 81" even after updating driver.  I am using Selenium WebDriver using C#.
Note: It works fine for new solutions.</p>

答:
Seems to be your machine does not have the latest chrome browser.
Either update the chrome browser or downgrade the chromedriver to 81.x.</p>


问:
Python - Iterating Through Multiple Dictionarys and Their Keys
I am attempting to create a program, where the user can input multiple lottery ticket numbers, and it will compare these numbers to a set of winning numbers. I know I can make it work by using several if statements, but I'm thinking there has to be a way to do this in a loop. I've tried a few loops that used "for key in ___", but I kept receiving errors.

amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
}

for i in range (0, amount, 1):
    tickets[i] = {
        '1': input('Input #1 '),
        '2': input('Input #2 '),
        '3': input('Input #3 '),
        '4': input('Input #4 '),
        '5': input('Input #5 '),
        '6': input('Input Powerball '),
    }

for i in range (0, len(tickets), 1):
    ticketMatch[i] = 0
    if tickets[i]['1'] in winingNumbers.values():
        ticketMatch[i] += 1
    if tickets[i]['2'] in winingNumbers.values():
        ticketMatch[i] += 1
```

Any tips or hints would be greatly appreciated. Thanks!

答:
Dictionaries make only sense if you have a key and store a value by it. Accessing the value of a key and checking if a key is part of a dictionary is fast (O(1)) - iterating all values of a dict is as slow as a list - but creating the dictionary is slower then creating a list and occupies more of your computers memory.

Using set operations avoid using if's cascades - for an example see further below.

Faster input in a loop can be done using split() and list decomposing *a,b=[1,2,3,4]:

```<code>for _ in range(int(input("How many tickets do you want to enter? "))):
    *nums, power = map(int,
         input( ("Input space seperated numbers of your ticket,"
                 " last one is Powerball: ") ).strip().split())
    print(nums, power)
</code>```

Output:

```<code>How many tickets do you want to enter? 3
Input space seperated numbers of your ticket, last one is Powerball: 1 2 3 4 99
    [1, 2, 3, 4] 99
Input space seperated numbers of your ticket, last one is Powerball: 2 3 4 7 199
    [2, 3, 4, 7] 199
Input space seperated numbers of your ticket, last one is Powerball: 4 2 4 5 6
    [4, 2, 4, 5] 6
</code>```

(Although some more checking might be appropirate for Users that do not enter numebrs at all or too few/out of range ones: Asking the user for input until they give a valid response )

For lotto comparisons a list of  "tickets" with a set() of numbers each can be fastly checked correct numbers using set-operations.

Checking the list of tickets will be O(n) (with n == amount of tickets) - checking if numbers match your winning numbers is fast: O(1) and avoids if ..:.

You could do this like so (fully random example):

```<code>import random

def random_nums():
    """Returns a tuple of a frozenset of 5 numbers in the range [1..69]
    and one number in the range of [1..26] (aka: USA Powerball Lottery)"""
    return ( frozenset(random.sample(range(1,70), 5)), random.choice(range(1,27)) )

# draw the win-numbers
winning_nums = set(random.sample(range(1,70), 5))
powerball = random.choice(range(1,27))
# print them
print("Winner: ", *winning_nums, "   Powerball: ", powerball)

# generate random tickets
tickets = [ random_nums() for _ in range(10) ]

# check if ticket got something in common with winner numbers
for (nums, power) in tickets:
    # fast set operations
    intersect = sorted(nums.intersection(winning_nums))
    wrong = sorted(nums.difference(winning_nums))
    p = 'correct' if power == powerball else 'wrong'
    n = "'nothing'"
    # some output
    print( ( f"You got {intersect or n} correct and guessed "
             f"{wrong or n} wrong. Powerball: {p}.") )
</code>```

Output:

```<code>Winner:  14 49 26 27 60    Powerball:  6

You got [49] correct and guessed [21, 41, 59, 66] wrong. Powerball: wrong.
You got [60] correct and guessed [17, 19, 63, 68] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [10, 21, 51, 67, 69] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [18, 30, 40, 45, 52] wrong. Powerball: wrong.
You got [26, 27] correct and guessed [11, 37, 58] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [28, 33, 38, 59, 65] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [11, 18, 35, 61, 64] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [2, 3, 47, 54, 63] wrong. Powerball: wrong.
You got [14] correct and guessed [23, 25, 58, 66] wrong. Powerball: wrong.
You got [27] correct and guessed [47, 52, 56, 58] wrong. Powerball: correct.
</code>```

See:

Whats the fuss about the Big O of algorythms

set operations

Body:
I am attempting to create a program, where the user can input multiple lottery ticket numbers, and it will compare these numbers to a set of winning numbers. I know I can make it work by using several if statements, but I'm thinking there has to be a way to do this in a loop. I've tried a few loops that used "for key in ___", but I kept receiving errors.

amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
}

for i in range (0, amount, 1):
    tickets[i] = {
        '1': input('Input #1 '),
        '2': input('Input #2 '),
        '3': input('Input #3 '),
        '4': input('Input #4 '),
        '5': input('Input #5 '),
        '6': input('Input Powerball '),
    }

for i in range (0, len(tickets), 1):
    ticketMatch[i] = 0
    if tickets[i]['1'] in winingNumbers.values():
        ticketMatch[i] += 1
    if tickets[i]['2'] in winingNumbers.values():
        ticketMatch[i] += 1

Any tips or hints would be greatly appreciated. Thanks!

Body:
Dictionaries make only sense if you have a key and store a value by it. Accessing the value of a key and checking if a key is part of a dictionary is fast (O(1)) - iterating all values of a dict is as slow as a list - but creating the dictionary is slower then creating a list and occupies more of your computers memory.

Using set operations avoid using if's cascades - for an example see further below.

Faster input in a loop can be done using split() and list decomposing *a,b=[1,2,3,4]:

for _ in range(int(input("How many tickets do you want to enter? "))):
    *nums, power = map(int,
         input( ("Input space seperated numbers of your ticket,"
                 " last one is Powerball: ") ).strip().split())
    print(nums, power)

Output:

How many tickets do you want to enter? 3
Input space seperated numbers of your ticket, last one is Powerball: 1 2 3 4 99
    [1, 2, 3, 4] 99
Input space seperated numbers of your ticket, last one is Powerball: 2 3 4 7 199
    [2, 3, 4, 7] 199
Input space seperated numbers of your ticket, last one is Powerball: 4 2 4 5 6
    [4, 2, 4, 5] 6

(Although some more checking might be appropirate for Users that do not enter numebrs at all or too few/out of range ones: Asking the user for input until they give a valid response )

For lotto comparisons a list of  "tickets" with a set() of numbers each can be fastly checked correct numbers using set-operations.

Checking the list of tickets will be O(n) (with n == amount of tickets) - checking if numbers match your winning numbers is fast: O(1) and avoids if ..:.

You could do this like so (fully random example):

import random

def random_nums():
    """Returns a tuple of a frozenset of 5 numbers in the range [1..69]
    and one number in the range of [1..26] (aka: USA Powerball Lottery)"""
    return ( frozenset(random.sample(range(1,70), 5)), random.choice(range(1,27)) )

# draw the win-numbers
winning_nums = set(random.sample(range(1,70), 5))
powerball = random.choice(range(1,27))
# print them
print("Winner: ", *winning_nums, "   Powerball: ", powerball)

# generate random tickets
tickets = [ random_nums() for _ in range(10) ]

# check if ticket got something in common with winner numbers
for (nums, power) in tickets:
    # fast set operations
    intersect = sorted(nums.intersection(winning_nums))
    wrong = sorted(nums.difference(winning_nums))
    p = 'correct' if power == powerball else 'wrong'
    n = "'nothing'"
    # some output
    print( ( f"You got {intersect or n} correct and guessed "
             f"{wrong or n} wrong. Powerball: {p}.") )

Output:

Winner:  14 49 26 27 60    Powerball:  6

You got [49] correct and guessed [21, 41, 59, 66] wrong. Powerball: wrong.
You got [60] correct and guessed [17, 19, 63, 68] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [10, 21, 51, 67, 69] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [18, 30, 40, 45, 52] wrong. Powerball: wrong.
You got [26, 27] correct and guessed [11, 37, 58] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [28, 33, 38, 59, 65] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [11, 18, 35, 61, 64] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [2, 3, 47, 54, 63] wrong. Powerball: wrong.
You got [14] correct and guessed [23, 25, 58, 66] wrong. Powerball: wrong.
You got [27] correct and guessed [47, 52, 56, 58] wrong. Powerball: correct.

See:

Whats the fuss about the Big O of algorythms

set operations


问:
Malloc() creates space for single struct, not array of structs
I've been banging my head against this problem all day, I would be very grateful to anyone who could help out.

Here's the deal - I'm trying to create a dynamic C array using malloc().  This array will hold CGPoint structs, which I start building and assigning right after the array is built.  Here's the code:

```<code>CGPoint* tempVertices = malloc(sizeof(CGPoint) * 4);  //defining a collision frame
tempVertices[0] = CGPointMake(37, 46);
tempVertices[1] = CGPointMake(69, 40);
tempVertices[2] = CGPointMake(48, 6);
tempVertices[3] = CGPointMake(17, 10);

//Then I pass the pointer to my array off to a setter...
[self setVertices: tempVertices];
</code>```

However, when tempVertices gets created, it seems that I'm only getting space for one CGPoint:

```<code>int test1 = sizeof(CGPoint);        // 8
int test2 = sizeof(tempVertices);   // 4
int test3 = sizeof(*tempVertices);  // 8
</code>```

When stepping through with the XCode debugger, it shows that tempVertices is a pointer to a CGPoint.  When I set tempVertices[0], the CGPoint that tempVertices points to recieves that value, which is reflected in the debugger.  Where did my other 3 slots go?  tempVertices seems to be pointing to a singe CGPoint instead of an array.  I want the array.

Any ideas on what I'm doing wrong?  I know that there are other ways to fix this using C++ or other objects, but I want to stick to C if possible.

Thanks in advance!

Update :

To answer zpasternack, setVertices: is a custom written setter.  And I don't know how / if it knows how big the incoming array is.  I'm trying to understand straight C stuff better, so insights/explanations regarding the proper way of passing a dynamic C-array as an argument are highly appreciated.  Here's what the setter looks like :

```<code>- (void) setVertices:(CGPoint*) val {
    _vertices = val;    //_vertices is a member variable of the type CGPoint*
    //...calculate a centroid, other stuff...
}
</code>```

If needed, I could wrap my CGPoints in NSValue objects and use an NSArray instead, but I sure would like to know the right way of doing it in plain ol' C.

Thanks to everyone who has commented - you guys are great :)

答:
OK, after your edit I think I see what's going on.  That code, exactly as you've written, should work OK.  Xcode won't show you the values of any of those CGPoints, because it doesn't know it's an array, just a pointer to a single CGPoint.  But it's there.  Set a breakpoint right after you call setVertices:.  At the gdb prompt, print some of those values.

```<code>(gdb) print _vertices[1]
$2 = {
  x = 69,
  y = 40
}
(gdb) print _vertices[3]
$3 = {
  x = 17,
  y = 10
}
</code>```

Correct, see?

That's not to say there aren't issues here.  For one thing, setVertices: is leaking that memory.  You're allocating memory for tempVertices, holding onto that pointer, but not freeing it anywhere.  The next time you call setVertices:, you'll have a leak.

A bigger issue is that nobody knows how many CGPoints are in that array, except the code that allocated the memory for it.  Will it always be 4 CGPoints?  What happens if somebody accesses _vertices[5] or _vertices[27]?  Bad things, if you didn't allocate that much space for them.

Is there a requirement that this be a plain C array?  Like, these points are going to get passed to OpenGL or cocos2d or something?  If not, you might consider using some kind of array class for it.  Because these aren't NSObject-derived objects you're storing, you can't use an NSArray.  You could use a std::vector, if you don't mind dragging in a buncha C++.  I probably would not do that.

If you're set on sticking with a C array, you should probably do some work to try to make the interface less error prone.  Like I mentioned before, you'll need to track the size of the array.  Perhaps you could add a parameter to setVertices: representing the number of CGPoints that the array holds.  Then other parts of the code that access _vertices could check that to make sure they're not walking off the end of the array.  And, like I mentioned before, make sure you free that memory before you reassign the pointer.

Messing about with pointers is fraught with danger.  Tread carefully, there be dragons there.

Body:
I've been banging my head against this problem all day, I would be very grateful to anyone who could help out.

Here's the deal - I'm trying to create a dynamic C array using malloc().  This array will hold CGPoint structs, which I start building and assigning right after the array is built.  Here's the code:

CGPoint* tempVertices = malloc(sizeof(CGPoint) * 4);  //defining a collision frame
tempVertices[0] = CGPointMake(37, 46);
tempVertices[1] = CGPointMake(69, 40);
tempVertices[2] = CGPointMake(48, 6);
tempVertices[3] = CGPointMake(17, 10);

//Then I pass the pointer to my array off to a setter...
[self setVertices: tempVertices];

However, when tempVertices gets created, it seems that I'm only getting space for one CGPoint:

int test1 = sizeof(CGPoint);        // 8
int test2 = sizeof(tempVertices);   // 4
int test3 = sizeof(*tempVertices);  // 8

When stepping through with the XCode debugger, it shows that tempVertices is a pointer to a CGPoint.  When I set tempVertices[0], the CGPoint that tempVertices points to recieves that value, which is reflected in the debugger.  Where did my other 3 slots go?  tempVertices seems to be pointing to a singe CGPoint instead of an array.  I want the array.

Any ideas on what I'm doing wrong?  I know that there are other ways to fix this using C++ or other objects, but I want to stick to C if possible.

Thanks in advance!

Update :

To answer zpasternack, setVertices: is a custom written setter.  And I don't know how / if it knows how big the incoming array is.  I'm trying to understand straight C stuff better, so insights/explanations regarding the proper way of passing a dynamic C-array as an argument are highly appreciated.  Here's what the setter looks like :

- (void) setVertices:(CGPoint*) val {
    _vertices = val;    //_vertices is a member variable of the type CGPoint*
    //...calculate a centroid, other stuff...
}

If needed, I could wrap my CGPoints in NSValue objects and use an NSArray instead, but I sure would like to know the right way of doing it in plain ol' C.

Thanks to everyone who has commented - you guys are great :)

Body:
OK, after your edit I think I see what's going on.  That code, exactly as you've written, should work OK.  Xcode won't show you the values of any of those CGPoints, because it doesn't know it's an array, just a pointer to a single CGPoint.  But it's there.  Set a breakpoint right after you call setVertices:.  At the gdb prompt, print some of those values.

(gdb) print _vertices[1]
$2 = {
  x = 69,
  y = 40
}
(gdb) print _vertices[3]
$3 = {
  x = 17,
  y = 10
}

Correct, see?

That's not to say there aren't issues here.  For one thing, setVertices: is leaking that memory.  You're allocating memory for tempVertices, holding onto that pointer, but not freeing it anywhere.  The next time you call setVertices:, you'll have a leak.

A bigger issue is that nobody knows how many CGPoints are in that array, except the code that allocated the memory for it.  Will it always be 4 CGPoints?  What happens if somebody accesses _vertices[5] or _vertices[27]?  Bad things, if you didn't allocate that much space for them.

Is there a requirement that this be a plain C array?  Like, these points are going to get passed to OpenGL or cocos2d or something?  If not, you might consider using some kind of array class for it.  Because these aren't NSObject-derived objects you're storing, you can't use an NSArray.  You could use a std::vector, if you don't mind dragging in a buncha C++.  I probably would not do that.

If you're set on sticking with a C array, you should probably do some work to try to make the interface less error prone.  Like I mentioned before, you'll need to track the size of the array.  Perhaps you could add a parameter to setVertices: representing the number of CGPoints that the array holds.  Then other parts of the code that access _vertices could check that to make sure they're not walking off the end of the array.  And, like I mentioned before, make sure you free that memory before you reassign the pointer.

Messing about with pointers is fraught with danger.  Tread carefully, there be dragons there.


问:
I've started a panic with my index out of range, and I can't get out
I'm writing this program to become comfortable with types (not objects!).

The basic premise is the user enters an animal name (cow, snake bird), then an action (eat, move, sound.) My code then looks it up and returns the value.

So, the user entry is suppose to be on ONE line separated by a " ". I use strings.Split.

I'm getting a "panic" notice when the user only enters a single char. I'm thinking this panic arises out of the compiler trying to "split" a single char.

TWO Questions:
1. Am I right?
2. How do I fix it?

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

//Create our type object.
type animal struct {
    aType, eats, moves, sounds string
}

//Create our methods.
func (animal animal) info (querie string) {
    if querie == "eats" {
        fmt.Printf("The animal, %s , eats %s\n ", animal.aType, animal.eats)
    } else if querie == "moves" {
        fmt.Printf("The animal, %s , moves by  %s\n ", animal.aType, animal.moves)
    } else {
        fmt.Printf("The animal, %s , makes the sound %s\n ", animal.aType, animal.sounds)
    }
}

func main() {
    //Now create our animals

    cow := animal{aType:"cow", eats: "grass", moves: "walking", sounds: "moo"}
    bird := animal{aType:"bird", eats: "worms", moves: "flying", sounds: "peep"}
    snake := animal{aType:"snake", eats: "mice", moves: "slithering", sounds: "hiss"}
    // need a boolean to perpetuate our loop
    var flag bool = true

    for flag {
        fmt.Println("Remember enter X to exit")
        fmt.Printf(">please enter your (format: type & information) request -> ")
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Scan()
        request := scanner.Text()

        //Capture user entered data

        typed := strings.Split(request, " ")[0]
        if typed == "X" {
            flag = false
            break
        }
        infoe := strings.Split(request, " ")[1]

        // contruct the logic tree.

        if !((infoe == "eat") || (infoe == "move") || (infoe == "speak")) {
            switch typed {
            case "cow":
                cow.info(infoe)

            case "snake":
                snake.info(infoe)

            case "bird":
                bird.info(infoe)
            default:
                fmt.Println("I don't know about that animal.")
            }
        } else {
            fmt.Printf("I don't have that informtion")
                break
            }
        }
    }
</code>```

答:
To simplify your code, I would suggest using fmt.Scanf as shown below:

```<code>package main

import "fmt"

func main() {
    var animal, action string

    fmt.Printf("Enter animal: ")
    fmt.Scanf("%s", &animal)
    fmt.Printf("Enter action: ")
    fmt.Scanf("%s", &action)

    fmt.Printf("Animal was %s and action was %s", animal, action)
}
</code>```

Also am not sure why there are multiple downvotes. Is it the problem with the way the code is written? I think that's ok if someone is just trying to learn the language. First get it working and then focus on other things.

Once you are comfortable with the language, you can go through points listed in Effective Go

Body:
I'm writing this program to become comfortable with types (not objects!).

The basic premise is the user enters an animal name (cow, snake bird), then an action (eat, move, sound.) My code then looks it up and returns the value.

So, the user entry is suppose to be on ONE line separated by a " ". I use strings.Split.

I'm getting a "panic" notice when the user only enters a single char. I'm thinking this panic arises out of the compiler trying to "split" a single char.

TWO Questions:
1. Am I right?
2. How do I fix it?

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

//Create our type object.
type animal struct {
    aType, eats, moves, sounds string
}

//Create our methods.
func (animal animal) info (querie string) {
    if querie == "eats" {
        fmt.Printf("The animal, %s , eats %s\n ", animal.aType, animal.eats)
    } else if querie == "moves" {
        fmt.Printf("The animal, %s , moves by  %s\n ", animal.aType, animal.moves)
    } else {
        fmt.Printf("The animal, %s , makes the sound %s\n ", animal.aType, animal.sounds)
    }
}

func main() {
    //Now create our animals

    cow := animal{aType:"cow", eats: "grass", moves: "walking", sounds: "moo"}
    bird := animal{aType:"bird", eats: "worms", moves: "flying", sounds: "peep"}
    snake := animal{aType:"snake", eats: "mice", moves: "slithering", sounds: "hiss"}
    // need a boolean to perpetuate our loop
    var flag bool = true

    for flag {
        fmt.Println("Remember enter X to exit")
        fmt.Printf(">please enter your (format: type & information) request -> ")
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Scan()
        request := scanner.Text()

        //Capture user entered data

        typed := strings.Split(request, " ")[0]
        if typed == "X" {
            flag = false
            break
        }
        infoe := strings.Split(request, " ")[1]

        // contruct the logic tree.

        if !((infoe == "eat") || (infoe == "move") || (infoe == "speak")) {
            switch typed {
            case "cow":
                cow.info(infoe)

            case "snake":
                snake.info(infoe)

            case "bird":
                bird.info(infoe)
            default:
                fmt.Println("I don't know about that animal.")
            }
        } else {
            fmt.Printf("I don't have that informtion")
                break
            }
        }
    }

Body:
To simplify your code, I would suggest using fmt.Scanf as shown below:

package main

import "fmt"

func main() {
    var animal, action string

    fmt.Printf("Enter animal: ")
    fmt.Scanf("%s", &animal)
    fmt.Printf("Enter action: ")
    fmt.Scanf("%s", &action)

    fmt.Printf("Animal was %s and action was %s", animal, action)
}

Also am not sure why there are multiple downvotes. Is it the problem with the way the code is written? I think that's ok if someone is just trying to learn the language. First get it working and then focus on other things.

Once you are comfortable with the language, you can go through points listed in Effective Go


答:
You can use a recursive function like the following:

def generate_binary_entries(n, t=[[]]):  # n: length of bit number
    if n == 0:
        return t
    new_t = []
    for entry in t:
        new_t.append(entry + [0])
        new_t.append(entry + [1])
    return generate_binary_entries(n - 1, new_t)
```

<p>Then</p>

<pre class="lang-py prettyprint-override"><code>generate_binary_entries(4)
</code>```

generates

```<code>[[0, 0, 0, 0],
 [0, 0, 0, 1],
 [0, 0, 1, 0],
 [0, 0, 1, 1],
 [0, 1, 0, 0],
 [0, 1, 0, 1],
 [0, 1, 1, 0],
 [0, 1, 1, 1],
 [1, 0, 0, 0],
 [1, 0, 0, 1],
 [1, 0, 1, 0],
 [1, 0, 1, 1],
 [1, 1, 0, 0],
 [1, 1, 0, 1],
 [1, 1, 1, 0],
 [1, 1, 1, 1]]
</code>```

Title: Generating binary entries array in python

Body:
I would like to generate an array as follows:

[[0,0,0],
 [0,0,1],
 [0,1,0],
 [0,1,1],
 [1,0,0],
 [1,0,1],
 [1,1,0]
 [1,1,1]]

I tried to achieve this by setting 3 for loops, but I wish to go further to 4, 5, and higher bit-numbers, so the last method would not scale easly to these numbers.

Is there any simple way for doing this?

Body:
You can use a recursive function like the following:

def generate_binary_entries(n, t=[[]]):  # n: length of bit number
    if n == 0:
        return t
    new_t = []
    for entry in t:
        new_t.append(entry + [0])
        new_t.append(entry + [1])
    return generate_binary_entries(n - 1, new_t)

Then

generate_binary_entries(4)

generates

[[0, 0, 0, 0],
 [0, 0, 0, 1],
 [0, 0, 1, 0],
 [0, 0, 1, 1],
 [0, 1, 0, 0],
 [0, 1, 0, 1],
 [0, 1, 1, 0],
 [0, 1, 1, 1],
 [1, 0, 0, 0],
 [1, 0, 0, 1],
 [1, 0, 1, 0],
 [1, 0, 1, 1],
 [1, 1, 0, 0],
 [1, 1, 0, 1],
 [1, 1, 1, 0],
 [1, 1, 1, 1]]