问:
How to start content div below fixed header without giving margin?
Div with id header is fixed but the div with the id content is going behind the header div. What can I do if I want to fix this issue without adding margin-top to the content div?

I tried adding margin-top but it occurs the problem with other elements in responsive view.

My code

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>

    <style>
        body {
            margin: 0;
            padding: 0;
        }
        #header {
            color: white;
            font-size: 18px;
            background-color: black;
            text-align: center;
            position: fixed;
            width: 100%;
            top: 0;
            opacity: 0.8;
        }

        #header div {
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid grey;
        }

        #content {
            background-color: orange;
        }
    </style>
</head>

<body>
    <div id="header">
        <div>
            <p>This is header</p>
        </div>
    </div>

    <div id="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
    </div>
</body>
</html>
</code>```

答:
  body {
            margin: 0;
            padding: 0;
        }
        #header {
            color: white;
            font-size: 18px;
            background-color: black;
            text-align: center;
            position: fixed;
            width: 100%;
            top: 0;
            opacity: 0.8;
        }

        #header div {
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid grey;
        }

        #content {
            background-color: orange;
        }

        #a {
            content: "";
            display: block;
            height: 40px;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div id="header">
        <div>
            <p>This is header</p>
        </div>
    </div>
  <div id="a"></div>
    <div id="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
    </div>
</body></code>```

Body:
Div with id header is fixed but the div with the id content is going behind the header div. What can I do if I want to fix this issue without adding margin-top to the content div?

I tried adding margin-top but it occurs the problem with other elements in responsive view.

My code

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>

This is header

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.

Body:
  body {
            margin: 0;
            padding: 0;
        }
        #header {
            color: white;
            font-size: 18px;
            background-color: black;
            text-align: center;
            position: fixed;
            width: 100%;
            top: 0;
            opacity: 0.8;
        }

        #header div {
            display: flex;
            justify-content: center;
            align-items: center;
            border: 1px solid grey;
        }

        #content {
            background-color: orange;
        }

        #a {
            content: "";
            display: block;
            height: 40px;
        }

<body>
    <div id="header">
        <div>
            <p>This is header</p>
        </div>
    </div>
  <div id="a"></div>
    <div id="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita facere iusto vel aperiam, maiores dignissimos magni quam, laudantium officiis cupiditate libero soluta eum consequuntur dolores blanditiis, in recusandae sequi incidunt.</p>
    </div>
</body>


来源: stackexchange

问:
Libraries(armel) for cross compiling
Where can I get compiled libraries specific architectures?  My company hired some contractors to port some code to our powerpc platform.  I am trying to move this to an arm platform(omap3).

They created a cross compiling environment(in Windows).  All of the libraries that are linked at still compiled for PowerPC.   For each lib there are 3 files: .so, .so.X and .so.X.Y.Z  I can get the second 2 from the deb packages and I found the .so in developer deb package but it is 0 bytes.

Any help would be great.

答:
Theres no way (that I know of) to convert a binary from machine A(power pc) into binaries for machine B(arm). If you have the source, or a way of acquiring the source, you can rebuild them for your arm target.  You can accomplish this by either using a local compiler on a arm machine, or cross compile using a cross compiling tool chain (eg code sorcery lite (http://www.codesourcery.com/sgpp/lite/arm) to build libraries from your build machine onto your arm target.  Most libraries are not obtainable on arm in a pre-compiled form.<br>
Depending on what OS you're using on your arm target, eg debian or redhat.  There may be a package manager available to do this for you.  </p>

ContentLicense: CC BY-SA 3.0

Title: Libraries(armel) for cross compiling

Body:
Theres no way (that I know of) to convert a binary from machine A(power pc) into binaries for machine B(arm). If you have the source, or a way of acquiring the source, you can rebuild them for your arm target.  You can accomplish this by either using a local compiler on a arm machine, or cross compile using a cross compiling tool chain (eg code sorcery lite (http://www.codesourcery.com/sgpp/lite/arm) to build libraries from your build machine onto your arm target.  Most libraries are not obtainable on arm in a pre-compiled form.

Depending on what OS you're using on your arm target, eg debian or redhat.  There may be a package manager available to do this for you.


问:
How to find matching values in a dictionary and get a certain output? Pyhton
I have a dictionary and with some items, see here:

```<code>elements = {
    1: Element(1, nodes[1], nodes[2]),
    2: Element(2, nodes[2], nodes[3]),
    3: Element(3, nodes[3], nodes[4]),
    4: Element(4, nodes[3], nodes[5]),
}
</code>```

The first value in the dictionary resembles the element number.

I want to find the elements for certain nodes.

For example: I want to find all elements containing node number 3, how can I iterate through the dict and find these elements? I had a for loop in mind, but don't know how to get the certain elements.

答:
Assuming that the nodes array stores Objects of the Element class, we can use this list comprehension:</p>
```<code>result = [i or i in elements if (i.node1.id==3 or i.node2.id==3)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dictionary and with some items, see here:

elements = {
    1: Element(1, nodes[1], nodes[2]),
    2: Element(2, nodes[2], nodes[3]),
    3: Element(3, nodes[3], nodes[4]),
    4: Element(4, nodes[3], nodes[5]),
}

The first value in the dictionary resembles the element number.

I want to find the elements for certain nodes.

For example: I want to find all elements containing node number 3, how can I iterate through the dict and find these elements? I had a for loop in mind, but don't know how to get the certain elements.

Body:
Assuming that the nodes array stores Objects of the Element class, we can use this list comprehension:

result = [i or i in elements if (i.node1.id==3 or i.node2.id==3)]


问:
How to mock ICorrelationContextAccessor for CorrelationId
For the mocking, I am using Moq 4.16.1 package.

I have a class that derives from DelegatingHandler class

```<code>public class Handler : DelegatingHandler
{
  private readonly ICorrelationContextAccessor _correlationContextAccessor;
  public Handler(ICorrelationContextAccessor correlationContextAccessor)
        {
            _correlationContextAccessor = correlationContextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
        {
                request.Headers.Add("x-correlation-Id", _correlationContextAccessor.CorrelationContext.CorrelationId);

                var response = await base.SendAsync(request, ct);

                response.EnsureSuccessStatusCode();

                return response;
        }
}
</code>```

now I need to mock the ICorrelationContextAccessor.

I have tried the below code but had no luck

```<code>_correlationContextAccessor.SetupProperty(x => x.CorrelationContext.CorrelationId, new Guid().ToString());
</code>```

Anyone who how to mock CorrelationId in this situation?

答:
From the source code of CorrelationContext, you can't mock CorrelationId property because it's an only read property.

There is another way you can try to use it, Try to use mock CorrelationContext property by SetupProperty method, then create an instance with your expectation Guid

```<code>var guid = new Guid().ToString();
_correlationContextAccessor.SetupProperty(x => x.CorrelationContext, new CorrelationContext(guid,"x-correlation-Id"));
</code>```

Body:
For the mocking, I am using Moq 4.16.1 package.

I have a class that derives from DelegatingHandler class

public class Handler : DelegatingHandler
{
  private readonly ICorrelationContextAccessor _correlationContextAccessor;
  public Handler(ICorrelationContextAccessor correlationContextAccessor)
        {
            _correlationContextAccessor = correlationContextAccessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
        {
                request.Headers.Add("x-correlation-Id", _correlationContextAccessor.CorrelationContext.CorrelationId);

                var response = await base.SendAsync(request, ct);

                response.EnsureSuccessStatusCode();

                return response;
        }
}

now I need to mock the ICorrelationContextAccessor.

I have tried the below code but had no luck

_correlationContextAccessor.SetupProperty(x => x.CorrelationContext.CorrelationId, new Guid().ToString());

Anyone who how to mock CorrelationId in this situation?

Body:
From the source code of CorrelationContext, you can't mock CorrelationId property because it's an only read property.

There is another way you can try to use it, Try to use mock CorrelationContext property by SetupProperty method, then create an instance with your expectation Guid

var guid = new Guid().ToString();
_correlationContextAccessor.SetupProperty(x => x.CorrelationContext, new CorrelationContext(guid,"x-correlation-Id"));


问:
How to run some element in recyle from an array?
Well, I know my question is very difficult. But I want to know Things?

Suppose, I have an array element?

```<code>const array = [
   "AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]
</code>```

I need here on Function that can run only 10 element every time. When I run function for first time it's show me first 10 element. Then If I run again then it show me the rest element.

Suppose this is function

```<code>const runElement = () => {
    console.log(element)
}
</code>```

If I run this function first time it show me first 10 element from array.

```<code>"AEDAUD"
"AEDCAD"
"AEDCHF"
"AEDEUR"
"AEDGBP"
"AEDINR"
"AEDJPY"
"AEDNOK"
"AEDNZD"
"AEDPKR"
</code>```

Then If I run that function again it should show me the rest element-

```<code>"AEDSAR"
"AEDSEK"
"AEDZAR"
"ANG"
"ARSBRL"
"ARSEUR"
"ARSGBP"
</code>```

If I run the function again it should go first 10 element again. In that It should run for always.

Is this possible in javascript?

答:
Maybe you would be interested in using a generator: provide it with the array and the chunk size, and let it just cycle happily through the array for ever while yielding the results.

The iterator can be used to grab as many results as needed:

function* pullValues(arr, chunkSize) {
    let i = 0;
    while (true) {
        yield arr.slice(i, i += chunkSize);
        if (i >= arr.length) i = 0;
    }
}

// demo

const array = [
   "AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
];
let it = pullValues(array, 10);

console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
console.log(...it.next().value);
//....```

Body:
Well, I know my question is very difficult. But I want to know Things?

Suppose, I have an array element?

const array = [
   "AEDAUD", "AEDCAD", "AEDCHF", "AEDEUR", "AEDGBP", "AEDINR", "AEDJPY", "AEDNOK", "AEDNZD", "AEDPKR", "AEDSAR", "AEDSEK", "AEDZAR", "ANG", "ARSBRL", "ARSEUR", "ARSGBP"
]

I need here on Function that can run only 10 element every time. When I run function for first time it's show me first 10 element. Then If I run again then it show me the rest element.

Suppose this is function

const runElement = () => {
    console.log(element)
}

If I run this function first time it show me first 10 element from array.

"AEDAUD"
"AEDCAD"
"AEDCHF"
"AEDEUR"
"AEDGBP"
"AEDINR"
"AEDJPY"
"AEDNOK"
"AEDNZD"
"AEDPKR"

Then If I run that function again it should show me the rest element-

"AEDSAR"
"AEDSEK"
"AEDZAR"
"ANG"
"ARSBRL"
"ARSEUR"
"ARSGBP"

If I run the function again it should go first 10 element again. In that It should run for always.

Is this possible in javascript?


问:
Foreign key relationship with composite primary keys in SQL Server 2005
I have two tables

```<code>Table1(
  FileID,
  BundledFileID,
  Domain)
</code>```

and

```<code>Table2(
  FileID,
  FileType,
  FileName)
</code>```

In Table2 FileID and FileType are the composite primary key. I want to create a foreign key relationship from Table1.FileID  to Table2.

Is it possible to do this?

答:
I did this using SQL Server Management Studio:

First reference foreign keys, then make composite primary key.

When you create Table2, don't make a primary key at all in the beginning.
First create the foreign key of Table2.FileID with Table1.FileID. And then set the composite key for Table2 (Table2.FileID, Table2.FileType).

Same concept goes if FileType needs to be a foreign key as well. First reference both of the foreign keys and then create the composite key.

Body:
I have two tables

Table1(
  FileID,
  BundledFileID,
  Domain)

and

Table2(
  FileID,
  FileType,
  FileName)

In Table2 FileID and FileType are the composite primary key. I want to create a foreign key relationship from Table1.FileID  to Table2.

Is it possible to do this?


问:
How do you set up "test mode" for your Java app?
I am working on a Java web app with unit tests that deploy the app in Jetty. I use HtmlUnit to hit the app and do some high level tests. I set it up so that I can use a singleton probe to modify my system configuration and add a "test" flag--This is handy because I want to be able to run some tests without having to authenticate an actual user or check user roles.

However, it seems like it could open the door for vulnerability when the app is deployed. I'm looking for suggestions about how to make this "back door" a little more bullet proof. I could use a mock object to handle this, but I think that still leaves the back door exposed.

答: Throw some kind of security around the process you use to change the app over to Test mode - Basic Authentication for that page, or something.  This can all be configured directly in web.xml.</p>


问:
Comparing array of ObjectIds to ObjectId
I have a simple use case that used to work in my code, however now I've had to make changes to accommodate an issue I am now having.  Looking to get some insights into why this has changed and requires extra check if anyone can help.  My scenario is as described.

I have an array userBadgeIds which holds the following: [ new ObjectId("59f347fca0f50c0004b5a3ac") ]

I used to do the following line: const exists = userBadgeIds.includes(badge._id) which worked perfectly and told me if the input badge._id was in the array.  Both are mongoose ObjectId so comparing equivalent in this way seemed perfect (again, it worked!).

However, for whatever reason I now have to compare them in the following way:

```<code>      const exists = userBadgeIds.map(String).includes(badge._id.toString())
</code>```

Now it works again.  Is there something I'm missing about how the .includes compares equivalence or something I'm missing about comparing ObjectId specifically around ObjectId[]?

答:
When you compare objects, they have to be the exact same object and not an object that has the same properties.

It's possible that something has changed in your code elsewhere or in a library that turns what was basically this:

```<code>const obj1 = { _id: 'a' };
const obj2 = { _id: 'b' };
const obj3 = { _id: 'c' };
const searchFor = obj1;

[obj1, obj2, obj3].includes(searchFor); // true
</code>```

Into something that is essentially this:

```<code>const obj1 = { _id: 'a' };
const obj2 = { _id: 'b' };
const obj3 = { _id: 'c' };
const searchFor = { _id: 'a' };

[obj1, obj2, obj3].includes(searchFor); // false
</code>```

searchFor might have the same properties and prototype, but it's not the exact same object as obj1. Perhaps some code is cloning badge, making it not equal to the entries in the userBadgeIds array.

Your workaround works, because when you compare strings, they don't have to be the exact same string, just have the same value.

As an aside, there's ObjectId.prototype.equals() to compare two (identical or equivalent) ObjectIds.

```<code>// You need to pass searchFor as the second parameter to `some`
// so that `this` is correctly set.
[obj1, obj2, obj3].some(searchFor.equals, searchFor);

// Or you can do:
[obj1, obj2, obj3].some(searchFor.equals.bind(searchFor));

// Or:
[obj1, obj2, obj3].some(id => searchFor.equals(id));
</code>```

Array.prototype.some returns true if any array entry matches the callback function, like includes does for values.

Body:
I have a simple use case that used to work in my code, however now I've had to make changes to accommodate an issue I am now having.  Looking to get some insights into why this has changed and requires extra check if anyone can help.  My scenario is as described.

I have an array userBadgeIds which holds the following: [ new ObjectId("59f347fca0f50c0004b5a3ac") ]

I used to do the following line: const exists = userBadgeIds.includes(badge._id) which worked perfectly and told me if the input badge._id was in the array.  Both are mongoose ObjectId so comparing equivalent in this way seemed perfect (again, it worked!).

However, for whatever reason I now have to compare them in the following way:

      const exists = userBadgeIds.map(String).includes(badge._id.toString())

Now it works again.  Is there something I'm missing about how the .includes compares equivalence or something I'm missing about comparing ObjectId specifically around ObjectId[]?

Body:
When you compare objects, they have to be the exact same object and not an object that has the same properties.

It's possible that something has changed in your code elsewhere or in a library that turns what was basically this:

const obj1 = { _id: 'a' };
const obj2 = { _id: 'b' };
const obj3 = { _id: 'c' };
const searchFor = obj1;

[obj1, obj2, obj3].includes(searchFor); // true

Into something that is essentially this:

const obj1 = { _id: 'a' };
const obj2 = { _id: 'b' };
const obj3 = { _id: 'c' };
const searchFor = { _id: 'a' };

[obj1, obj2, obj3].includes(searchFor); // false

searchFor might have the same properties and prototype, but it's not the exact same object as obj1. Perhaps some code is cloning badge, making it not equal to the entries in the userBadgeIds array.

Your workaround works, because when you compare strings, they don't have to be the exact same string, just have the same value.

As an aside, there's ObjectId.prototype.equals() to compare two (identical or equivalent) ObjectIds.

// You need to pass searchFor as the second parameter to `some`
// so that `this` is correctly set.
[obj1, obj2, obj3].some(searchFor.equals, searchFor);

// Or you can do:
[obj1, obj2, obj3].some(searchFor.equals.bind(searchFor));

// Or:
[obj1, obj2, obj3].some(id => searchFor.equals(id));

Array.prototype.some returns true if any array entry matches the callback function, like includes does for values.


问:
what is the difference between clone method or copy of one arrayList to another arrayList in java ? both gives the same hashCode pls check below code
```<code>public static void main(String[] args) {
    ArrayList<String> c1= new ArrayList<String>();
    c1.add("Red");
    c1.add("Green");
    c1.add("Black");
    c1.add("White");
    c1.add("Pink");

    System.out.println("Original array list: " + c1);
    ArrayList<String> newc1 = new ArrayList<String>();

    newc1 = (ArrayList<String>) c1.clone();

    System.out.println("Cloned array list: " + newc1);

    ArrayList<String> c2 = new ArrayList<String>();
    c2.addAll(c1);

    System.out.println(c1.hashCode());
    System.out.println(newc1.hashCode());
    System.out.println(c2.hashCode());

}
</code>```

what is the difference between clone method or copy of one arrayList to another arrayList in java ? both gives the same hashCode pls check below code.

答:
clone() is the function of the Obejct class, which is a kind of shallow copy, which means that it just copys the address of the object.

hashcode() of a list depends on the elements of the list, so if these list contains the same elements, they will have the same result value of hashcode(), unless you overwrite hashcode() by yourself.

Body:
public static void main(String[] args) {
    ArrayList<String> c1= new ArrayList<String>();
    c1.add("Red");
    c1.add("Green");
    c1.add("Black");
    c1.add("White");
    c1.add("Pink");

    System.out.println("Original array list: " + c1);
    ArrayList<String> newc1 = new ArrayList<String>();

    newc1 = (ArrayList<String>) c1.clone();

    System.out.println("Cloned array list: " + newc1);

    ArrayList<String> c2 = new ArrayList<String>();
    c2.addAll(c1);

    System.out.println(c1.hashCode());
    System.out.println(newc1.hashCode());
    System.out.println(c2.hashCode());

}

what is the difference between clone method or copy of one arrayList to another arrayList in java ? both gives the same hashCode pls check below code.


问:
Joining three tables on two IDs
I have this exercise for an application and I can't really check if I'm doing it right because I'm a beginner and I don't how to make my own database.

These are the given data:

Table 1: Company

Company_ID
Name
Desc
Location
Ticker

1
ABC
An..
US
AB

2
EFG
An..
US
EF

3
HIJ
An..
EU
HI

Table 2: Others

Company_ID
Ratings
Issue
BUD_ID

1
ABC
An...
US

2
EFG
An...
US

3
HIJ
An...
EU

Table 3: Sectors

Company_ID
Sector
Code

1
Electronic

2
Industrial
000111

3
Manufacturing
222333

Here's what I've written: I need to extract the name, description, location, issue, and BUD_ID  based on company id's 2 and 3

```<code>SELECT c.Company_ID, c.Name, c.Description, c.Location, cxi.Issue, cxi.BUD_ID
FROM Companies as c
JOIN Others as cxi
ON c.Company_ID = cxi.Company_ID
JOIN Sectors as csx
ON c.Company_ID = csx.Company_ID
WHERE c.Company_ID = '2'
AND c.Company_ID = '3';
</code>```

Thank you so much.

答:
Change:

```<code>SELECT c.Company_ID, c.Name, c.Description, c.Location, cxi.Issue, cxi.BUD_ID
FROM Companies as c
JOIN Others as cxi
ON c.Company_ID = cxi.Company_ID
JOIN Sectors as csx
ON c.Company_ID = csx.Company_ID
WHERE c.Company_ID = '2'
AND c.Company_ID = '3';
</code>```

to:

```<code>SELECT c.Company_ID, c.Name, c.Description, c.Location, cxi.Issue, cxi.BUD_ID
FROM Companies as c
JOIN Others as cxi
ON c.Company_ID = cxi.Company_ID
JOIN Sectors as csx
ON c.Company_ID = csx.Company_ID
WHERE c.Company_ID = '2'
OR c.Company_ID = '3';
</code>```

You cannot have ID 2 and 3 on the same row. If you want to get data for both use the OR rather than AND.

Title: Joining three tables on two IDs

Body:
I have this exercise for an application and I can't really check if I'm doing it right because I'm a beginner and I don't how to make my own database.

These are the given data:

Table 1: Company

Company_ID
Name
Desc
Location
Ticker

1
ABC
An..
US
AB

2
EFG
An..
US
EF

3
HIJ
An..
EU
HI

Table 2: Others

Company_ID
Ratings
Issue
BUD_ID

1
ABC
An...
US

2
EFG
An...
US

3
HIJ
An...
EU

Table 3: Sectors

Company_ID
Sector
Code

1
Electronic

2
Industrial
000111

3
Manufacturing
222333

Here's what I've written: I need to extract the name, description, location, issue, and BUD_ID  based on company id's 2 and 3

SELECT c.Company_ID, c.Name, c.Description, c.Location, cxi.Issue, cxi.BUD_ID
FROM Companies as c
JOIN Others as cxi
ON c.Company_ID = cxi.Company_ID
JOIN Sectors as csx
ON c.Company_ID = csx.Company_ID
WHERE c.Company_ID = '2'
AND c.Company_ID = '3';

Thank you so much.

Body:
Change:

SELECT c.Company_ID, c.Name, c.Description, c.Location, cxi.Issue, cxi.BUD_ID
FROM Companies as c
JOIN Others as cxi
ON c.Company_ID = cxi.Company_ID
JOIN Sectors as csx
ON c.Company_ID = csx.Company_ID
WHERE c.Company_ID = '2'
AND c.Company_ID = '3';

to:

SELECT c.Company_ID, c.Name, c.Description, c.Location, cxi.Issue, cxi.BUD_ID
FROM Companies as c
JOIN Others as cxi
ON c.Company_ID = cxi.Company_ID
JOIN Sectors as csx
ON c.Company_ID = csx.Company_ID
WHERE c.Company_ID = '2'
OR c.Company_ID = '3';

You cannot have ID 2 and 3 on the same row. If you want to get data for both use the OR rather than AND.


问:
Why can't I reuse an event even after explicit ResetEvent call?
I want to watch for changes done with a file (the event i'm waiting for is change contents event, i.e. last modified date is updated)

I have a code like this (minimalized example of actual code)
I expect that each iteration of the while loop the event gets reset and is available to be fired again but that doesn't happen

Why it fires change event only once?

int main()
{
    const wchar_t *dir_path = L"C:\\Users\\IC\\AppData\\Roaming\\JetBrains\\CLion2021.3\\scratches\\";

    HANDLE hDir = ::CreateFileW(
        dir_path,
        FILE_LIST_DIRECTORY,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
        NULL
    );

    FILE_NOTIFY_INFORMATION fni;
    OVERLAPPED overlapped;
    overlapped.hEvent = ::CreateEventA(NULL, FALSE, FALSE, NULL);

    ::ReadDirectoryChangesW(
        hDir,
        &fni,
        sizeof(fni),
        TRUE,
        FILE_NOTIFY_CHANGE_LAST_WRITE,
        NULL,
        &overlapped,
        NULL
    );

    while (true)
    {
        std::vector<HANDLE> all_job_event_handles;
        if (::ResetEvent(overlapped.hEvent) == FALSE)
        {
            printf("ResetEvent failed\n");
            fflush(stdout);
            return 1;
        }
        all_job_event_handles.push_back(overlapped.hEvent);

        DWORD result = ::WaitForMultipleObjects(all_job_event_handles.size(), all_job_event_handles.data(), FALSE, INFINITE);
        if (result == WAIT_FAILED)
        {
            printf("WaitForMultipleObjects failed\n");
            fflush(stdout);
            return 1;
        }

        if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + all_job_event_handles.size())
        {
            printf("file changed\n");
            fflush(stdout);
        }
    }
}
```

答:
Because that's just not how ReadDirectoryChanges works. It doesn't continuously send you changes. It sends you one batch of changes. You process them. You call the function again to tell the system that you want more changes.

I found a correct usage example of the function here: https://gist.github.com/nickav/a57009d4fcc3b527ed0f5c9cf30618f8

Some side notes:

You don't check whether ReadDirectoryChanges succeeds. This is bad; if it failed, you will hang on the Wait call forever.

You don't zero-initialize the OVERLAPPED structure.

You create the event as an auto-reset event (second parameter is FALSE). ResetEvent on such an event does nothing.

All the event handles you add into your vector are the same event object. You just have an ever-growing list of the same event repeatedly that you pass to WaitForMultipleObjects. This does nothing at best, but will eventually fail because WFMO doesn't allow more than MAXIMUM_WAIT_OBJECTS handles, and this number is fairly low (32, I think).

You probably want a more permissive share mode on the directory you open.


问:
When testing with Cypress.io how to programmatically log in using nuxt.js and nuxt-auth
Testing with Cypress.io I would like to trigger a "stubbed" log in on my Nuxt app.

I have tried stubbing the login and user-details XHR calls that the nuxt-auth module fires.

I've used a custom plugin to expose the Nuxt app's context to Cypress. Seemed successful.

/plugins/cypress.js

const isCypress = typeof window.Cypress !== 'undefined'
export default context => {
  if (isCypress) {
    window.nuxtApp = context
  }
}
```

<p>Within a Cypress spec file I've called nuxt-auth's <code>$auth.loginWith('local', {…})</code> which appears to set the Vuex <code>$state.loggedIn</code> to <code>true</code> and sets the user object with the contents of my fixture file.</p>

<p>Example of my Cypress login command</p>

<pre class="lang-js prettyprint-override"><code>Cypress.Commands.add('login', () => {
  // Use as cy.login()
  cy.server()
  cy.fixture('userLogin').as('userLoginJson')
  cy.fixture('userDetails').as('userDetailsJson')
  cy.route({
    method: 'POST',
    url: '/api/auth/login',
    response: '@userLoginJson'
  }).as('postLogin')
  cy.route({
    method: 'GET',
    url: '/api/user/details',
    response: '@userDetailsJson'
  })
  cy.visit('/')
  cy.window().should('have.property', 'nuxtApp') // is TRUE
  cy.window().then(window => {
    console.log('nuxtApp', window.nuxtApp) // Nuxt context visible in console
    window.nuxtApp.$auth
      .loginWith('local', {
        data: {
          email: 'anything',
          password: 'anything',
          remember_me: true
        }
      })
      .then(response => response)
  })
  cy.visit('/user') // Middleware denies this route. Consistent with being logged out.
})
</code>```

I would like the app to act like it's logged in but middleware continues to deny access to logged in routes and any v-if="$auth.loggedIn" within components render as logged out.

/middleware/authenticated.js

export default ({ store, redirect }) => {
  // If the user is not authenticated
  if (!store.state.auth.loggedIn) {
    return redirect('/login')
  }
}
```

My best guess is that Nuxt's server side rendering is getting in the way …but it could be anything ♂.

Thanks

Some inspiration from:

https://www.cypress.io/blog/2017/11/28/testing-vue-web-application-with-vuex-data-store-and-rest-backend/

答:
There is no need to create a plugin, here is mine using laravel Sanctrum

  Cypress.Commands.add("login", (email, password) => {
  cy.intercept("GET", "api/sanctum/csrf-cookie").as("csrfCookie");

  cy.intercept("POST", "/api/login", {
    fixture: "auth/user-login.json",
  }).as("userLogin");

  cy.fixture("auth/user-info.json").then((user) => {
    user.email = email;
    cy.intercept("GET", "/api/user", user).as("userInfo");
  });

  cy.window()
    .its("$nuxt")
    .then((nuxt) => {
      nuxt.$auth.loginWith("laravelSanctum", {
        data: {
          email: email,
          password: password,
          //   remember_me: true,
        },
      });
      cy.wait("@userInfo");
    });
```

Body:
Testing with Cypress.io I would like to trigger a "stubbed" log in on my Nuxt app.

I have tried stubbing the login and user-details XHR calls that the nuxt-auth module fires.

I've used a custom plugin to expose the Nuxt app's context to Cypress. Seemed successful.

/plugins/cypress.js

const isCypress = typeof window.Cypress !== 'undefined'
export default context => {
  if (isCypress) {
    window.nuxtApp = context
  }
}

Within a Cypress spec file I've called nuxt-auth's $auth.loginWith('local', {…}) which appears to set the Vuex $state.loggedIn to true and sets the user object with the contents of my fixture file.

Example of my Cypress login command

Cypress.Commands.add('login', () => {
  // Use as cy.login()
  cy.server()
  cy.fixture('userLogin').as('userLoginJson')
  cy.fixture('userDetails').as('userDetailsJson')
  cy.route({
    method: 'POST',
    url: '/api/auth/login',
    response: '@userLoginJson'
  }).as('postLogin')
  cy.route({
    method: 'GET',
    url: '/api/user/details',
    response: '@userDetailsJson'
  })
  cy.visit('/')
  cy.window().should('have.property', 'nuxtApp') // is TRUE
  cy.window().then(window => {
    console.log('nuxtApp', window.nuxtApp) // Nuxt context visible in console
    window.nuxtApp.$auth
      .loginWith('local', {
        data: {
          email: 'anything',
          password: 'anything',
          remember_me: true
        }
      })
      .then(response => response)
  })
  cy.visit('/user') // Middleware denies this route. Consistent with being logged out.
})

I would like the app to act like it's logged in but middleware continues to deny access to logged in routes and any v-if="$auth.loggedIn" within components render as logged out.

/middleware/authenticated.js

export default ({ store, redirect }) => {
  // If the user is not authenticated
  if (!store.state.auth.loggedIn) {
    return redirect('/login')
  }
}

My best guess is that Nuxt's server side rendering is getting in the way …but it could be anything ♂.

Thanks

Some inspiration from:

https://www.cypress.io/blog/2017/11/28/testing-vue-web-application-with-vuex-data-store-and-rest-backend/


问:
How do I get notification that the local Visual Studio build is complete?
There doesn't seem to be a post-build solution task.  One could presumably hack it by creating a dummy project that is the last one to build and put a beep in the post-build project.</p>

答:
You can also now as of VS2019 gain access to the system sounds through the UI. Go Options->Test.

You can also find more info out here: https://learn.microsoft.com/en-us/visualstudio/test/run-unit-tests-with-test-explorer?view=vs-2019#test-audio-cue

ContentLicense: CC BY-SA 2.5


问:
Show H1 somwhere else on the page again without typing it manually (as a kind of variable)?
I am searching for a way to display an H1 somwhere else on the page again with just HTML or JavaScript.

What I mean: I do have a H1-title which is typed in manually. And I want it automatically be displayed at the bottom on the page again, without having to type it in manually again. (The thing with the bottom on the page is just an example, my project is a bit more complex).

I'm searching kind of a variable, I think.

Thanks in advance for your help.

答:
Consider you have a heading element. First you need to select the heading then create its clone using the cloneNode() function, it accepts a deep parameter which basically means the node and its whole subtree, including text that may be in child Text nodes, is also copied. After that we basically append the cloned element to the document body.

// select the heading
let el = document.querySelector('.heading');

// clone the element
let clone_el = el.cloneNode( true );

// append it to the body
document.body.append(clone_el);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="heading">This is a heading</h1></code>```

Body:
Consider you have a heading element. First you need to select the heading then create its clone using the cloneNode() function, it accepts a deep parameter which basically means the node and its whole subtree, including text that may be in child Text nodes, is also copied. After that we basically append the cloned element to the document body.

// select the heading
let el = document.querySelector('.heading');

// clone the element
let clone_el = el.cloneNode( true );

// append it to the body
document.body.append(clone_el);

<h1 class="heading">This is a heading</h1>


问:
Django 4.0 shows path not found even after configuring all urls and views properly
So my django app looks like this

```<code>-assaydash
--dashboard (app)
--members (app)
--djangobackend (django project directory)
--static
--manage.py
</code>```

djangobackend/settings.py

```<code># Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'dashboard.apps.DashboardConfig',
    'members.apps.MembersConfig',
]
</code>```

djangobackend/urls.py

```<code>urlpatterns = [
    path('admin/', admin.site.urls, name='admin'),
    path('', include('dashboard.urls')),
    path('members/', include('django.contrib.auth.urls')),
    path('members/', include('members.urls')),
]
</code>```

members/urls.py

```<code>urlpatterns = [
    path('login_user', views.login_user, name="login"),
    path('logout_user', views.logout_user, name='logout'),
]

</code>```

members/views.py

```<code>def login_user(request):
    if request.method == "POST":
        ...
        else:
            messages.success(request, ("There Was An Error Logging In, Try Again..."))
            return redirect('login')

    else:
        return render(request, 'authenticate/login.html', {})

def logout_user(request):
    logout(request)
    messages.success(request, ("You Were Logged Out!"))
    return redirect('home')
</code>```

index.html

```<code> <a href="{% url 'login' %}" >
    <span class="d-sm-inline d-none">Sign In</span>
 </a>
</code>```

On the index page when i click on the a tag it shows me a debug page with path not found. Even though the url exists and i have included it in my main urls.py and i have added the app in the settings.py as well. please help and let me know what is wrong here.
Notice that the url for name login was detected by the template but the path wasn't found. Also the other urls on the debug page are from my dashboard app which works fine

答:
Because you have set the url path of django.contrib.auth.urls to members/ and the django.contrib.auth.urls include patterns of /members/login/ for name=login. Since urlpatterns will look from upper to lower your /members/login/ called instead of /members/login_userand look for corresponding page. So change your url path to others than members/ in

```<code>path('members/', include('django.contrib.auth.urls')),
</code>```

and use members/ for include('members.urls').

If you have set

```<code>urlpatterns = [
    path('accounts/', include('django.contrib.auth.urls')),
</code>```

]

The django.contrib.auth.urls include urlpatterns as

```<code>accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']
</code>```

See Authentication Views[Django-doc]

So change your djangobackend/urls.py as

```<code>urlpatterns = [
    path('admin/', admin.site.urls, name='admin'),
    path('', include('dashboard.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('members/', include('members.urls')),
]
</code>```

Also change your member urls.py as

```<code>urlpatterns = [
    path('login_user', views.login_user, name="login-user"),
    path('logout_user', views.logout_user, name='logout-user'),
]
</code>```

Also in html

```<code><a href="{% url 'login-user' %}" >
    <span class="d-sm-inline d-none">Sign In</span>
 </a>
</code>```

Body:
So my django app looks like this

-assaydash
--dashboard (app)
--members (app)
--djangobackend (django project directory)
--static
--manage.py

djangobackend/settings.py

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'dashboard.apps.DashboardConfig',
    'members.apps.MembersConfig',
]

djangobackend/urls.py

urlpatterns = [
    path('admin/', admin.site.urls, name='admin'),
    path('', include('dashboard.urls')),
    path('members/', include('django.contrib.auth.urls')),
    path('members/', include('members.urls')),
]

members/urls.py

urlpatterns = [
    path('login_user', views.login_user, name="login"),
    path('logout_user', views.logout_user, name='logout'),
]

members/views.py

def login_user(request):
    if request.method == "POST":
        ...
        else:
            messages.success(request, ("There Was An Error Logging In, Try Again..."))
            return redirect('login')

    else:
        return render(request, 'authenticate/login.html', {})

def logout_user(request):
    logout(request)
    messages.success(request, ("You Were Logged Out!"))
    return redirect('home')

index.html

    Sign In

On the index page when i click on the a tag it shows me a debug page with path not found. Even though the url exists and i have included it in my main urls.py and i have added the app in the settings.py as well. please help and let me know what is wrong here.
Notice that the url for name login was detected by the template but the path wasn't found. Also the other urls on the debug page are from my dashboard app which works fine

Body:
Because you have set the url path of django.contrib.auth.urls to members/ and the django.contrib.auth.urls include patterns of /members/login/ for name=login. Since urlpatterns will look from upper to lower your /members/login/ called instead of /members/login_userand look for corresponding page. So change your url path to others than members/ in

path('members/', include('django.contrib.auth.urls')),

and use members/ for include('members.urls').

If you have set

urlpatterns = [
    path('accounts/', include('django.contrib.auth.urls')),

]

The django.contrib.auth.urls include urlpatterns as

accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']

See Authentication Views[Django-doc]

So change your djangobackend/urls.py as

urlpatterns = [
    path('admin/', admin.site.urls, name='admin'),
    path('', include('dashboard.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
    path('members/', include('members.urls')),
]

Also change your member urls.py as

urlpatterns = [
    path('login_user', views.login_user, name="login-user"),
    path('logout_user', views.logout_user, name='logout-user'),
]

Also in html

<a href="{% url 'login-user' %}" >
    <span class="d-sm-inline d-none">Sign In</span>
 </a>


问:
Video memory and android applications
I would like to know if the video memory (VRAM) that an android OpenGL application can use is limited ? If so, would you know what the limit is?</p>

答: The OpenGL driver allocates normal RAM until you run out of it and normal RAM size is device independent.  </p>

Title: Video memory and android applications


问:
Deep nested Array of Objects, set parentId as property in subTask
I am trying to set the parentId as property of every subTask. I have a structure like this (For example), which can grow very big and deep:

```<code>[
  {
    "id": 0,
    "lane": 0,
    "name": "Task A",
    "start": 0,
    "end": 10000,
    "subTasks": [
      {
        "id": "0.1",
        "lane": 0,
        "name": "Subtask",
        "start": 0,
        "end": 10000,
        "class": "danger",
        "sublane": 0,
        "subTasks": [
          {
            "id": "0.1.1",
            "name": "Subtask",
            "start": 0,
            "end": 10000,
            "subTasks": [
              {
                "id": "0.1.1.1",
                "name": "Subtask",
                "start": 0,
                "end": 10000,
                "subTasks": [
                  {
                    "id": "0.1.1.1.1",
                    "name": "Subtask",
                    "start": 0,
                    "end": 10000
                  },
                  {
                    "id": "0.1.1.1.2",
                    "name": "Subtask",
                    "start": 0,
                    "end": 10000
                  }
                ]
              },
              {
                "id": "0.1.1.2",
                "name": "Subtask",
                "start": 0,
                "end": 10000
              }
            ]
          },
          {
            "id": "0.1.2",
            "name": "Subtask",
            "start": 0,
            "end": 10000
          },
          {
            "id": "0.1.3",
            "name": "Subtask",
            "start": 0,
            "end": 10000
          }
        ]
      },
      {
        "id": "0.2",
        "name": "Subtask",
        "start": 0,
        "end": 10000
      }
    ],
    "class": "danger",
    "sublane": 0
  },
  {
    "id": 1,
    "lane": 2,
    "name": "Task B",
    "start": 15000,
    "end": 25000,
    ],
    "class": "success",
    "sublane": 0
  }
]
</code>```

I tried this, but it didnt work:

```<code> addParentId: function () {
        for (let obj of taskss.data) {
            taskss.depthIteration(obj);
        }
    },

    depthIteration: function (obj) {
        if (obj.subTasks && obj.subCollapsed === false) {
            for (let item of obj.subTasks) {
                item.parentId = obj.id;
                this.depthIteration(item);
            }
        }
        return null;
    },
</code>```

Now I want this data not just to be returned flatten, every task which is a subTask should have a parentId property. For example, the subTask with "id": "0.1.1" should also have a "parentId": "0.1".
How can I do this?

答:
const arr = [{
    id: 0,
    lane: 0,
    name: 'Task A',
    start: 0,
    end: 10000,
    subTasks: [{
        id: '0.1',
        lane: 0,
        name: 'Subtask',
        start: 0,
        end: 10000,
        class: 'danger',
        sublane: 0,
        subTasks: [{
            id: '0.1.1',
            name: 'Subtask',
            start: 0,
            end: 10000,
            subTasks: [{
                id: '0.1.1.1',
                name: 'Subtask',
                start: 0,
                end: 10000,
                subTasks: [{
                    id: '0.1.1.1.1',
                    name: 'Subtask',
                    start: 0,
                    end: 10000,
                  },
                  {
                    id: '0.1.1.1.2',
                    name: 'Subtask',
                    start: 0,
                    end: 10000,
                  },
                ],
              },
              {
                id: '0.1.1.2',
                name: 'Subtask',
                start: 0,
                end: 10000,
              },
            ],
          },
          {
            id: '0.1.2',
            name: 'Subtask',
            start: 0,
            end: 10000,
          },
          {
            id: '0.1.3',
            name: 'Subtask',
            start: 0,
            end: 10000,
          },
        ],
      },
      {
        id: '0.2',
        name: 'Subtask',
        start: 0,
        end: 10000,
      },
    ],
    class: 'danger',
    sublane: 0,
  },
  {
    id: 1,
    lane: 2,
    name: 'Task B',
    start: 15000,
    end: 25000,
    class: 'success',
    sublane: 0,
  },
];
const addParentId = (arr) => {
  arr.forEach((task) => {
    if (task.subTasks) {
      task.subTasks.forEach((subTask) => {
        subTask.parentId = task.id;
        if (subTask.subTasks) {
          addParentId(subTask.subTasks);
        }
      });
    }
  });
  return arr;
};
console.log(JSON.stringify(addParentId(arr), null, 2));```

Body:
I am trying to set the parentId as property of every subTask. I have a structure like this (For example), which can grow very big and deep:

[
  {
    "id": 0,
    "lane": 0,
    "name": "Task A",
    "start": 0,
    "end": 10000,
    "subTasks": [
      {
        "id": "0.1",
        "lane": 0,
        "name": "Subtask",
        "start": 0,
        "end": 10000,
        "class": "danger",
        "sublane": 0,
        "subTasks": [
          {
            "id": "0.1.1",
            "name": "Subtask",
            "start": 0,
            "end": 10000,
            "subTasks": [
              {
                "id": "0.1.1.1",
                "name": "Subtask",
                "start": 0,
                "end": 10000,
                "subTasks": [
                  {
                    "id": "0.1.1.1.1",
                    "name": "Subtask",
                    "start": 0,
                    "end": 10000
                  },
                  {
                    "id": "0.1.1.1.2",
                    "name": "Subtask",
                    "start": 0,
                    "end": 10000
                  }
                ]
              },
              {
                "id": "0.1.1.2",
                "name": "Subtask",
                "start": 0,
                "end": 10000
              }
            ]
          },
          {
            "id": "0.1.2",
            "name": "Subtask",
            "start": 0,
            "end": 10000
          },
          {
            "id": "0.1.3",
            "name": "Subtask",
            "start": 0,
            "end": 10000
          }
        ]
      },
      {
        "id": "0.2",
        "name": "Subtask",
        "start": 0,
        "end": 10000
      }
    ],
    "class": "danger",
    "sublane": 0
  },
  {
    "id": 1,
    "lane": 2,
    "name": "Task B",
    "start": 15000,
    "end": 25000,
    ],
    "class": "success",
    "sublane": 0
  }
]

I tried this, but it didnt work:

 addParentId: function () {
        for (let obj of taskss.data) {
            taskss.depthIteration(obj);
        }
    },

    depthIteration: function (obj) {
        if (obj.subTasks && obj.subCollapsed === false) {
            for (let item of obj.subTasks) {
                item.parentId = obj.id;
                this.depthIteration(item);
            }
        }
        return null;
    },

Now I want this data not just to be returned flatten, every task which is a subTask should have a parentId property. For example, the subTask with "id": "0.1.1" should also have a "parentId": "0.1".
How can I do this?


问:
How to open a new window on textbox click using tkinter
I have a program where upon pressing login button opens a new screen. On this screen is 3 text boxes which upon pressing I would like to open a new screen (this new screen will eventually become a numpad or keyboard used to enter data).

However i am struggling to get the new window to open upon clicking the textbox.

In essence Main screen open upon load. login widget opens when login button is pressed. upon clicking any text box calibration1, calibration2 or calibration3, this should open widget new_window.

new_window will eventually be turned into a keyboard or numpad.

```<code>from tkinter import *
import os
import time
from tkinter import simpledialog

def new_window():
    global screen6
    screen6 = Toplevel(screen)
    screen6.title("Sucess")
    screen6.geometry("150x100")
    Label(screen4, text = "New Window Openned Successfully").pack()

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()

    global calibration1_entry
    global calibration2_entry
    global calibration3_entry

    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()

    screen.mainloop()

main_screen()
</code>```

any Help would be greatly appreciated

答:
Your code:

```<code>  calibration1_entry = Entry(screen2, textvariable=calibration1).place(x=350, y=70)
</code>```

assign None to calibration1_entry. It should be:

```<code>calibration1_entry = Entry(screen2, textvariable=calibration1)
calibration1_entry.place(x=350, y=70) # return None
calibration1_entry.bind('<Button-1>', lambda e: print(e))
</code>```

Instead of print(e) you must use your function.

Body:
I have a program where upon pressing login button opens a new screen. On this screen is 3 text boxes which upon pressing I would like to open a new screen (this new screen will eventually become a numpad or keyboard used to enter data).

However i am struggling to get the new window to open upon clicking the textbox.

In essence Main screen open upon load. login widget opens when login button is pressed. upon clicking any text box calibration1, calibration2 or calibration3, this should open widget new_window.

new_window will eventually be turned into a keyboard or numpad.

from tkinter import *
import os
import time
from tkinter import simpledialog

def new_window():
    global screen6
    screen6 = Toplevel(screen)
    screen6.title("Sucess")
    screen6.geometry("150x100")
    Label(screen4, text = "New Window Openned Successfully").pack()

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()

    global calibration1_entry
    global calibration2_entry
    global calibration3_entry

    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()

    screen.mainloop()

main_screen()

any Help would be greatly appreciated

Body:
Your code:

  calibration1_entry = Entry(screen2, textvariable=calibration1).place(x=350, y=70)

assign None to calibration1_entry. It should be:

calibration1_entry = Entry(screen2, textvariable=calibration1)
calibration1_entry.place(x=350, y=70) # return None
calibration1_entry.bind('<Button-1>', lambda e: print(e))

Instead of print(e) you must use your function.


问:
Filtering and array mapping issue in react
This is a translate of the original question, sorry for the english

I'm creating a filter for the notifications of an app I'm working on, the app is in react, the thing is this, I'm trying to use filter and map, but for some reason, I think it's probably some syntax error on my part, it does not do the filtering part, in the data I receive there is a value called status, if this is completed I want it to be removed from the new array.

status is located in notifications.data.status I put below the way I receive the data

notifications.data

It only does the mapping, I have to use Object.keys, because of the rest it gives me a compiled error, thank you very much

```<code>          <GlobalNotifications id="GlobalNotifications">
            {/* {console.log(Object.keys(notifications.data).filter(notification => notification.status !== 'completed'))} */}
            {console.log(Object.values(notifications.data))}
            {Object.keys(notifications.data)
              .filter(notification => notification.status !== 'completed')
              .map(key => (
                <NotificationItem
                  id={key}
                  key={key}
                  data={notifications.data[key]}
                  openHistory={openHistory === key}
                  callbackOpenHistory={onOpenHistory}
                />
              ))}
          </GlobalNotifications>
</code>```

答:
Your notifications.data is already an array, so you don't need to use Object.keys() to return an array.

```<code>filteredArray = data
  .filter((notification) => notification.status === "accepted")
</code>```

Then map the returned filtered array (I used 'accepted' as it gave more elements to play with) based on each item.
.map((item) => { the brackets for your code and return(make sure to return your jsx within these parentheses)})

It is best to use a unique key when making a list, so I chose to use your item._id for the key. Sample Data and code below followed by output

```<code>    import "./styles.css";
    let data = [
      {
        status: "completed",
        events: [],
        _id: 1
      },
      {
        status: "accepted",
        events: [],
        _id: 2
      },
      {
        status: "accepted",
        events: [],
        _id: 3
      },
      {
        status: "accepted",
        events: [],
        _id: 4
      },
      {
        status: "accepted",
        events: [],
        _id: 5
      },
      {
        status: "accepted",
        events: [],
        _id: 6
      },
      {
        status: "accepted",
        events: [],
        _id: 7
      },
      {
        status: "accepted",
        events: [],
        _id: 8
      },
      {
        status: "accepted",
        events: [],
        _id: 9
      },
      {
        status: "accepted",
        events: [],
        _id: 10
      }
    ];
    const filteredArray = data
      .filter((notification) => notification.status === "accepted")
      .map((item) => {
        let key = item._id;
        return (
          <div key={key}>
            id: {key}; status: {item.status}
          </div>
        );
      });

</code>```

Output:

id: 2; status: accepted

id: 3; status: accepted

id: 4; status: accepted

id: 5; status: accepted

id: 6; status: accepted

id: 7; status: accepted

id: 8; status: accepted

id: 9; status: accepted

id: 10; status: accepted

Body:
This is a translate of the original question, sorry for the english

I'm creating a filter for the notifications of an app I'm working on, the app is in react, the thing is this, I'm trying to use filter and map, but for some reason, I think it's probably some syntax error on my part, it does not do the filtering part, in the data I receive there is a value called status, if this is completed I want it to be removed from the new array.

status is located in notifications.data.status I put below the way I receive the data

notifications.data

It only does the mapping, I have to use Object.keys, because of the rest it gives me a compiled error, thank you very much

          <GlobalNotifications id="GlobalNotifications">
            {/* {console.log(Object.keys(notifications.data).filter(notification => notification.status !== 'completed'))} */}
            {console.log(Object.values(notifications.data))}
            {Object.keys(notifications.data)
              .filter(notification => notification.status !== 'completed')
              .map(key => (
                <NotificationItem
                  id={key}
                  key={key}
                  data={notifications.data[key]}
                  openHistory={openHistory === key}
                  callbackOpenHistory={onOpenHistory}
                />
              ))}
          </GlobalNotifications>

Body:
Your notifications.data is already an array, so you don't need to use Object.keys() to return an array.

filteredArray = data
  .filter((notification) => notification.status === "accepted")

Then map the returned filtered array (I used 'accepted' as it gave more elements to play with) based on each item.
.map((item) => { the brackets for your code and return(make sure to return your jsx within these parentheses)})

It is best to use a unique key when making a list, so I chose to use your item._id for the key. Sample Data and code below followed by output

    import "./styles.css";
    let data = [
      {
        status: "completed",
        events: [],
        _id: 1
      },
      {
        status: "accepted",
        events: [],
        _id: 2
      },
      {
        status: "accepted",
        events: [],
        _id: 3
      },
      {
        status: "accepted",
        events: [],
        _id: 4
      },
      {
        status: "accepted",
        events: [],
        _id: 5
      },
      {
        status: "accepted",
        events: [],
        _id: 6
      },
      {
        status: "accepted",
        events: [],
        _id: 7
      },
      {
        status: "accepted",
        events: [],
        _id: 8
      },
      {
        status: "accepted",
        events: [],
        _id: 9
      },
      {
        status: "accepted",
        events: [],
        _id: 10
      }
    ];
    const filteredArray = data
      .filter((notification) => notification.status === "accepted")
      .map((item) => {
        let key = item._id;
        return (
          <div key={key}>
            id: {key}; status: {item.status}
          </div>
        );
      });

Output:

id: 2; status: accepted

id: 3; status: accepted

id: 4; status: accepted

id: 5; status: accepted

id: 6; status: accepted

id: 7; status: accepted

id: 8; status: accepted

id: 9; status: accepted

id: 10; status: accepted


问:
Google artifact regitsry NPM + github action
I'm trying to publish a npm package on GAR (Google Artifact Registry) through github using google-github-actions/auth@v0 and google-artifactregistry-auth

For the authentication to google from github here is what I did to use the Federation Workload Identity:

export PROJECT_ID="my-project-id"

gcloud iam service-accounts create "gh-deploy-service-account" --project "${PROJECT_ID}"

gcloud iam workload-identity-pools create "github-pool" --project="${PROJECT_ID}" --location="global" --display-name="Github pool"

gcloud iam workload-identity-pools describe github-pool" --project="${PROJECT_ID}" --location="global" --format="value(name)"

export WORKLOAD_IDENTITY_POOL_ID=projects/my-custom-id-number/locations/global/workloadIdentityPools/github-pool

gcloud iam workload-identity-pools providers create-oidc "github-provider" \
  --project="${PROJECT_ID}" \
  --location="global" \
  --workload-identity-pool="github-pool" \
  --display-name="Github provider" \
  --attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.repository=assertion.repository" \
  --issuer-uri="https://token.actions.githubusercontent.com"

export REPO="@example/my-package"

gcloud iam service-accounts add-iam-policy-binding "gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/${WORKLOAD_IDENTITY_POOL_ID}/attribute.repository/${REPO}"
```
<p>Then I created my artifact repository on google :</p>
<pre class="lang-sh prettyprint-override"><code>gcloud artifacts repositories create npm-repository --repository-format=npm --location=asia-east2
</code>```

Here is my github workflows :

name: Publish Package
on:
  push:
    branches:
      - main

jobs:
  publish:
    timeout-minutes: 10
    runs-on: ubuntu-latest
    permissions:
      contents: "read"
      id-token: "write"
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - uses: actions/setup-node@v2
        with:
          node-version: 16

      - name: Install
        run: npm ci

      - id: "auth"
        name: "Authenticate to Google Cloud"
        uses: "google-github-actions/auth@v0"
        with:
          workload_identity_provider: ${{ secrets.WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.SERVICE_ACCOUNT }}
          create_credentials_file: true

      - name: "Set up Cloud SDK"
        uses: "google-github-actions/setup-gcloud@v0"

      - name: Create .npmrc
        run: |
          cat << EOF > .npmrc
            @example:registry=https://asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:_authToken=""
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:always-auth=true
          EOF

      - name: Artifact login
        run: |
          #export GOOGLE_APPLICATION_CREDENTIALS=${{ steps.auth.outputs.credentials_file_path }}
          npx google-artifactregistry-auth@v3 --repo-config=[./.npmrc] --credential-config=[./.npmrc]

```
<p>But on this workflow, I got an error on the step <code>Artifact login</code>. Telling me :</p>
```npm WARN exec The following package was not found and will be installed: google-artifactregistry-auth
Retrieving application default credentials...
Retrieving credentials from gcloud...
Error: Fail to get credentials. Please run:
`gcloud auth application-default login`, `gcloud auth login`, or
`export GOOGLE_APPLICATION_CREDENTIALS=<path/to/service/account/key>`
    at Object.getCreds (/home/runner/.npm/_npx/64aef35f3ba01c7c/node_modules/google-artifactregistry-auth/src/auth.js:40:9)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async main (/home/runner/.npm/_npx/64aef35f3ba01c7c/node_modules/google-artifactregistry-auth/src/main.js:66:19)
Error: Process completed with exit code 1.
```
<p>The full workflow is available here
I don't know where is my mistake here. Does my service account need more right ? or is it an issue on the <code>google-artifactregistry-auth</code> ? I really don't know :/</p>
<p>Thx in advance for you help !</p>
<p>EDIT 1 : I tried to follow this documentation and I added to my service account some right :</p>
<pre class="lang-sh prettyprint-override"><code>gcloud artifacts repositories add-iam-policy-binding npm-repository \
--location asia-east2 --member=serviceAccount:my-service-account --role=roles/artifactregistry.writer
</code>```

答:
I finally find out !!!
BUT I'm not sure in term of security if there is any risk or not so if anyone can advice I'll edit the answer !

What is changing but I'm not sure in term of security is here :

gcloud iam service-accounts add-iam-policy-binding "gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.serviceAccountTokenCreator" \
  --member="principalSet://iam.googleapis.com/projects/MY_PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool-2/*"

gcloud iam service-accounts add-iam-policy-binding "gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/MY_PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool-2/*"

```
<p>I think I don't really get the <code>principalSet</code> option and all the attribute possible so if anyone can advice also on this, I'll be grateful !</p>
<p>Then don't forget to bind your repo to your service account :</p>
<pre class="lang-sh prettyprint-override"><code>gcloud artifacts repositories add-iam-policy-binding npm-repository \
--location asia-east2 --member=serviceAccount:gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com --role=roles/artifactregistry.writer
</code>```

And for the github workflow I remove the google-artifactregistry-auth  and i use the access_token in the .npmrc file.

Here is the full workflow :

name: Publish Package
on:
  push:
    branches:
      - main

jobs:
  publish:
    timeout-minutes: 10
    runs-on: ubuntu-latest
    permissions:
      contents: "read"
      id-token: "write"
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - uses: actions/setup-node@v2
        with:
          node-version: 16

      - name: Install
        run: npm ci

      - id: "auth"
        name: "Authenticate to Google Cloud"
        uses: "google-github-actions/auth@v0"
        with:
          workload_identity_provider: ${{ secrets.WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.SERVICE_ACCOUNT }}
          token_format: 'access_token'

      - name: "Set up Cloud SDK"
        uses: "google-github-actions/setup-gcloud@v0"

      - name: Create .npmrc
        run: |
          cat << EOF > .npmrc
            @example:registry=https://asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:_authToken="${{ steps.auth.outputs.access_token }}"
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:always-auth=true
          EOF

      - name: Artifact login
        run: |
          npm publish
```

Body:
I'm trying to publish a npm package on GAR (Google Artifact Registry) through github using google-github-actions/auth@v0 and google-artifactregistry-auth

For the authentication to google from github here is what I did to use the Federation Workload Identity:

export PROJECT_ID="my-project-id"

gcloud iam service-accounts create "gh-deploy-service-account" --project "${PROJECT_ID}"

gcloud iam workload-identity-pools create "github-pool" --project="${PROJECT_ID}" --location="global" --display-name="Github pool"

gcloud iam workload-identity-pools describe github-pool" --project="${PROJECT_ID}" --location="global" --format="value(name)"

export WORKLOAD_IDENTITY_POOL_ID=projects/my-custom-id-number/locations/global/workloadIdentityPools/github-pool

gcloud iam workload-identity-pools providers create-oidc "github-provider" \
  --project="${PROJECT_ID}" \
  --location="global" \
  --workload-identity-pool="github-pool" \
  --display-name="Github provider" \
  --attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.repository=assertion.repository" \
  --issuer-uri="https://token.actions.githubusercontent.com"

export REPO="@example/my-package"

gcloud iam service-accounts add-iam-policy-binding "gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/${WORKLOAD_IDENTITY_POOL_ID}/attribute.repository/${REPO}"

Then I created my artifact repository on google :

gcloud artifacts repositories create npm-repository --repository-format=npm --location=asia-east2

Here is my github workflows :

name: Publish Package
on:
  push:
    branches:
      - main

jobs:
  publish:
    timeout-minutes: 10
    runs-on: ubuntu-latest
    permissions:
      contents: "read"
      id-token: "write"
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - uses: actions/setup-node@v2
        with:
          node-version: 16

      - name: Install
        run: npm ci

      - id: "auth"
        name: "Authenticate to Google Cloud"
        uses: "google-github-actions/auth@v0"
        with:
          workload_identity_provider: ${{ secrets.WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.SERVICE_ACCOUNT }}
          create_credentials_file: true

      - name: "Set up Cloud SDK"
        uses: "google-github-actions/setup-gcloud@v0"

      - name: Create .npmrc
        run: |
          cat << EOF > .npmrc
            @example:registry=https://asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:_authToken=""
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:always-auth=true
          EOF

      - name: Artifact login
        run: |
          #export GOOGLE_APPLICATION_CREDENTIALS=${{ steps.auth.outputs.credentials_file_path }}
          npx google-artifactregistry-auth@v3 --repo-config=[./.npmrc] --credential-config=[./.npmrc]

But on this workflow, I got an error on the step Artifact login. Telling me :

npm WARN exec The following package was not found and will be installed: google-artifactregistry-auth
Retrieving application default credentials...
Retrieving credentials from gcloud...
Error: Fail to get credentials. Please run:
`gcloud auth application-default login`, `gcloud auth login`, or
`export GOOGLE_APPLICATION_CREDENTIALS=<path/to/service/account/key>`
    at Object.getCreds (/home/runner/.npm/_npx/64aef35f3ba01c7c/node_modules/google-artifactregistry-auth/src/auth.js:40:9)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async main (/home/runner/.npm/_npx/64aef35f3ba01c7c/node_modules/google-artifactregistry-auth/src/main.js:66:19)
Error: Process completed with exit code 1.

The full workflow is available here
I don't know where is my mistake here. Does my service account need more right ? or is it an issue on the google-artifactregistry-auth ? I really don't know :/

Thx in advance for you help !

EDIT 1 : I tried to follow this documentation and I added to my service account some right :

gcloud artifacts repositories add-iam-policy-binding npm-repository \
--location asia-east2 --member=serviceAccount:my-service-account --role=roles/artifactregistry.writer

Body:
I finally find out !!!
BUT I'm not sure in term of security if there is any risk or not so if anyone can advice I'll edit the answer !

What is changing but I'm not sure in term of security is here :

gcloud iam service-accounts add-iam-policy-binding "gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.serviceAccountTokenCreator" \
  --member="principalSet://iam.googleapis.com/projects/MY_PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool-2/*"

gcloud iam service-accounts add-iam-policy-binding "gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com" \
  --project="${PROJECT_ID}" \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/MY_PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool-2/*"

I think I don't really get the principalSet option and all the attribute possible so if anyone can advice also on this, I'll be grateful !

Then don't forget to bind your repo to your service account :

gcloud artifacts repositories add-iam-policy-binding npm-repository \
--location asia-east2 --member=serviceAccount:gh-deploy-service-account@${PROJECT_ID}.iam.gserviceaccount.com --role=roles/artifactregistry.writer

And for the github workflow I remove the google-artifactregistry-auth  and i use the access_token in the .npmrc file.

Here is the full workflow :

name: Publish Package
on:
  push:
    branches:
      - main

jobs:
  publish:
    timeout-minutes: 10
    runs-on: ubuntu-latest
    permissions:
      contents: "read"
      id-token: "write"
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - uses: actions/setup-node@v2
        with:
          node-version: 16

      - name: Install
        run: npm ci

      - id: "auth"
        name: "Authenticate to Google Cloud"
        uses: "google-github-actions/auth@v0"
        with:
          workload_identity_provider: ${{ secrets.WORKLOAD_IDENTITY_PROVIDER }}
          service_account: ${{ secrets.SERVICE_ACCOUNT }}
          token_format: 'access_token'

      - name: "Set up Cloud SDK"
        uses: "google-github-actions/setup-gcloud@v0"

      - name: Create .npmrc
        run: |
          cat << EOF > .npmrc
            @example:registry=https://asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:_authToken="${{ steps.auth.outputs.access_token }}"
            //asia-east2-npm.pkg.dev/${{ secrets.GCP_PROJECT_ID }}/npm-repository/:always-auth=true
          EOF

      - name: Artifact login
        run: |
          npm publish


问:
Trouble figuring out why my procedure to print out bits of each integer in an array isn't working
I'm trying to make a class that optimizes an array of booleans by storing an ordered array of integers whose bits individual bits can be accessed to see if they're on or off. Yes, I know that

```<code>std::vector<bool>
</code>```

does something like this, but I'm trying to make my own implementation, for practice.

For instance, an unsigned short int is 16 bits, so I can pack 100 bools into an array of of 7 unsigned short ints where the last element acts as padding.

As I test this, I see that something is already going wrong, possibly something with my print() function. In main you can see that I made a BitPack object of 32 bools, which will be stored in an array of 2 unsigned short ints, and I've verified that this is so. However, my print function isn't working because it gives me the following output, which isn't 32 zeros, as it should be.

```<code>0000000000000000
</code>```

I've looked over my print function numerous times and can't figure out what is wrong. Sorry about any indentations that got lost when I copied my code here. Any help greatly appreciated.

```<code>#include <iostream>
#include <limits.h>
#include <assert.h>

typedef unsigned short int usi;

class BitPack {

public:
    BitPack(int);
    ~BitPack();
    bool getVal(int);
    int getSize();
    void setVal(int, bool);
    void print();

private:
    const static int USI_BITS = sizeof(usi)*CHAR_BIT;
    usi* _booArr;
    int _booArrLen;
    int _numBoos;

};

BitPack::BitPack(int sz) {
     assert (sz > 0);
      _numBoos = sz;
  _booArrLen = _numBoos/USI_BITS+(_numBoos % USI_BITS ? 1 : 0);
  _booArr = new usi[_booArrLen];
  for (int i = 0; i < _booArrLen; ++i)
     _booArr[i] = 0;
}

BitPack::~BitPack() {
    delete[] _booArr;
}

bool BitPack::getVal(int indx) {
    assert (indx > 0);
    usi bA_indx_val = _booArr[indx/USI_BITS];
    bA_indx_val >>= (bA_indx_val % USI_BITS);
    return (bA_indx_val % 2 ? true : false);
}

int BitPack::getSize() {
    return (_numBoos);
}

void BitPack::setVal(int indx, bool valset) {
    assert (indx > 0);
    bool curval = getVal(indx);
    if ((curval == true) && (valset == false)) {
        _booArr[indx/USI_BITS] += (1 << (indx % USI_BITS));
    } else if ((curval == true) && (valset == false)) {
        _booArr[indx/USI_BITS] -= (1 << (indx % USI_BITS));
    }
}

void BitPack::print() {
    int i = 0;
    usi thisval;
    while (i < _booArrLen - 1) {
        thisval = _booArr[i];
        for (int j = 0; j < USI_BITS; ++j) {
            std::cout << (thisval % 2 ? '1' : '0');
            thisval >>= 1;
        }
        i++;
    }
    thisval = _booArr[i];
    for (int j = 0; j < _numBoos % USI_BITS; ++j) {
        std::cout << (thisval % 2 ? '1' : '0');
        thisval >>= 1;
    }
}

int main (int argc, char* const argv[]) {

    BitPack bp(32);
    bp.print();

    return 0;
}
</code>```

答:
'This can be done in VB.NET.

'I have an array of 20 Shorts or Integers and I want to transfer these both into and out of a Boolean Array of 320 Items (16 bits)

'I'm using a checkbox array but can us Treeview or other Boolean Object Array

'MyCheckbox(320) is declared as Public

'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
Private Sub ReadData() 'Reads Integer (0-65535)

```<code>Dim Intx As Int16
Dim Bit As Int16

For Intx = 0 To 19
        For Bit = 0 To 15
            MyCheckbox(Bit + (Intx * 16)).Checked = CBool(MyDataTable.Data(Intx) And CInt(2 ^ Bit))
        Next Bit
    Next Intx
End Sub

</code>```

'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------

Private Sub WriteData() ' Writes same data back as Short if it has changed (-32768-32767)

Dim Shorty As Short
Dim Bit As Short

```<code>For Shorty = 0 To 19 ' Array of 20 Type Integer or Short
     For Bit = 0 To 15 ' 16 Bits
            If MyCheckbox(Bit + (Shorty * 16)).Checked Then
                MyDataTable.Data(Shorty) = (MyDataTable.Data(Shorty) Or CShort(1S << Bit))
                Else
                  MyDataTable.Data(Shorty) = (MyDataTable.Data(Shorty) And Not (CShort(1S << Bit)))
             End If
Next
    Next
End Sub
</code>```

'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------

Body:
I'm trying to make a class that optimizes an array of booleans by storing an ordered array of integers whose bits individual bits can be accessed to see if they're on or off. Yes, I know that

std::vector<bool>

does something like this, but I'm trying to make my own implementation, for practice.

For instance, an unsigned short int is 16 bits, so I can pack 100 bools into an array of of 7 unsigned short ints where the last element acts as padding.

As I test this, I see that something is already going wrong, possibly something with my print() function. In main you can see that I made a BitPack object of 32 bools, which will be stored in an array of 2 unsigned short ints, and I've verified that this is so. However, my print function isn't working because it gives me the following output, which isn't 32 zeros, as it should be.

0000000000000000

I've looked over my print function numerous times and can't figure out what is wrong. Sorry about any indentations that got lost when I copied my code here. Any help greatly appreciated.

#include <iostream>
#include <limits.h>
#include <assert.h>

typedef unsigned short int usi;

class BitPack {

public:
    BitPack(int);
    ~BitPack();
    bool getVal(int);
    int getSize();
    void setVal(int, bool);
    void print();

private:
    const static int USI_BITS = sizeof(usi)*CHAR_BIT;
    usi* _booArr;
    int _booArrLen;
    int _numBoos;

};

BitPack::BitPack(int sz) {
     assert (sz > 0);
      _numBoos = sz;
  _booArrLen = _numBoos/USI_BITS+(_numBoos % USI_BITS ? 1 : 0);
  _booArr = new usi[_booArrLen];
  for (int i = 0; i < _booArrLen; ++i)
     _booArr[i] = 0;
}

BitPack::~BitPack() {
    delete[] _booArr;
}

bool BitPack::getVal(int indx) {
    assert (indx > 0);
    usi bA_indx_val = _booArr[indx/USI_BITS];
    bA_indx_val >>= (bA_indx_val % USI_BITS);
    return (bA_indx_val % 2 ? true : false);
}

int BitPack::getSize() {
    return (_numBoos);
}

void BitPack::setVal(int indx, bool valset) {
    assert (indx > 0);
    bool curval = getVal(indx);
    if ((curval == true) && (valset == false)) {
        _booArr[indx/USI_BITS] += (1 << (indx % USI_BITS));
    } else if ((curval == true) && (valset == false)) {
        _booArr[indx/USI_BITS] -= (1 << (indx % USI_BITS));
    }
}

void BitPack::print() {
    int i = 0;
    usi thisval;
    while (i < _booArrLen - 1) {
        thisval = _booArr[i];
        for (int j = 0; j < USI_BITS; ++j) {
            std::cout << (thisval % 2 ? '1' : '0');
            thisval >>= 1;
        }
        i++;
    }
    thisval = _booArr[i];
    for (int j = 0; j < _numBoos % USI_BITS; ++j) {
        std::cout << (thisval % 2 ? '1' : '0');
        thisval >>= 1;
    }
}

int main (int argc, char* const argv[]) {

    BitPack bp(32);
    bp.print();

    return 0;
}

Body:
'This can be done in VB.NET.

'I have an array of 20 Shorts or Integers and I want to transfer these both into and out of a Boolean Array of 320 Items (16 bits)

'I'm using a checkbox array but can us Treeview or other Boolean Object Array

'MyCheckbox(320) is declared as Public

'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------
Private Sub ReadData() 'Reads Integer (0-65535)

Dim Intx As Int16
Dim Bit As Int16

For Intx = 0 To 19
        For Bit = 0 To 15
            MyCheckbox(Bit + (Intx * 16)).Checked = CBool(MyDataTable.Data(Intx) And CInt(2 ^ Bit))
        Next Bit
    Next Intx
End Sub

'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------

Private Sub WriteData() ' Writes same data back as Short if it has changed (-32768-32767)

Dim Shorty As Short
Dim Bit As Short

For Shorty = 0 To 19 ' Array of 20 Type Integer or Short
     For Bit = 0 To 15 ' 16 Bits
            If MyCheckbox(Bit + (Shorty * 16)).Checked Then
                MyDataTable.Data(Shorty) = (MyDataTable.Data(Shorty) Or CShort(1S << Bit))
                Else
                  MyDataTable.Data(Shorty) = (MyDataTable.Data(Shorty) And Not (CShort(1S << Bit)))
             End If
Next
    Next
End Sub

'-----------------------------------------------------------------------------
'-----------------------------------------------------------------------------