问:
eBay Feed API -> uploadFile script working on local PC but not working on live server
Here is my script which uploads feed to ebay. The script working on local PC but when I upload to my live server, it does not work.

Here is my code.

```<code>public function createTask($feedType='FX_LISTING')
    {
        $link = "https://api.ebay.com/sell/feed/v1/task";
        //$appConfig = parse_ini_file("config.ini");

        //payload
        $payload = json_encode(array("schemaVersion"=>"1.0","feedType"=>"FX_LISTING"));

        //$appConfig['user_token'] = 'mehboob';
        $ch = curl_init($link);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization:Bearer ' . $this->userToken,
            'Accept:application/json',
            'Content-Type:application/json',
            'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ));
        curl_setopt($ch, CURLHEADER_SEPARATE, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //scurl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        $response = curl_exec($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $info = curl_getinfo($ch);

        echo($body);
        curl_close($ch);

        $headers = explode("\r\n", $headers); // The seperator used in the Response Header is CRLF (Aka. \r\n)

        $headers = array_filter($headers);

        $loc = basename(implode(preg_grep("/^location.*/", $headers)));
      return $loc;

    }

    public function uploadFile($taskID, $fName)
    {
          $link = "https://api.ebay.com/sell/feed/v1/task/$taskID/upload_file";
         $curl = curl_init();
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt_array($curl, array(
        CURLOPT_URL => $link,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYHOST=> 1,
        CURLOPT_SSL_VERIFYPEER=> 1,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_HEADER => 1,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('file'=> new CURLFILE(realpath($fName)),'type' => 'form-data'),
        CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $this->userToken,
        'Content-Type: multipart/form-data',
        'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ),

        ));

        $response = curl_exec($curl);
        var_dump($response);

        curl_close($curl);

    }
</code>```

Using the code as under:

```<code>$feedPath = __DIR__ . "/" ."feed.csv";
$taskID= createTask();
$uF = uploadFile($taskID,$feedPath);
</code>```

The above code works fine on my local PC, creating task id and uploading file to ebay. But when I am uploading code on my server, it gets failed.
I confirmed the path to the file on my server is OK.
Also I am using the same version of PHP on my server.

Please see the following response I receives from Server.

```<code>string(595) "HTTP/1.1 100 Continue HTTP/1.1 500 Internal Server Error rlogid: t6pitaf%60btuf1%3D9vjdpitaf%60btuf1*or3ah%28rbpv6775-1795f5551e5-0x2340 x-ebay-client-tls-version: TLSv1.2 content-type: application/json content-length: 228 date: Wed, 12 May 2021 06:48:18 GMT x-envoy-upstream-service-time: 125 server: ebay-proxy-server x-ebay-pop-id: UFES2-LVSAZ01-api {"errors":[{"errorId":160001,"domain":"API_FEED","subdomain":"Selling","category":"APPLICATION","message":"There was a problem with an eBay internal system or process. Contact eBay Developer Technical Support for assistance."}]}"
</code>```

The error says about "eBay internal error" but I don't think so. its due to some problem in the code.

The documentation to the above eBay service is as under:
eBay Feed File - uploadFile documentation

Your cooperation in this context will be highly appreciated.

答:
```<code>CREATE TASK
============
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.ebay.com/sell/feed/v1/task',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
  "schemaVersion": "1149",
  "feedType": "LMS_REVISE_INVENTORY_STATUS"
}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer v^1.1#i^1#p^3#I^*****YOUR USER ACCESS TOKEN HERE****py9v3J3ALc5rcFAAA',
    'Accept: application/json',
    'Content-Type: application/json',
    'X-EBAY-C-MARKETPLACE-ID: EBAY_GB'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

UPLOAD FILE
===========

test.xml file
-------------
<?xml version="1.0" encoding="utf-8"?>
<ReviseInventoryStatusRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <RequesterCredentials>
    <eBayAuthToken></eBayAuthToken>
  </RequesterCredentials>
    <ErrorLanguage>en_US</ErrorLanguage>
    <WarningLevel>High</WarningLevel>
  <InventoryStatus>
    <SKU>test-1111</SKU>
    <Quantity>10</Quantity>
  </InventoryStatus>
  <InventoryStatus>
    <SKU>test-2222</SKU>
    <Quantity>20</Quantity>
  </InventoryStatus>
</ReviseInventoryStatusRequest>

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.ebay.com/sell/feed/v1/task/task-12-1127376027/upload_file',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array('fileName' => 'test.xml','file'=> new CURLFILE('/F:/test.xml'),'type' => 'form-data'),
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer v^1.1#i^1#p^3#I^*****YOUR USER ACCESS TOKEN HERE****py9v3J3ALc5rcFAAA',
    'X-EBAY-C-MARKETPLACE-ID: EBAY_GB',
    'Accept: application/json',
    'Content-Type: multipart/form-data'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

GETTASK
=======
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.ebay.com/sell/feed/v1/task/task-12-1127376027',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer v^1.1#i^1#p^3#I^*****YOUR USER ACCESS TOKEN HERE****py9v3J3ALc5rcFAAA',
    'Accept: application/json',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
</code>```

Body:
Here is my script which uploads feed to ebay. The script working on local PC but when I upload to my live server, it does not work.

Here is my code.

public function createTask($feedType='FX_LISTING')
    {
        $link = "https://api.ebay.com/sell/feed/v1/task";
        //$appConfig = parse_ini_file("config.ini");

        //payload
        $payload = json_encode(array("schemaVersion"=>"1.0","feedType"=>"FX_LISTING"));

        //$appConfig['user_token'] = 'mehboob';
        $ch = curl_init($link);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization:Bearer ' . $this->userToken,
            'Accept:application/json',
            'Content-Type:application/json',
            'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ));
        curl_setopt($ch, CURLHEADER_SEPARATE, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //scurl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        $response = curl_exec($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $info = curl_getinfo($ch);

        echo($body);
        curl_close($ch);

        $headers = explode("\r\n", $headers); // The seperator used in the Response Header is CRLF (Aka. \r\n)

        $headers = array_filter($headers);

        $loc = basename(implode(preg_grep("/^location.*/", $headers)));
      return $loc;

    }

    public function uploadFile($taskID, $fName)
    {
          $link = "https://api.ebay.com/sell/feed/v1/task/$taskID/upload_file";
         $curl = curl_init();
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        // curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');
        curl_setopt_array($curl, array(
        CURLOPT_URL => $link,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_SSL_VERIFYHOST=> 1,
        CURLOPT_SSL_VERIFYPEER=> 1,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_HEADER => 1,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => array('file'=> new CURLFILE(realpath($fName)),'type' => 'form-data'),
        CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $this->userToken,
        'Content-Type: multipart/form-data',
        'X-EBAY-C-MARKETPLACE-ID: EBAY_US'
        ),

        ));

        $response = curl_exec($curl);
        var_dump($response);

        curl_close($curl);

    }

Using the code as under:

$feedPath = __DIR__ . "/" ."feed.csv";
$taskID= createTask();
$uF = uploadFile($taskID,$feedPath);

The above code works fine on my local PC, creating task id and uploading file to ebay. But when I am uploading code on my server, it gets failed.
I confirmed the path to the file on my server is OK.
Also I am using the same version of PHP on my server.

Please see the following response I receives from Server.

string(595) "HTTP/1.1 100 Continue HTTP/1.1 500 Internal Server Error rlogid: t6pitaf%60btuf1%3D9vjdpitaf%60btuf1*or3ah%28rbpv6775-1795f5551e5-0x2340 x-ebay-client-tls-version: TLSv1.2 content-type: application/json content-length: 228 date: Wed, 12 May 2021 06:48:18 GMT x-envoy-upstream-service-time: 125 server: ebay-proxy-server x-ebay-pop-id: UFES2-LVSAZ01-api {"errors":[{"errorId":160001,"domain":"API_FEED","subdomain":"Selling","category":"APPLICATION","message":"There was a problem with an eBay internal system or process. Contact eBay Developer Technical Support for assistance."}]}"

The error says about "eBay internal error" but I don't think so. its due to some problem in the code.

The documentation to the above eBay service is as under:
eBay Feed File - uploadFile documentation

Your cooperation in this context will be highly appreciated.


来源: stackexchange

问:
Making a call programmatically from iPhone app and returning back to the app after ending the call
I am trying to initiate a call from my iphone app,and I did it the following way..

```<code>-(IBAction) call:(id)sender
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Call Besito" message:@"\n\n\n"
                                                   delegate:self cancelButtonTitle:@"Cancel"  otherButtonTitles:@"Submit", nil];

    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex])
    {
      NSString *phone_number = @"0911234567"; // assing dynamically from your code
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString    stringWithFormat:@"tel:%@", phone_number]]];
         NSString *phone_number = @"09008934848";
        NSString *phoneStr = [[NSString alloc] initWithFormat:@"tel:%@",phone_number];
        NSURL *phoneURL = [[NSURL alloc] initWithString:phoneStr];
        [[UIApplication sharedApplication] openURL:phoneURL];
        [phoneURL release];
        [phoneStr release];
    }
}
</code>```

by the above code..I am able to successfully make a call..but when I end a call,I'm not able to return to my app

So, I want to know how to achieve,that..also please tell me how we can initiate a call using webview...

答: It's not possible to return back to the app after ending a call because it's an app.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to initiate a call from my iphone app,and I did it the following way..

-(IBAction) call:(id)sender
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Call Besito" message:@"\n\n\n"
                                                   delegate:self cancelButtonTitle:@"Cancel"  otherButtonTitles:@"Submit", nil];

    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex])
    {
      NSString *phone_number = @"0911234567"; // assing dynamically from your code
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString    stringWithFormat:@"tel:%@", phone_number]]];
         NSString *phone_number = @"09008934848";
        NSString *phoneStr = [[NSString alloc] initWithFormat:@"tel:%@",phone_number];
        NSURL *phoneURL = [[NSURL alloc] initWithString:phoneStr];
        [[UIApplication sharedApplication] openURL:phoneURL];
        [phoneURL release];
        [phoneStr release];
    }
}

by the above code..I am able to successfully make a call..but when I end a call,I'm not able to return to my app

So, I want to know how to achieve,that..also please tell me how we can initiate a call using webview...

ContentLicense: CC BY-SA 3.0


问:
How to give permissions to AKS to access ACR via terraform?

Question and details

How can I allow a Kubernetes cluster in Azure to  talk to an Azure Container Registry via terraform?

I want to load custom images from my Azure Container Registry. Unfortunately, I encounter a permissions error at the point where Kubernetes is supposed to download the image from the ACR.

What I have tried so far

My experiments without terraform (az cli)

It all works perfectly after I attach the acr to the aks via az cli:

az aks update -n myAKSCluster -g myResourceGroup --attach-acr <acrName>

My experiments with terraform

This is my terraform configuration; I have stripped some other stuff out. It works in itself.

```<code>terraform {
  backend "azurerm" {
    resource_group_name  = "tf-state"
    storage_account_name = "devopstfstate"
    container_name       = "tfstatetest"
    key                  = "prod.terraform.tfstatetest"
  }
}

provider "azurerm" {
}
provider "azuread" {
}
provider "random" {
}

# define the password
resource "random_string" "password" {
  length  = 32
  special = true
}

# define the resource group
resource "azurerm_resource_group" "rg" {
        name = "myrg"
        location = "eastus2"
}

# define the app
resource "azuread_application" "tfapp" {
  name                       = "mytfapp"
}

# define the service principal
resource "azuread_service_principal" "tfapp" {
  application_id = azuread_application.tfapp.application_id
}

# define the service principal password
resource "azuread_service_principal_password" "tfapp" {
  service_principal_id = azuread_service_principal.tfapp.id
  end_date = "2020-12-31T09:00:00Z"
  value = random_string.password.result
}

# define the container registry
resource "azurerm_container_registry" "acr" {
  name                     = "mycontainerregistry2387987222"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  sku                      = "Basic"
  admin_enabled            = false
}

# define the kubernetes cluster
resource "azurerm_kubernetes_cluster" "mycluster" {
  name                = "myaks"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  dns_prefix          = "mycluster"
  network_profile {
    network_plugin      = "azure"
  }

  default_node_pool {
    name       = "default"
    node_count = 1
    vm_size    = "Standard_B2s"
  }
  # Use the service principal created above
  service_principal {
    client_id     = azuread_service_principal.tfapp.application_id
    client_secret = azuread_service_principal_password.tfapp.value
  }
  tags = {
    Environment = "demo"
  }
  windows_profile {
    admin_username = "dingding"
    admin_password = random_string.password.result
  }
}

# define the windows node pool for kubernetes
resource "azurerm_kubernetes_cluster_node_pool" "winpool" {
  name                  = "winp"
  kubernetes_cluster_id = azurerm_kubernetes_cluster.mycluster.id
  vm_size               = "Standard_B2s"
  node_count            = 1
  os_type       = "Windows"
}

# define the kubernetes name space
resource "kubernetes_namespace" "namesp" {
  metadata {
    name = "namesp"
  }
}

# Try to give permissions, to let the AKR access the ACR
resource "azurerm_role_assignment" "acrpull_role" {
  scope                            = azurerm_container_registry.acr.id
  role_definition_name             = "AcrPull"
  principal_id                     = azuread_service_principal.tfapp.object_id
  skip_service_principal_aad_check = true
}
</code>```

This code is adapted from https://github.com/terraform-providers/terraform-provider-azuread/issues/104.

Unfortunately, when I launch a container inside the kubernetes cluster, I receive an error message:

```<code>Failed to pull image "mycontainerregistry.azurecr.io/myunittests": [rpc error: code = Unknown desc = Error response from daemon: manifest for mycontainerregistry.azurecr.io/myunittests:latest not found: manifest unknown: manifest unknown, rpc error: code = Unknown desc = Error response from daemon: Get https://mycontainerregistry.azurecr.io/v2/myunittests/manifests/latest: unauthorized: authentication required]
</code>```

Update / note:

When I run terraform apply with the above code, the creation of resources is interrupted:

```<code>azurerm_container_registry.acr: Creation complete after 18s [id=/subscriptions/000/resourceGroups/myrg/providers/Microsoft.ContainerRegistry/registries/mycontainerregistry2387987222]
azurerm_role_assignment.acrpull_role: Creating...
azuread_service_principal_password.tfapp: Still creating... [10s elapsed]
azuread_service_principal_password.tfapp: Creation complete after 12s [id=000/000]
azurerm_kubernetes_cluster.mycluster: Creating...
azurerm_role_assignment.acrpull_role: Creation complete after 8s [id=/subscriptions/000/resourceGroups/myrg/providers/Microsoft.ContainerRegistry/registries/mycontainerregistry2387987222/providers/Microsoft.Authorization/roleAssignments/000]
azurerm_kubernetes_cluster.mycluster: Still creating... [10s elapsed]

Error: Error creating Managed Kubernetes Cluster "myaks" (Resource Group "myrg"): containerservice.ManagedClustersClient#CreateOrUpdate: Failure sending request: StatusCode=400 -- Original Error: Code="ServicePrincipalNotFound" Message="Service principal clientID: 000 not found in Active Directory tenant 000, Please see https://aka.ms/aks-sp-help for more details."

  on test.tf line 56, in resource "azurerm_kubernetes_cluster" "mycluster":
  56: resource "azurerm_kubernetes_cluster" "mycluster" {
</code>```

I think, however, that this is just because it takes a few minutes for the service principal to be created. When I run terraform apply again a few minutes later, it goes beyond that point without issues.

答:
Just want to go into more depth as this was something I struggled with as-well.

The recommended approach is to use Managed Identities instead of Service Principal due to less overhead.

Create a Container Registry:

```<code> resource "azurerm_container_registry" "acr" {
  name                = "acr"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  sku                 = "Standard"
  admin_enabled       = false
}
</code>```

Create a AKS Cluster, the code below creates the AKS Cluster with 2 Identities:

A System Assigned Identity which is assigned to the Control Plane.

A User Assigned Managed Identity is also automatically created and assigned to the Kubelet, notice I have no specific code for that as it happens automatically.

The Kubelet is the process which goes to the Container Registry to pull the image, thus we need to make sure this User Assigned Managed Identity has the AcrPull Role on the Container Registry.

```<code>resource "azurerm_kubernetes_cluster" "aks" {
  name                = "aks"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  dns_prefix          = "aks"
  node_resource_group = "aks-node"

  default_node_pool {
    name                = "default"
    node_count          = 1
    vm_size             = "Standard_Ds2_v2"
    enable_auto_scaling = false
    type                = "VirtualMachineScaleSets"
    vnet_subnet_id      = azurerm_subnet.aks_subnet.id
    max_pods            = 50
  }

  network_profile {
    network_plugin    = "azure"
    load_balancer_sku = "Standard"
  }

  identity {
    type = "SystemAssigned"
  }
}
</code>```

Create Role Assignment mentioned above to allow the User Assigned Managed Identity to Pull from the Container Registry.

```<code>resource "azurerm_role_assignment" "ra" {
  principal_id                     =  azurerm_kubernetes_cluster.aks.kubelet_identity[0].object_id
  role_definition_name             = "AcrPull"
  scope                            = azurerm_container_registry.acr.id
  skip_service_principal_aad_check = true
}
</code>```

Hope that clears things up for you, as I have seen some confusion on the internet about the two identities created.

source: https://jimferrari.com/2022/02/09/attach-azure-container-registry-to-azure-kubernetes-service-terraform/

Body:
Question and details

How can I allow a Kubernetes cluster in Azure to  talk to an Azure Container Registry via terraform?

I want to load custom images from my Azure Container Registry. Unfortunately, I encounter a permissions error at the point where Kubernetes is supposed to download the image from the ACR.

What I have tried so far

My experiments without terraform (az cli)

It all works perfectly after I attach the acr to the aks via az cli:

az aks update -n myAKSCluster -g myResourceGroup --attach-acr <acrName>

My experiments with terraform

This is my terraform configuration; I have stripped some other stuff out. It works in itself.

terraform {
  backend "azurerm" {
    resource_group_name  = "tf-state"
    storage_account_name = "devopstfstate"
    container_name       = "tfstatetest"
    key                  = "prod.terraform.tfstatetest"
  }
}

provider "azurerm" {
}
provider "azuread" {
}
provider "random" {
}

# define the password
resource "random_string" "password" {
  length  = 32
  special = true
}

# define the resource group
resource "azurerm_resource_group" "rg" {
        name = "myrg"
        location = "eastus2"
}

# define the app
resource "azuread_application" "tfapp" {
  name                       = "mytfapp"
}

# define the service principal
resource "azuread_service_principal" "tfapp" {
  application_id = azuread_application.tfapp.application_id
}

# define the service principal password
resource "azuread_service_principal_password" "tfapp" {
  service_principal_id = azuread_service_principal.tfapp.id
  end_date = "2020-12-31T09:00:00Z"
  value = random_string.password.result
}

# define the container registry
resource "azurerm_container_registry" "acr" {
  name                     = "mycontainerregistry2387987222"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  sku                      = "Basic"
  admin_enabled            = false
}

# define the kubernetes cluster
resource "azurerm_kubernetes_cluster" "mycluster" {
  name                = "myaks"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  dns_prefix          = "mycluster"
  network_profile {
    network_plugin      = "azure"
  }

  default_node_pool {
    name       = "default"
    node_count = 1
    vm_size    = "Standard_B2s"
  }
  # Use the service principal created above
  service_principal {
    client_id     = azuread_service_principal.tfapp.application_id
    client_secret = azuread_service_principal_password.tfapp.value
  }
  tags = {
    Environment = "demo"
  }
  windows_profile {
    admin_username = "dingding"
    admin_password = random_string.password.result
  }
}

# define the windows node pool for kubernetes
resource "azurerm_kubernetes_cluster_node_pool" "winpool" {
  name                  = "winp"
  kubernetes_cluster_id = azurerm_kubernetes_cluster.mycluster.id
  vm_size               = "Standard_B2s"
  node_count            = 1
  os_type       = "Windows"
}

# define the kubernetes name space
resource "kubernetes_namespace" "namesp" {
  metadata {
    name = "namesp"
  }
}

# Try to give permissions, to let the AKR access the ACR
resource "azurerm_role_assignment" "acrpull_role" {
  scope                            = azurerm_container_registry.acr.id
  role_definition_name             = "AcrPull"
  principal_id                     = azuread_service_principal.tfapp.object_id
  skip_service_principal_aad_check = true
}

This code is adapted from https://github.com/terraform-providers/terraform-provider-azuread/issues/104.

Unfortunately, when I launch a container inside the kubernetes cluster, I receive an error message:

Failed to pull image "mycontainerregistry.azurecr.io/myunittests": [rpc error: code = Unknown desc = Error response from daemon: manifest for mycontainerregistry.azurecr.io/myunittests:latest not found: manifest unknown: manifest unknown, rpc error: code = Unknown desc = Error response from daemon: Get https://mycontainerregistry.azurecr.io/v2/myunittests/manifests/latest: unauthorized: authentication required]

Update / note:

When I run terraform apply with the above code, the creation of resources is interrupted:

azurerm_container_registry.acr: Creation complete after 18s [id=/subscriptions/000/resourceGroups/myrg/providers/Microsoft.ContainerRegistry/registries/mycontainerregistry2387987222]
azurerm_role_assignment.acrpull_role: Creating...
azuread_service_principal_password.tfapp: Still creating... [10s elapsed]
azuread_service_principal_password.tfapp: Creation complete after 12s [id=000/000]
azurerm_kubernetes_cluster.mycluster: Creating...
azurerm_role_assignment.acrpull_role: Creation complete after 8s [id=/subscriptions/000/resourceGroups/myrg/providers/Microsoft.ContainerRegistry/registries/mycontainerregistry2387987222/providers/Microsoft.Authorization/roleAssignments/000]
azurerm_kubernetes_cluster.mycluster: Still creating... [10s elapsed]

Error: Error creating Managed Kubernetes Cluster "myaks" (Resource Group "myrg"): containerservice.ManagedClustersClient#CreateOrUpdate: Failure sending request: StatusCode=400 -- Original Error: Code="ServicePrincipalNotFound" Message="Service principal clientID: 000 not found in Active Directory tenant 000, Please see https://aka.ms/aks-sp-help for more details."

  on test.tf line 56, in resource "azurerm_kubernetes_cluster" "mycluster":
  56: resource "azurerm_kubernetes_cluster" "mycluster" {

I think, however, that this is just because it takes a few minutes for the service principal to be created. When I run terraform apply again a few minutes later, it goes beyond that point without issues.

Body:
Just want to go into more depth as this was something I struggled with as-well.

The recommended approach is to use Managed Identities instead of Service Principal due to less overhead.

Create a Container Registry:

 resource "azurerm_container_registry" "acr" {
  name                = "acr"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  sku                 = "Standard"
  admin_enabled       = false
}

Create a AKS Cluster, the code below creates the AKS Cluster with 2 Identities:

A System Assigned Identity which is assigned to the Control Plane.

A User Assigned Managed Identity is also automatically created and assigned to the Kubelet, notice I have no specific code for that as it happens automatically.

The Kubelet is the process which goes to the Container Registry to pull the image, thus we need to make sure this User Assigned Managed Identity has the AcrPull Role on the Container Registry.

resource "azurerm_kubernetes_cluster" "aks" {
  name                = "aks"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  dns_prefix          = "aks"
  node_resource_group = "aks-node"

  default_node_pool {
    name                = "default"
    node_count          = 1
    vm_size             = "Standard_Ds2_v2"
    enable_auto_scaling = false
    type                = "VirtualMachineScaleSets"
    vnet_subnet_id      = azurerm_subnet.aks_subnet.id
    max_pods            = 50
  }

  network_profile {
    network_plugin    = "azure"
    load_balancer_sku = "Standard"
  }

  identity {
    type = "SystemAssigned"
  }
}

Create Role Assignment mentioned above to allow the User Assigned Managed Identity to Pull from the Container Registry.

resource "azurerm_role_assignment" "ra" {
  principal_id                     =  azurerm_kubernetes_cluster.aks.kubelet_identity[0].object_id
  role_definition_name             = "AcrPull"
  scope                            = azurerm_container_registry.acr.id
  skip_service_principal_aad_check = true
}

Hope that clears things up for you, as I have seen some confusion on the internet about the two identities created.

source: https://jimferrari.com/2022/02/09/attach-azure-container-registry-to-azure-kubernetes-service-terraform/


问:
How to add instagram feed to website in 2022?
I would like to show the last 8 images from my Instagram profile on my website.

I've just spent the last hour looking for info on this but can't find anything recent information anywhere. I can't believe something as simple as showing my latest posts can be so complicated!

I have custom built our site using HTML, PHP and jquery. I'm not interested in paid 3rd party software and Wordpress/Shopify plugins aren't relevant to me.

答:
I'm in the same situation if it can reassure you!

Indeed according to my research I think that Instagram have put their APIs on hold because of the Metaverse and the takeover by Facebook etc...
So it is currently impossible to display our instagram news feed on our sites, whether in PHP or JS...

It's quite compelling...


问:
restart policy in Kubernetes deployment
Is it possible to create a deployment on Kubernetes and using restart policy on failure ?
I did a small research but didn't find anything that enables restart policy on failure for Deployment.

KR

答:
restartPolicy for kind: Deployment support Always only.

One of the requirements is "restart policy on failure max 3 times"

Try:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: busybox
spec:
  template:
    backoffLimit: 3  # <-- max fail 3 times
    spec:
      restartPolicy: OnFailure  # <-- You can do this with job
      containers:
      - name: busybox
        image: busybox
        command: ["ash","-c","sleep 15"]  # <-- replace with an invalid command to see backoffLimit in action
</code>```

Title: restart policy in Kubernetes deployment

Body:
restartPolicy for kind: Deployment support Always only.

One of the requirements is "restart policy on failure max 3 times"

Try:

apiVersion: batch/v1
kind: Job
metadata:
  name: busybox
spec:
  template:
    backoffLimit: 3  # <-- max fail 3 times
    spec:
      restartPolicy: OnFailure  # <-- You can do this with job
      containers:
      - name: busybox
        image: busybox
        command: ["ash","-c","sleep 15"]  # <-- replace with an invalid command to see backoffLimit in action


问:
No such file or directory: 'arm-none-eabi-gcc' error trying to make micropython for STM32
I am following the documentation for building micropython

```<code>cd mpy-cross
make
</code>```

And then installed the GNU Arm Embedded Toolchain as I am using a Mac with OSX. Then I proceeded to

```<code>cd ../ports/stm32
make submodules
make
</code>```

and got the error

```<code>Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity.
mkdir -p build-PYBV10/genhdr
GEN build-PYBV10/genhdr/pins.h
GEN stmconst build-PYBV10/modstm_qstr.h
GEN build-PYBV10/genhdr/pybcdc.inf
GEN build-PYBV10/genhdr/pybcdc_inf.h
GEN build-PYBV10/genhdr/pllfreqtable.h
GEN build-PYBV10/genhdr/mpversion.h
GEN build-PYBV10/genhdr/moduledefs.h
GEN build-PYBV10/genhdr/qstr.i.last
Traceback (most recent call last):
  File "../../py/makeqstrdefs.py", line 188, in <module>
    preprocess()
  File "../../py/makeqstrdefs.py", line 62, in preprocess
    for output in p.imap(pp(flags), chunks):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/multiprocessing/pool.py", line 748, in next
    raise value
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/multiprocessing/pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "../../py/makeqstrdefs.py", line 46, in run
    return subprocess.check_output(args.pp + flags + files)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1522, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'arm-none-eabi-gcc': 'arm-none-eabi-gcc'
make: *** [build-PYBV10/genhdr/qstr.i.last] Error 1
make: *** Deleting file `build-PYBV10/genhdr/qstr.i.last'
</code>```

I've looked at the docs for the GNU Arm Embedded Toolchain, but it doesn't appear that I missed a step. What am I missing?

答:
For some reason the installer did not put the binaries in my path. I fixed this with

```<code>export PATH="/Applications/ARM/bin:$PATH"
</code>```

and then was able to run make without error.

Body:
I am following the documentation for building micropython

cd mpy-cross
make

And then installed the GNU Arm Embedded Toolchain as I am using a Mac with OSX. Then I proceeded to

cd ../ports/stm32
make submodules
make

and got the error

Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity.
mkdir -p build-PYBV10/genhdr
GEN build-PYBV10/genhdr/pins.h
GEN stmconst build-PYBV10/modstm_qstr.h
GEN build-PYBV10/genhdr/pybcdc.inf
GEN build-PYBV10/genhdr/pybcdc_inf.h
GEN build-PYBV10/genhdr/pllfreqtable.h
GEN build-PYBV10/genhdr/mpversion.h
GEN build-PYBV10/genhdr/moduledefs.h
GEN build-PYBV10/genhdr/qstr.i.last
Traceback (most recent call last):
  File "../../py/makeqstrdefs.py", line 188, in <module>
    preprocess()
  File "../../py/makeqstrdefs.py", line 62, in preprocess
    for output in p.imap(pp(flags), chunks):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/multiprocessing/pool.py", line 748, in next
    raise value
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/multiprocessing/pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "../../py/makeqstrdefs.py", line 46, in run
    return subprocess.check_output(args.pp + flags + files)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 395, in check_output
    **kwargs).stdout
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1522, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'arm-none-eabi-gcc': 'arm-none-eabi-gcc'
make: *** [build-PYBV10/genhdr/qstr.i.last] Error 1
make: *** Deleting file `build-PYBV10/genhdr/qstr.i.last'

I've looked at the docs for the GNU Arm Embedded Toolchain, but it doesn't appear that I missed a step. What am I missing?

Body:
For some reason the installer did not put the binaries in my path. I fixed this with

export PATH="/Applications/ARM/bin:$PATH"

and then was able to run make without error.


问:
How can I write a where clause in SQL to filter a DATETIME column by the time of day?
I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day.  What's the best way to do this?

UPDATE: Changed because I need precision to the minute, not just hour.  Sorry about that.

答:
Concatenate hour and minutes and compare the range.</p>

```<code>with Result as (
    select  [Time] = cast(cast(datepart(hh, AuditDate) as varchar) +
            cast(datepart(mi, AuditDate) as varchar) as int), *
    from    AuditTable
)
select  *
from    Result
where   [Time] between 930 and 1730
</code>```

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milen A. Radev

Body:
Concatenate hour and minutes and compare the range.

with Result as (
    select  [Time] = cast(cast(datepart(hh, AuditDate) as varchar) +
            cast(datepart(mi, AuditDate) as varchar) as int), *
    from    AuditTable
)
select  *
from    Result
where   [Time] between 930 and 1730

OwnerDisplayName: Sung Meister

LastEditorDisplayName: Sung Meister


问:
How to Iterate dictionary in React Typescript
I am learning react with typescript. I have one dictionary of the department in which employees data of department is stored in the form of an array.

```<code>type Department = {
    Emp_Id: number,
    Name: string,
    Age: number
}

let dict: {[DepartmentNo: number]: Department[] } = {};

dict[0] = [   {Emp_Id: 1, Name:"Test", Age: 23},
            {Emp_Id: 2, Name:"Test", Age: 23},
            {Emp_Id: 3, Name:"Test", Age: 23}
        ];

dict[1] = [  {Emp_Id: 1, Name:"Test 2", Age: 23},
           {Emp_Id: 2, Name:"Test 3", Age: 23},
           {Emp_Id: 3, Name:"Test 4", Age: 23}
        ];

dict[2] = [  {Emp_Id: 1, Name:"Test 2", Age: 23},
           {Emp_Id: 2, Name:"Test 3", Age: 23}
     ];
</code>```

I created a function that will return me an unordered list.

```<code>const printDepartment = () => {
     // getting error in map argument: department
    Object.entries(dict).map((department: Department) => {
        let count = 0;
     // here also saying condition will always return true
      if(dict[count] != 2){
          return (<ul>
              <li>{department.Emp_Id}</li>
              <li>{department.Name}</li>
          </ul>)
      }
    })
}

</code>```

in my return I am simply calling this function:

```<code><div>
      {
          printDepartment()
      }
  </div>
</code>```

答:
The type of keys on your dict will always be string. If you change that, the types in the Array.map element will be correctly inferred as [string, Department[]].

```<code>type Department = {
  Emp_Id: number;
  Name: string;
  Age: number;
};

let dict: { [DepartmentNo: string]: Department[] } = {};

dict[0] = [
  { Emp_Id: 1, Name: "Test", Age: 23 },
  { Emp_Id: 2, Name: "Test", Age: 23 },
  { Emp_Id: 3, Name: "Test", Age: 23 },
];

dict[1] = [
  { Emp_Id: 1, Name: "Test 2", Age: 23 },
  { Emp_Id: 2, Name: "Test 3", Age: 23 },
  { Emp_Id: 3, Name: "Test 4", Age: 23 },
];

dict[2] = [
  { Emp_Id: 1, Name: "Test 2", Age: 23 },
  { Emp_Id: 2, Name: "Test 3", Age: 23 },
];

const printDepartment = () => {
  Object.entries(dict).map((entry) => { // [string, Department[]]
    console.log({ key: entry[0], value: entry[1] });
  });
};

printDepartment();

</code>```

demo

Body:
I am learning react with typescript. I have one dictionary of the department in which employees data of department is stored in the form of an array.

type Department = {
    Emp_Id: number,
    Name: string,
    Age: number
}

let dict: {[DepartmentNo: number]: Department[] } = {};

dict[0] = [   {Emp_Id: 1, Name:"Test", Age: 23},
            {Emp_Id: 2, Name:"Test", Age: 23},
            {Emp_Id: 3, Name:"Test", Age: 23}
        ];

dict[1] = [  {Emp_Id: 1, Name:"Test 2", Age: 23},
           {Emp_Id: 2, Name:"Test 3", Age: 23},
           {Emp_Id: 3, Name:"Test 4", Age: 23}
        ];

dict[2] = [  {Emp_Id: 1, Name:"Test 2", Age: 23},
           {Emp_Id: 2, Name:"Test 3", Age: 23}
     ];

I created a function that will return me an unordered list.

const printDepartment = () => {
     // getting error in map argument: department
    Object.entries(dict).map((department: Department) => {
        let count = 0;
     // here also saying condition will always return true
      if(dict[count] != 2){
          return (

{department.Emp_Id}

{department.Name}

)
      }
    })
}

in my return I am simply calling this function:

      {
          printDepartment()
      }

Body:
The type of keys on your dict will always be string. If you change that, the types in the Array.map element will be correctly inferred as [string, Department[]].

type Department = {
  Emp_Id: number;
  Name: string;
  Age: number;
};

let dict: { [DepartmentNo: string]: Department[] } = {};

dict[0] = [
  { Emp_Id: 1, Name: "Test", Age: 23 },
  { Emp_Id: 2, Name: "Test", Age: 23 },
  { Emp_Id: 3, Name: "Test", Age: 23 },
];

dict[1] = [
  { Emp_Id: 1, Name: "Test 2", Age: 23 },
  { Emp_Id: 2, Name: "Test 3", Age: 23 },
  { Emp_Id: 3, Name: "Test 4", Age: 23 },
];

dict[2] = [
  { Emp_Id: 1, Name: "Test 2", Age: 23 },
  { Emp_Id: 2, Name: "Test 3", Age: 23 },
];

const printDepartment = () => {
  Object.entries(dict).map((entry) => { // [string, Department[]]
    console.log({ key: entry[0], value: entry[1] });
  });
};

printDepartment();

<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAIhYEMBOwC2EB2woF4oG8AoKKAUVTAH0BJAEwC4oMBXVAIwiQG5ioA5BOkYBnYEgCWGAOY8SAQSkRGLdpx4BfHoQA2EbLXEBjYI3xQA2nEQp0WPgHsRYyVIC6jK8jSZg511HVcAk1CQgNjcwAGfzxzXjNyKjpGAEYAGn5BJSgAIgAVCFEcjIVsgCYAZgC0%20LIKGgYoMoyBIVyCopLFRkrq2sSGxgqWrMZ8wuBiqFKeqvUa1y1w3xSYi3765Kh0zLbx0Sapmaa5mpIEzcbm3ez97Aqj7pO%2087qkxuGbsY7sABZH8qnQiLULLcxlNZxV4DLY7Vq3H6HLqAl4EN6DJojPaIh7I2Z9EGEQz2DAHMASLCeGw%20IIACgAlLgAHwEXgkADybAAVhBjAA6HwSQq05b0vmoBBgWm08wAawgIAyADcENpmBBXIycCyiCQ9XriaT7Lo%20dp7FJafh5YqoCq1RB1PS2QEnepQuTJMAqd4sAygA" rel="nofollow noreferrer">demo


问:
With MS Graph API, how do I force my programmatically created Service Principals, MSIs, and IaC code to be scoped to my subscription only?
Active Directory Graph API is now fully deprecated, in favor of MS Graph API.

My company has given me my own Visual Studio Professional subscription. I also have a DevOps organization. I am the Owner role in both.

with AADG API, I could use Terraform, for example, to create Service Principals and manage roles. Service Connections in DevOps were scoped to my subscription.

Example:

```<code>## These are in my resource group
...
resource "azuread_service_principal" "example" {
  application_id               = azuread_application.example.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.current.object_id]
}

...

resource "azurerm_role_assignment" "kubweb_to_acr" {
  scope                = azurerm_container_registry.acr.id
  role_definition_name = "AcrPull"
  principal_id         = azurerm_kubernetes_cluster.kubweb.kubelet_identity[0].object_id
}
</code>```

This used to work great. Now it does not. Now I get errors like:

```<code>Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client '3520c717-e1cc-4d0b-b021-2f93a1b05d80' with object id '3520c717-e1cc-4d0b-b021-2f93a1b05d80' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write
</code>```

and

```<code>ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData
│ error: Authorization_RequestDenied: Insufficient privileges to complete the
│ operation.
</code>```

Even though I own my subscription, there is a parent organization above me. My SPs get scoped to their AD where I can't manage them. I can't use "Grant Admin Consent" through MS Graph API. Also, in DevOps, when I create an ARM Service Connection, for example, I scope it to my Subscription. It never scopes to my subscription, but the parent's, and I can't change its permissions.

How do I alter my development or scope my resources so that I don't have to defer to parent organization?

What role do they need to give me so I don't have to involve them?

I'm already the owner of my subscription. How do I create these types of resources in a way that I have full control over managing them again?

Side-note, it's interesting. I can use Azure CLI and run the same commands via terminal, and I have no problems creating or altering resources. The same commands az ad sp create-for-rbac don't throw any errors at all, and it's using the same permissions and scope defined in the pipelines.

答:
Both errors you show are due to the service principal that Terraform is running as has not been authorized to perform the action in question. (From the Azure role assignment error, we can know this is the service principal with object ID "3520c717-e1cc-4d0b-b021-2f93a1b05d80".)

To assign an Azure role to a user, group, or service principal (your first error), the service principal used by Terraform needs to be have been granted a role that includes the "Microsoft.Authorization/roleAssignments/write" operation, scoped to (at least) scope you're trying to grant the role at (e.g. the specific Azure resource, the resource group it's in, or the subscription it's in). Typically, if you need to create Azure role assignments, this is the "Owner" role. More details from Terraform in Allowing the Service Principal to manage the Subscription. If you're "Owner" of the Azure subscription, then you will be able to do this yourself.

To create Azure AD application and service principals (your second error): The service principal used by Terraform needs to be granted permission to do this in the Azure AD tenant in question. For example, the app roles (application permissions) Application.Read.All and Application.ReadWrite.OwnedBy would suffice in many cases. These are actions that take place in the Azure AD tenant, so an Azure AD administrator will need to grant this access—you cannot do this on your own if you're not an admin of the Azure AD tenant. More details from Terraform in Configuring a User or Service Principal for managing Azure Active Directory.

How do I alter my development or scope my resources so that I don't have to defer to parent organization?

You could have an entirely separate Azure AD tenant (where you'd be administrator), and point the Azure subscription to trust that tenant. This may or may not be compatible with your organization's policies and practices.

I'm already the owner of my subscription. How do I create these types of resources in a way that I have full control over managing them again?

Azure AD applications and service principals are not a part of your Azure subscription, they're in the "parent" Azure AD tenant. You (the user) probably do have permission over these objects (e.g. you're owner of them in Azure AD), but Terraform isn't running as you—it's running as a separate service principal.

Side-note, it's interesting. I can use Azure CLI and run the same commands via terminal, and I have no problems creating or altering resources. The same commands az ad sp create-for-rbac don't throw any errors at all, and it's using the same permissions and scope defined in the pipelines.

You're probably connecting to Azure CLI as yourself (i.e. your user account), instead of the service principal Terraform is using. If you connect to Azure CLI using the same service principal (e.g. az login --service-principal ...), you'd likely experience the same errors, because that service principal hasn't been granted privileges over the Azure AD tenant and the Azure subscription yet.

Body:
Active Directory Graph API is now fully deprecated, in favor of MS Graph API.

My company has given me my own Visual Studio Professional subscription. I also have a DevOps organization. I am the Owner role in both.

with AADG API, I could use Terraform, for example, to create Service Principals and manage roles. Service Connections in DevOps were scoped to my subscription.

Example:

## These are in my resource group
...
resource "azuread_service_principal" "example" {
  application_id               = azuread_application.example.application_id
  app_role_assignment_required = false
  owners                       = [data.azuread_client_config.current.object_id]
}

...

resource "azurerm_role_assignment" "kubweb_to_acr" {
  scope                = azurerm_container_registry.acr.id
  role_definition_name = "AcrPull"
  principal_id         = azurerm_kubernetes_cluster.kubweb.kubelet_identity[0].object_id
}

This used to work great. Now it does not. Now I get errors like:

Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=403 -- Original Error: autorest/azure: Service returned an error. Status=403 Code="AuthorizationFailed" Message="The client '3520c717-e1cc-4d0b-b021-2f93a1b05d80' with object id '3520c717-e1cc-4d0b-b021-2f93a1b05d80' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write

and

ApplicationsClient.BaseClient.Post(): unexpected status 403 with OData
│ error: Authorization_RequestDenied: Insufficient privileges to complete the
│ operation.

Even though I own my subscription, there is a parent organization above me. My SPs get scoped to their AD where I can't manage them. I can't use "Grant Admin Consent" through MS Graph API. Also, in DevOps, when I create an ARM Service Connection, for example, I scope it to my Subscription. It never scopes to my subscription, but the parent's, and I can't change its permissions.

How do I alter my development or scope my resources so that I don't have to defer to parent organization?

What role do they need to give me so I don't have to involve them?

I'm already the owner of my subscription. How do I create these types of resources in a way that I have full control over managing them again?

Side-note, it's interesting. I can use Azure CLI and run the same commands via terminal, and I have no problems creating or altering resources. The same commands az ad sp create-for-rbac don't throw any errors at all, and it's using the same permissions and scope defined in the pipelines.


问:
VBA Excel: Add one second to a time
I'm working with a spreadsheet with two columns, in which one of the columns is a time. I have loaded the data into a dictionary using the time as a key. I want to look up the data corresponding to a particular time (easy), and then get the next data point so that I can compare their values. The data is recorded such that one piece of data is generated every second over a period of around two hours.

My question is, does VBA in Excel have a function which can automatically add one second to a time? Or do I need to manually write one?

Update: In addition to the answers below, I have also found the "DateAdd" function useful - I suspect it depends on the version of Excel being used.

答: you can use TimeValue("00:00:01") for adding in this example 1 second</p>

Title: VBA Excel: Add one second to a time


问:
Is there a way to use a map function inside another map function?
I need to "traduce" the value inside a RDD using the value in another RDD
Something like this:

```<code>rdd1=sc.parallelize(['aa,bb','cc,dd','ee,aa'])
rdd2=sc.parallelize(['aa,1' , 'bb,2' , 'cc,3' , 'dd,4' , 'ee,5'])
result: ['1,2', '3,4' , '5,1']
</code>```

I've tried to use the following map function

```<code>      def mymap (c):
          src=c[0]
          dst=c[2]
          srcnew=rdd2.lookup(src)[0]
          dstnew=rdd2.lookup(dst)[0]
          return (srcnew,dstnew)

    rdd3=rdd1.map(mymap)
</code>```

But i get the following error:

It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.

The only solution i came up to is to use the collect() command but my dataset is huge. There is a way to call the value in a RDD in another RDD?

答:
You should be able to accomplish this with some simple joins and maps. Note rdd1 and rdd2 below have been adjusted with a map function so the entries are available as arrays.

rdd1=sc.parallelize(['aa,bb','cc,dd','ee,ff']) \
.map(lambda x: x.split(','))
rdd2=sc.parallelize(['aa,1','bb,2','cc,3','dd,4','ee,5','ff,6']) \
.map(lambda x: x.split(','))

rdd3 = rdd1 \
.join(rdd2) \
.map(lambda x: x[1]) \
.join(rdd2) \
.map(lambda x: x[1]) \
.map(lambda x: ','.join(x))

rdd3.foreach(print)

# outputs
# 1,2
# 3,4
# 5,6
```

The above will

join the rdds to resolve the first entry in rdd1 giving

[('aa', ('bb', '1')), ('cc', ('dd', '3')), ('ee', ('ff', '5'))]

map the above rdd to just be the values from the join giving

[('bb', '1'), ('dd', '3'), ('ff', '5')]

join with rdd2 again to resolve the second entry oringinally from rdd1 giving

[('bb', ('1', '2')), ('dd', ('3', '4')), ('ff', ('5', '6'))]

again, map the above rdd to just be the values from the join giving

[('1', '2'), ('3', '4'), ('5', '6')]

map the tuples to strings, joining on , giving

['1,2', '3,4', '5,6']

Steps 4 and 5 can obviously combined as lambda x : ','.join(x[1]) - I've kept them separate above for clarity

For a more complex example where you need to preserve an initial key see this answer

Body:
I need to "traduce" the value inside a RDD using the value in another RDD
Something like this:

rdd1=sc.parallelize(['aa,bb','cc,dd','ee,aa'])
rdd2=sc.parallelize(['aa,1' , 'bb,2' , 'cc,3' , 'dd,4' , 'ee,5'])
result: ['1,2', '3,4' , '5,1']

I've tried to use the following map function

      def mymap (c):
          src=c[0]
          dst=c[2]
          srcnew=rdd2.lookup(src)[0]
          dstnew=rdd2.lookup(dst)[0]
          return (srcnew,dstnew)

    rdd3=rdd1.map(mymap)

But i get the following error:

It appears that you are attempting to broadcast an RDD or reference an RDD from an action or transformation. RDD transformations and actions can only be invoked by the driver, not inside of other transformations; for example, rdd1.map(lambda x: rdd2.values.count() * x) is invalid because the values transformation and count action cannot be performed inside of the rdd1.map transformation. For more information, see SPARK-5063.

The only solution i came up to is to use the collect() command but my dataset is huge. There is a way to call the value in a RDD in another RDD?

Body:
You should be able to accomplish this with some simple joins and maps. Note rdd1 and rdd2 below have been adjusted with a map function so the entries are available as arrays.

rdd1=sc.parallelize(['aa,bb','cc,dd','ee,ff']) \
.map(lambda x: x.split(','))
rdd2=sc.parallelize(['aa,1','bb,2','cc,3','dd,4','ee,5','ff,6']) \
.map(lambda x: x.split(','))

rdd3 = rdd1 \
.join(rdd2) \
.map(lambda x: x[1]) \
.join(rdd2) \
.map(lambda x: x[1]) \
.map(lambda x: ','.join(x))

rdd3.foreach(print)

# outputs
# 1,2
# 3,4
# 5,6

The above will

join the rdds to resolve the first entry in rdd1 giving

[('aa', ('bb', '1')), ('cc', ('dd', '3')), ('ee', ('ff', '5'))]

map the above rdd to just be the values from the join giving

[('bb', '1'), ('dd', '3'), ('ff', '5')]

join with rdd2 again to resolve the second entry oringinally from rdd1 giving

[('bb', ('1', '2')), ('dd', ('3', '4')), ('ff', ('5', '6'))]

again, map the above rdd to just be the values from the join giving

[('1', '2'), ('3', '4'), ('5', '6')]

map the tuples to strings, joining on , giving

['1,2', '3,4', '5,6']

Steps 4 and 5 can obviously combined as lambda x : ','.join(x[1]) - I've kept them separate above for clarity

For a more complex example where you need to preserve an initial key see this answer


问:
dense_rank function error and not able to proceed further
I have used below query in Fiddle application for learning purpose but its throwing error:

```<code>with result as
(
  select salary, dense_rank() over (order by salary desc) as 'dense_rank'
  from salary
)
select salary from result where result.denserank = 3
</code>```

Error:

You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '(order by salary desc) as 'DENSE_RANK' from salary' at line 1

What to do further.? Also is Mysql and postgreSql same

答:
Apparently you're using a MySQL version that supports CTEs but does not support Window functions. MySQL 8.0.1 is such version (8.0.1 introduces CTEs for the first time and 8.0.2 introduces window functions).

You need to use a more recent version of MySQL and (ii) change where result.denserank = 3 to where result.dense_rank = 3.

Body:
I have used below query in Fiddle application for learning purpose but its throwing error:

with result as
(
  select salary, dense_rank() over (order by salary desc) as 'dense_rank'
  from salary
)
select salary from result where result.denserank = 3

Error:

You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '(order by salary desc) as 'DENSE_RANK' from salary' at line 1

What to do further.? Also is Mysql and postgreSql same


问:
How to select elements that need to scroll down to load?
I've been scraping some websites in Python for practice and notice that when I need to select a set of elements on a scrollable area, I will only get a few instead of all the elements and I will only get them all if I scroll down for them to load. Here's an example:

```<code>from bs4 import BeautifulSoup
import requests

Zillow_URL = "https://www.zillow.com/homes/for_rent/1-_beds/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22usersSearchTerm%22%3Anull%2C%22mapBounds%22%3A%7B%22west%22%3A-122.56276167822266%2C%22east%22%3A-122.30389632177734%2C%22south%22%3A37.69261345230467%2C%22north%22%3A37.857877098316834%7D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22fr%22%3A%7B%22value%22%3Atrue%7D%2C%22fsba%22%3A%7B%22value%22%3Afalse%7D%2C%22fsbo%22%3A%7B%22value%22%3Afalse%7D%2C%22nc%22%3A%7B%22value%22%3Afalse%7D%2C%22cmsn%22%3A%7B%22value%22%3Afalse%7D%2C%22auc%22%3A%7B%22value%22%3Afalse%7D%2C%22fore%22%3A%7B%22value%22%3Afalse%7D%2C%22pmf%22%3A%7B%22value%22%3Afalse%7D%2C%22pf%22%3A%7B%22value%22%3Afalse%7D%2C%22mp%22%3A%7B%22max%22%3A3000%7D%2C%22price%22%3A%7B%22max%22%3A872627%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A12%7D"

HEADERS = {...} # Im not sure if I should put my browser info to public

response = requests.get(url=Zillow_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")

prices = soup.select("div.list-card-price")
print(prices, len(prices))
</code>```

The only solution I can think of is to use a webdriver to scroll down and get the elements but that seems inefficient. Is there a way to achieve this without having to scroll down?

答:
Not sure if this will help but you can actually pull the data as JSON from the below query.</p>
```<code>import requests
import json
from bs4 import BeautifulSoup as bs

headers = {
'authority': 'www.zillow.com',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "GoogleChrome";v="98"',
'dnt': '1',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36',
'sec-ch-ua-platform': '"Windows"',
'accept': '*/*',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'sec-gpc': '1',
}

response = requests.get('https://www.zillow.com/search/GetSearchPageState.htm?searchQueryState=%7B%22pagination%22%3A%7B%22currentPage%22%3A1%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-122.35259056091309%2C%22east%22%3A-122.15174674987793%2C%22south%22%3A37.79133717593069%2C%22north%22%3A37.84707034351907%7D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22price%22%3A%7B%22min%22%3A0%2C%22max%22%3A872627%7D%2C%22monthlyPayment%22%3A%7B%22min%22%3A0%2C%22max%22%3A3000%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%2C%22isForSaleByAgent%22%3A%7B%22value%22%3Afalse%7D%2C%22isForSaleByOwner%22%3A%7B%22value%22%3Afalse%7D%2C%22isNewConstruction%22%3A%7B%22value%22%3Afalse%7D%2C%22isForSaleForeclosure%22%3A%7B%22value%22%3Afalse%7D%2C%22isComingSoon%22%3A%7B%22value%22%3Afalse%7D%2C%22isAuction%22%3A%7B%22value%22%3Afalse%7D%2C%22isForRent%22%3A%7B%22value%22%3Atrue%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A13%7D&wants={%22cat1%22:[%22listResults%22,%22mapResults%22]}', headers=headers)
soup = bs(response.text, 'lxml')

json_file = json.loads(soup.select_one('p').text.strip())
firms = [i for i in json_file['cat1']['searchResults']['mapResults']]
</code>```

Body:
I've been scraping some websites in Python for practice and notice that when I need to select a set of elements on a scrollable area, I will only get a few instead of all the elements and I will only get them all if I scroll down for them to load. Here's an example:

from bs4 import BeautifulSoup
import requests

Zillow_URL = "https://www.zillow.com/homes/for_rent/1-_beds/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22usersSearchTerm%22%3Anull%2C%22mapBounds%22%3A%7B%22west%22%3A-122.56276167822266%2C%22east%22%3A-122.30389632177734%2C%22south%22%3A37.69261345230467%2C%22north%22%3A37.857877098316834%7D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22fr%22%3A%7B%22value%22%3Atrue%7D%2C%22fsba%22%3A%7B%22value%22%3Afalse%7D%2C%22fsbo%22%3A%7B%22value%22%3Afalse%7D%2C%22nc%22%3A%7B%22value%22%3Afalse%7D%2C%22cmsn%22%3A%7B%22value%22%3Afalse%7D%2C%22auc%22%3A%7B%22value%22%3Afalse%7D%2C%22fore%22%3A%7B%22value%22%3Afalse%7D%2C%22pmf%22%3A%7B%22value%22%3Afalse%7D%2C%22pf%22%3A%7B%22value%22%3Afalse%7D%2C%22mp%22%3A%7B%22max%22%3A3000%7D%2C%22price%22%3A%7B%22max%22%3A872627%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A12%7D"

HEADERS = {...} # Im not sure if I should put my browser info to public

response = requests.get(url=Zillow_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")

prices = soup.select("div.list-card-price")
print(prices, len(prices))

The only solution I can think of is to use a webdriver to scroll down and get the elements but that seems inefficient. Is there a way to achieve this without having to scroll down?

Body:
Not sure if this will help but you can actually pull the data as JSON from the below query.

import requests
import json
from bs4 import BeautifulSoup as bs

headers = {
'authority': 'www.zillow.com',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "GoogleChrome";v="98"',
'dnt': '1',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36',
'sec-ch-ua-platform': '"Windows"',
'accept': '*/*',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
'sec-gpc': '1',
}

response = requests.get('https://www.zillow.com/search/GetSearchPageState.htm?searchQueryState=%7B%22pagination%22%3A%7B%22currentPage%22%3A1%7D%2C%22mapBounds%22%3A%7B%22west%22%3A-122.35259056091309%2C%22east%22%3A-122.15174674987793%2C%22south%22%3A37.79133717593069%2C%22north%22%3A37.84707034351907%7D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22price%22%3A%7B%22min%22%3A0%2C%22max%22%3A872627%7D%2C%22monthlyPayment%22%3A%7B%22min%22%3A0%2C%22max%22%3A3000%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%2C%22isForSaleByAgent%22%3A%7B%22value%22%3Afalse%7D%2C%22isForSaleByOwner%22%3A%7B%22value%22%3Afalse%7D%2C%22isNewConstruction%22%3A%7B%22value%22%3Afalse%7D%2C%22isForSaleForeclosure%22%3A%7B%22value%22%3Afalse%7D%2C%22isComingSoon%22%3A%7B%22value%22%3Afalse%7D%2C%22isAuction%22%3A%7B%22value%22%3Afalse%7D%2C%22isForRent%22%3A%7B%22value%22%3Atrue%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A13%7D&wants={%22cat1%22:[%22listResults%22,%22mapResults%22]}', headers=headers)
soup = bs(response.text, 'lxml')

json_file = json.loads(soup.select_one('p').text.strip())
firms = [i for i in json_file['cat1']['searchResults']['mapResults']]


问:
Filtering rows based on specific values: Pandas
I have the following dataframe.

```<code>ID Value1  Value2  Value3  Value4  Value5
1   0        0       50      100     0
2   0        0       0        0      0
3   0        0       0        50     0
4   0        100     0        0      0
5   50        0      100      50     50
</code>```

I would like to filter IDs which has only one non-zero values. For example ID == 1 has two non-zero values but ID == 3 and 4 has only one non-zero values and I would like to filter them.

The expected output is ID 3 and 4.

```<code>ID Value1  Value2  Value3  Value4  Value5
3   0        0       0        50     0
4   0        100     0        0      0
</code>```

Can anyone help on this?

答:
Solutions if ID is column with boolean indexing and count not 0 values by compare and sum:

```<code>df[df.drop('ID', 1).ne(0).sum(axis=1).eq(1)]
</code>```

Or if need omit first column:

```<code>df[df.iloc[:, 1:].ne(0).sum(axis=1).eq(1)]
</code>```

If ID is index:

```<code>df[df.ne(0).sum(axis=1).eq(1)]
</code>```

Body:
I have the following dataframe.

ID Value1  Value2  Value3  Value4  Value5
1   0        0       50      100     0
2   0        0       0        0      0
3   0        0       0        50     0
4   0        100     0        0      0
5   50        0      100      50     50

I would like to filter IDs which has only one non-zero values. For example ID == 1 has two non-zero values but ID == 3 and 4 has only one non-zero values and I would like to filter them.

The expected output is ID 3 and 4.

ID Value1  Value2  Value3  Value4  Value5
3   0        0       0        50     0
4   0        100     0        0      0

Can anyone help on this?

Body:
Solutions if ID is column with boolean indexing and count not 0 values by compare and sum:

df[df.drop('ID', 1).ne(0).sum(axis=1).eq(1)]

Or if need omit first column:

df[df.iloc[:, 1:].ne(0).sum(axis=1).eq(1)]

If ID is index:

df[df.ne(0).sum(axis=1).eq(1)]


问:
How to properly define destructor
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

```<code>class1::~class1(void) {

}
</code>```

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico

答: If you are allocating memory dynamically you need to free it in destructor, but better solution would be to use some smart pointer to hold dynamic data - std::auto_ptr or std::shared_ptr. Then you will not need to explicitly free memory - this will be done automatically in smart pointer destructor.

Title: How to properly define destructor

Body:
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

class1::~class1(void) {

}

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico


问:
how to convert denary to binary by repeatedly dividing by 2?
Im stuck on a problem where I have to write a function that converts a denary number into a binary number using the repeated division by two algorithm. Steps Include:

-The number to be converted is divided by two.

-The remainder from the division is the next binary digit. Digits are added to the front of the sequence.

-The result is truncated so that the input to the next division by two is always an integer.

-The algorithm continues until the result is 0.

Please click the link below to see what the output should be like: https://i.stack.imgur.com/pifUO.png

This is My code so far:

```<code>
def dentobi(user):
  denary = user
  divide = user / 2
  remainder = user % 2
  binary = remainder

  while user != 0:
    print("Denary:", denary)
    print("Divide by 2:", divide)
    print("Remainder:", remainder)
    print("Binary:", binary)
    result = str(binary) + str(remainder)
    print(result)

user = int(input("Please enter a number: "))
dentobi(user)

</code>```

My output when a number doesn't have remainder is:

Please enter a number: 20
Denary: 20
Divide by 2: 10.0
Remainder: 0
Binary: 0
Output when the number does have a remainder:

Please enter a number: 20
Denary: 20
Divide by 2: 10.0
Remainder: 0
Binary: 0

This is one part of what I wanted to happen however I need this to iterate over and over again until the actual value reaches zero.

I need some help in coding the remainder to go in the front each time, appreciate the advice.

答:
There are many different ways to do this. Here's one:

```<code>def dentobi(n):
    result = ''
    while n > 0:
        result =  str(n % 2) + result
        n //= 2
    return result or '0'

print(dentobi(26))
</code>```

Output:

```<code>11010
</code>```

Note:

This will not work for negative values

Body:
Im stuck on a problem where I have to write a function that converts a denary number into a binary number using the repeated division by two algorithm. Steps Include:

-The number to be converted is divided by two.

-The remainder from the division is the next binary digit. Digits are added to the front of the sequence.

-The result is truncated so that the input to the next division by two is always an integer.

-The algorithm continues until the result is 0.

Please click the link below to see what the output should be like: https://i.stack.imgur.com/pifUO.png

This is My code so far:

def dentobi(user):
  denary = user
  divide = user / 2
  remainder = user % 2
  binary = remainder

  while user != 0:
    print("Denary:", denary)
    print("Divide by 2:", divide)
    print("Remainder:", remainder)
    print("Binary:", binary)
    result = str(binary) + str(remainder)
    print(result)

user = int(input("Please enter a number: "))
dentobi(user)

My output when a number doesn't have remainder is:

Please enter a number: 20
Denary: 20
Divide by 2: 10.0
Remainder: 0
Binary: 0
Output when the number does have a remainder:

Please enter a number: 20
Denary: 20
Divide by 2: 10.0
Remainder: 0
Binary: 0

This is one part of what I wanted to happen however I need this to iterate over and over again until the actual value reaches zero.

I need some help in coding the remainder to go in the front each time, appreciate the advice.

Body:
There are many different ways to do this. Here's one:

def dentobi(n):
    result = ''
    while n > 0:
        result =  str(n % 2) + result
        n //= 2
    return result or '0'

print(dentobi(26))

Output:

11010

Note:

This will not work for negative values


Title: Filtering rows based on specific values: Pandas

Body: df1.set_index('ID')[(df1.set_index('ID')>0).sum(1)==1]


问:
Hibernate JPA, duplicate children result?
I have some relations like the following:

```<code>@Entity
@Table(name="customer")
public class Customer
{
    @Id
    @Column(name="id")
    private int id;

    @OneToMany(fetch=FetchType.EAGER, mappedBy="customer", cascade=CascadeType.ALL)
    private List<OrderedItem> items;

    public List<OrderedItem> getItems ()
    {
        return items;
    }

    public void setItems (List<OrderedItem> _items)
    {
        items = _items;
    }
}

@Entity
@Table(name="ordereditem")
@IdClass(OrderedItemPK.class)
public class OrderedItem
{
    @Id
    @ManyToOne
    @JoinColumn(name="id_customer")
    private Customer customer;

    @Id
    @ManyToOne
    @JoinColumn(name="id_item")
    private Item item;

    public Customer getCustomer ()
    {
        return customer;
    }
    public void setCustomer (Customer _cust)
    {
        customer = _cust;
    }
    public Item getItem ()
    {
        return item;
    }
    public void setItem (Item _item)
    {
        item = _item;
    }
}

@Entity
@Table(name="item")
public class Item
{
    @Id
    @Column(name="id")
    private int id ;

    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name="itemcategory",
        joinColumns=
            @JoinColumn(name="id_item", referencedColumnName="id"),
        inverseJoinColumns=
            @JoinColumn(name="id_category", referencedColumnName="id")
    )
    private List<Category> categories ;

    public int getId ()
    {
        return id;
    }

    public void setId (int _id)
    {
        id = _id;
    }

    public List<Categories> getCategories ()
    {
        return categories;
    }

    public void setCategories (List<Category> _categories)
    {
        categories = _categories;
    }
}

@Entity
@Table(name="category")
public class Category
{
    @Id
    @Column(name="id")
    private int id;

    public int getId ()
    {
        return id;
    }

    public void setId (int _id)
    {
        id = _id;
    }
}

public class OrderedItemPK implements Serializable
{
    private int customer ;
    private int item ;

    public int getCustomer ()
    {
        return a;
    }
    public void setCustomer (int _cust)
    {
        customer = _cust;
    }
    public int getItem ()
    {
        return item;
    }
    public void setItem (int _item)
    {
        item = _item;
    }

    public int hashCode() {
        return customer + item;
    }

    public boolean equals(Object _o) {
        OrderedItemPK other = (OrderedItemPK) _o;
        return (customer == other.customer) && (item == other.item);
    }
}
</code>```

The repository:

```<code>public interface CustomerRepo extends JpaRepository<Customer, Integer> {
}
</code>```

the service:

```<code>@Service
@Transactional
public class CustomerSvc
{
    @Autowired
    CustomerRepo repo;

    public Customer findCustomer(int _id) {
        return repo.findOne(_id);
    }

    public List<Customer> findAllCustomer() {
        return repo.findAll();
    }
}
</code>```

Here is the content in the database:

```<code>customer table:

id
-----
1
2
3

ordereditem table:

id_customer     id_item
-------------------------
1                1
1                2
1                3

item table:

id
-----
1
2
3

category table:

id
----
1
2
3

itemcategory table:

id_item     id_category
-----------------------
1            1
1            2
1            3
2            1
2            2
2            3
3            1
3            2
3            3
</code>```

How I use the service:

```<code>Customer c = custSvc.findOne(1);

// this prints Number of ordered items: 9
System.out.println("Number of ordered items: " + c.getItems().size());

List<Customer> custs = custSvc.findAll();
c = custs.get(0);

// this prints Number of ordered items: 3
System.out.println("Number of ordered items: " + c.getItems().size());
</code>```

The correct amount should be 3, a customer with the id 1 has 3 OrderedItems, these 3 OrderedItems have 1 Item for each of them and every Item has 3 categories.

I wonder why it only gives the wrong children if I use method like findOne from the Spring Data and find method from the EntityManager, it correctly gives the right children if I use method like findAll or findByAttribute from the Spring Data.

答: remove fetch=FetchType.EAGER from @OneToMany in Customer entity. Rather use @Transactional where you want to fetch child records

Body:
I have some relations like the following:

@Entity
@Table(name="customer")
public class Customer
{
    @Id
    @Column(name="id")
    private int id;

    @OneToMany(fetch=FetchType.EAGER, mappedBy="customer", cascade=CascadeType.ALL)
    private List<OrderedItem> items;

    public List<OrderedItem> getItems ()
    {
        return items;
    }

    public void setItems (List<OrderedItem> _items)
    {
        items = _items;
    }
}

@Entity
@Table(name="ordereditem")
@IdClass(OrderedItemPK.class)
public class OrderedItem
{
    @Id
    @ManyToOne
    @JoinColumn(name="id_customer")
    private Customer customer;

    @Id
    @ManyToOne
    @JoinColumn(name="id_item")
    private Item item;

    public Customer getCustomer ()
    {
        return customer;
    }
    public void setCustomer (Customer _cust)
    {
        customer = _cust;
    }
    public Item getItem ()
    {
        return item;
    }
    public void setItem (Item _item)
    {
        item = _item;
    }
}

@Entity
@Table(name="item")
public class Item
{
    @Id
    @Column(name="id")
    private int id ;

    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(name="itemcategory",
        joinColumns=
            @JoinColumn(name="id_item", referencedColumnName="id"),
        inverseJoinColumns=
            @JoinColumn(name="id_category", referencedColumnName="id")
    )
    private List<Category> categories ;

    public int getId ()
    {
        return id;
    }

    public void setId (int _id)
    {
        id = _id;
    }

    public List<Categories> getCategories ()
    {
        return categories;
    }

    public void setCategories (List<Category> _categories)
    {
        categories = _categories;
    }
}

@Entity
@Table(name="category")
public class Category
{
    @Id
    @Column(name="id")
    private int id;

    public int getId ()
    {
        return id;
    }

    public void setId (int _id)
    {
        id = _id;
    }
}

public class OrderedItemPK implements Serializable
{
    private int customer ;
    private int item ;

    public int getCustomer ()
    {
        return a;
    }
    public void setCustomer (int _cust)
    {
        customer = _cust;
    }
    public int getItem ()
    {
        return item;
    }
    public void setItem (int _item)
    {
        item = _item;
    }

    public int hashCode() {
        return customer + item;
    }

    public boolean equals(Object _o) {
        OrderedItemPK other = (OrderedItemPK) _o;
        return (customer == other.customer) && (item == other.item);
    }
}

The repository:

public interface CustomerRepo extends JpaRepository<Customer, Integer> {
}

the service:

@Service
@Transactional
public class CustomerSvc
{
    @Autowired
    CustomerRepo repo;

    public Customer findCustomer(int _id) {
        return repo.findOne(_id);
    }

    public List<Customer> findAllCustomer() {
        return repo.findAll();
    }
}

Here is the content in the database:

customer table:

id
-----
1
2
3

ordereditem table:

id_customer     id_item
-------------------------
1                1
1                2
1                3

item table:

id
-----
1
2
3

category table:

id
----
1
2
3

itemcategory table:

id_item     id_category
-----------------------
1            1
1            2
1            3
2            1
2            2
2            3
3            1
3            2
3            3

How I use the service:

Customer c = custSvc.findOne(1);

// this prints Number of ordered items: 9
System.out.println("Number of ordered items: " + c.getItems().size());

List<Customer> custs = custSvc.findAll();
c = custs.get(0);

// this prints Number of ordered items: 3
System.out.println("Number of ordered items: " + c.getItems().size());

The correct amount should be 3, a customer with the id 1 has 3 OrderedItems, these 3 OrderedItems have 1 Item for each of them and every Item has 3 categories.

I wonder why it only gives the wrong children if I use method like findOne from the Spring Data and find method from the EntityManager, it correctly gives the right children if I use method like findAll or findByAttribute from the Spring Data.


问:
airflow task is failing because of "Set is not JSON serializable"
I got a DAG which is using BigQuery operators in some of its tasks.
One of such tasks keeps failing, saying that my configuration parameter is actually a set, which cannot be serialised to JSON.

However, I don't understand why I'm getting the error, since I don't see anything that could be turning this dict into a set.

```<code>some_task = BigQueryInsertJobOperator(
        task_id='some_task',
        configuration={
            "query": {
                "query": "{% include 'sql/some_sql_script.sql' %}",
                "useLegacySql": False,
            },
            "destinationTable": {
                some_dest_table.ref #I have access to this value.
            }
        },
        params={
            'some_param': some_param.ref,
            'some_other_param': some_other_param.ref,
            'yet_other_param': yet_other_param.ref
        }
    )
</code>```

When inspecting the rendered template, I can see the config "bleeding" into the actual sql script. i.e

```<code>"config={query select foo from bar"
</code>```

actual error from the logs is TypeError: Object of type set is not JSON serializable

答: Looks like the issue is with destinatonTable field. Drop the curly braces there. Your’e wrapping the value there with curly braces and provide no key - which makes a set</p>

Body:
I got a DAG which is using BigQuery operators in some of its tasks.
One of such tasks keeps failing, saying that my configuration parameter is actually a set, which cannot be serialised to JSON.

However, I don't understand why I'm getting the error, since I don't see anything that could be turning this dict into a set.

some_task = BigQueryInsertJobOperator(
        task_id='some_task',
        configuration={
            "query": {
                "query": "{% include 'sql/some_sql_script.sql' %}",
                "useLegacySql": False,
            },
            "destinationTable": {
                some_dest_table.ref #I have access to this value.
            }
        },
        params={
            'some_param': some_param.ref,
            'some_other_param': some_other_param.ref,
            'yet_other_param': yet_other_param.ref
        }
    )

When inspecting the rendered template, I can see the config "bleeding" into the actual sql script. i.e

"config={query select foo from bar"

actual error from the logs is TypeError: Object of type set is not JSON serializable


问:
Overloading class name with integer variable
I am learning C++ using the books listed here. In particular, i read about overloading. So after reading i am trying out different examples to clear my concept further. One such example whose output i am unable to understand is given below:

```<code>int Name = 0;

class Name
{
    int x[2];
};
void func()
{
    std::cout << sizeof(Name) << std::endl; //My question is: Why here Name refers to the integer variable Name and not class named Name
}

int main()
{
    func();

}
</code>```

When i call func, then in the statement std::cout << sizeof(Name) << std::endl;, Name refers to the int Name and not class named Name. Why is this so? I expected that this would give me ambiguity error because there are two(different) entities with the same name. But the program works without any error and sizeof is applied to int Name instead of class named Name. I have read about function overloading in the books. But not about this kind of overloading. What is it called and what is happening here.

PS: I know that i can write std::cout<< sizeof(class Name); where sizeof will applied to the class named Name instead of variable int Name. Also, the example is for academic purposes. I know that use of global variable should be avoided. The question is not about how to solve this(say by not using same name for those two entities) but about what is happening.

答:
What happens here is "shadowing". The global varible shadows the class of the same name.

What you can do to avoid it is:

(don't use global variables)

don't give the same name to different entities. Typically naming conventions are different for variables and types (eg name for the variable vs Name for the type).

make it explicit that you want to refer to the type via std::cout << sizeof(class Name) << std::endl;

if you really want them to have the same name you can place them in different namespaces.

For example:

```<code>#include <iostream>

namespace foo {
    int Name = 0;
}

namespace bar {
    class Name {
        int x[2];
    };
}

namespace baz {
    void func() {
        std::cout << sizeof(foo::Name) << std::endl;
        std::cout << sizeof(bar::Name) << std::endl;
    }
}

int main()
{
    baz::func();

}
</code>```

PS: As mentioned in a comment, this has nothing to do with overloading. Shadowing generally refers to entities having the same name while only one is accessible by that name. Overloading is very different from that, because when you overload a function then typically all the overloads are accessible and overload resolution decides which one to use.

Body:
I am learning C++ using the books listed here. In particular, i read about overloading. So after reading i am trying out different examples to clear my concept further. One such example whose output i am unable to understand is given below:

int Name = 0;

class Name
{
    int x[2];
};
void func()
{
    std::cout << sizeof(Name) << std::endl; //My question is: Why here Name refers to the integer variable Name and not class named Name
}

int main()
{
    func();

}

When i call func, then in the statement std::cout << sizeof(Name) << std::endl;, Name refers to the int Name and not class named Name. Why is this so? I expected that this would give me ambiguity error because there are two(different) entities with the same name. But the program works without any error and sizeof is applied to int Name instead of class named Name. I have read about function overloading in the books. But not about this kind of overloading. What is it called and what is happening here.

PS: I know that i can write std::cout<< sizeof(class Name); where sizeof will applied to the class named Name instead of variable int Name. Also, the example is for academic purposes. I know that use of global variable should be avoided. The question is not about how to solve this(say by not using same name for those two entities) but about what is happening.

Body:
What happens here is "shadowing". The global varible shadows the class of the same name.

What you can do to avoid it is:

(don't use global variables)

don't give the same name to different entities. Typically naming conventions are different for variables and types (eg name for the variable vs Name for the type).

make it explicit that you want to refer to the type via std::cout << sizeof(class Name) << std::endl;

if you really want them to have the same name you can place them in different namespaces.

For example:

#include <iostream>

namespace foo {
    int Name = 0;
}

namespace bar {
    class Name {
        int x[2];
    };
}

namespace baz {
    void func() {
        std::cout << sizeof(foo::Name) << std::endl;
        std::cout << sizeof(bar::Name) << std::endl;
    }
}

int main()
{
    baz::func();

}

PS: As mentioned in a comment, this has nothing to do with overloading. Shadowing generally refers to entities having the same name while only one is accessible by that name. Overloading is very different from that, because when you overload a function then typically all the overloads are accessible and overload resolution decides which one to use.


问:
understanding the content of a csproj file
I have some older projects in non-SDK style which were created using Visual Studio; the csproj files were almost never modified manually. They were done partly by colleages before I came to this company, so I have very incomplete knowledge about what should or shouldn't be in these files.

Now I am trying to turn them into SDK-style projects by manually modifying the csproj files. In order to do that, I need to understand for each tag what it is for, and if it can be omitted or must be modified.

There might be

non-SDK-style leftovers that can just be deleted,

content we were not aware of (because we don't always know what we are doing when playing around with settings in a project),

content that needs to be modified to fit the new SDK-style specification,

content that can be omitted because it contains just its default value,

etc.

I try getting by by googling a given tag together with "csproj", but more often than not I cannot find useful content. I also noticed that most of the time I DO NOT find a source from Microsoft, mostly blog entries by private guys that sometimes, sometimes not tell me what I want to know.

There are some Microsoft docs like sdk reference or common properties, but they do not cover all tags that I have in my project.

So, how can I understand the content of my csproj file? Is the documentation there and I am merely not finding it? If so, what to search for? Shouldn't Microsoft have a comprehensive list of all possible tags? They have invented the csproj format, so they should know. Or do I need to learn something else first that is a prerequisite of working with csproj files (like before constructing bridges one should know about basic algebra and calculus), that will help me figure out stuff on my own?

答:
cproj files can have a lot of project configurations. Visual Studio Extensions might also modify cproj files and add custom values.

As per the comments on this answer, there isn't a complete list of available properties for Visual Studio projects. The links provided in the question contains most used properties, so that should cater for the average project.

It is very rare that properties will be used that is not contained in those links. If you do run across an unknown property, try searching online, if that fails, ask on SO.

A good search query that hasn't failed me yet, {Project Type} "{Property}" csproj property : .Net "TestProjectType" csproj property.