问:
Interleave 2 Dataframes on certain columns
I have 2 dataframes

```<code>df1:

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort,LinkType,Speed
DD1,Switch1,P1,AD1,Switch2,P2,MTP,1000
DD2,Switch2,P3,AD2,Switch3,P2,MTP,1000
DD3,Switch3,P5,AD3,Switch4,P6,MTP,1000

df2:

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort
AB11,RU15,P1,AJ11,RU25,P2
AB12,RU18,P2,AB11,RU35,P2
AB13,RU19,P3,AB11,RU40,P4
</code>```

I want to interleave the two dataframes and I've tried a few options but can't seem to get it to work. I'm close to the functionality with the below code but it doesn't join on the appropriate columns

```<code>import pandas as pd
from toolz import interleave

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1)
</code>```

Expected Output would look like

```<code>StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort,LinkType,Speed
DD1,Switch1,P1,AD1,Switch2,P2,MTP,1000
AB11,RU15,P1,AJ11,RU25,P2,nan,nan
DD2,Switch2,P3,AD2,Switch3,P2,MTP,1000
AB12,RU18,P2,AB11,RU35,P2,nan,nan
DD3,Switch3,P5,AD3,Switch4,P6,MTP,1000
AB13,RU19,P3,AB11,RU40,P4,nan,nan
</code>```

I think it should be pretty simple but I can't find the appropriate syntax. Can anyone give any ideas?

Thanks in advance for the help!

答:
If columns names are same, only difference is some new columns names in one of DataFrame is possible use:

```<code>df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1.columns)
print (df3)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P2     None
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P2     None
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4     None

    Speed
0  1000.0
1     NaN
2  1000.0
3     NaN
4  1000.0
5     NaN
</code>```

More general solution working for any columns names is use DataFrame.align before for prevent correct align columns for each DataFrame:

```<code>print (df1)
  EndDevice EndLocation EndPort LinkType  Speed StartDevice StartLocation  \
0   Switch2         AD1      P2      MTP   1000     Switch1           DD1
1   Switch3         AD2      P2      MTP   1000     Switch2           DD2
2   Switch4         AD3      P6      MTP   1000     Switch3           DD3

  StartPort
0        P1
1        P3
2        P5

print (df2)
  EndDevice EndLocation EndPort  LinkType  Speed StartDevice StartLocation  \
0      RU25        AJ11      P2       NaN    NaN        RU15          AB11
1      RU35        AB11      P2       NaN    NaN        RU18          AB12
2      RU40        AB11      P4       NaN    NaN        RU19          AB13

  StartPort
0        P1
1        P2
2        P3
</code>```

```<code>df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1.columns)
print (df3)
  EndDevice EndLocation EndPort LinkType   Speed StartDevice StartLocation  \
0   Switch2         AD1      P2      MTP  1000.0     Switch1           DD1
1      RU25        AJ11      P2      NaN     NaN        RU15          AB11
2   Switch3         AD2      P2      MTP  1000.0     Switch2           DD2
3      RU35        AB11      P2      NaN     NaN        RU18          AB12
4   Switch4         AD3      P6      MTP  1000.0     Switch3           DD3
5      RU40        AB11      P4      NaN     NaN        RU19          AB13

  StartPort
0        P1
1        P1
2        P3
3        P2
4        P5
5        P3
</code>```

Another idea with Index.union and DataFrame.reindex:

```<code>cols = df1.columns.union(df2.columns, sort=False)

df1 = df1.reindex(cols, axis=1)
df2 = df2.reindex(cols, axis=1)
print (df1)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1           DD2     Switch2        P3         AD2   Switch3      P2      MTP
2           DD3     Switch3        P5         AD3   Switch4      P6      MTP

   Speed
0   1000
1   1000
2   1000

print (df2)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort  LinkType  \
0          AB11        RU15        P1        AJ11      RU25      P2       NaN
1          AB12        RU18        P2        AB11      RU35      P2       NaN
2          AB13        RU19        P3        AB11      RU40      P4       NaN

   Speed
0    NaN
1    NaN
2    NaN
</code>```

```<code>df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=cols)
print (df3)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P2      NaN
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P2      NaN
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4      NaN

    Speed
0  1000.0
1     NaN
2  1000.0
3     NaN
4  1000.0
5     NaN
</code>```

Body:
I have 2 dataframes

df1:

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort,LinkType,Speed
DD1,Switch1,P1,AD1,Switch2,P2,MTP,1000
DD2,Switch2,P3,AD2,Switch3,P2,MTP,1000
DD3,Switch3,P5,AD3,Switch4,P6,MTP,1000

df2:

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort
AB11,RU15,P1,AJ11,RU25,P2
AB12,RU18,P2,AB11,RU35,P2
AB13,RU19,P3,AB11,RU40,P4

I want to interleave the two dataframes and I've tried a few options but can't seem to get it to work. I'm close to the functionality with the below code but it doesn't join on the appropriate columns

import pandas as pd
from toolz import interleave

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1)

Expected Output would look like

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort,LinkType,Speed
DD1,Switch1,P1,AD1,Switch2,P2,MTP,1000
AB11,RU15,P1,AJ11,RU25,P2,nan,nan
DD2,Switch2,P3,AD2,Switch3,P2,MTP,1000
AB12,RU18,P2,AB11,RU35,P2,nan,nan
DD3,Switch3,P5,AD3,Switch4,P6,MTP,1000
AB13,RU19,P3,AB11,RU40,P4,nan,nan

I think it should be pretty simple but I can't find the appropriate syntax. Can anyone give any ideas?

Thanks in advance for the help!

Body:
If columns names are same, only difference is some new columns names in one of DataFrame is possible use:

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1.columns)
print (df3)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P2     None
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P2     None
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4     None

    Speed
0  1000.0
1     NaN
2  1000.0
3     NaN
4  1000.0
5     NaN

More general solution working for any columns names is use DataFrame.align before for prevent correct align columns for each DataFrame:

print (df1)
  EndDevice EndLocation EndPort LinkType  Speed StartDevice StartLocation  \
0   Switch2         AD1      P2      MTP   1000     Switch1           DD1
1   Switch3         AD2      P2      MTP   1000     Switch2           DD2
2   Switch4         AD3      P6      MTP   1000     Switch3           DD3

  StartPort
0        P1
1        P3
2        P5

print (df2)
  EndDevice EndLocation EndPort  LinkType  Speed StartDevice StartLocation  \
0      RU25        AJ11      P2       NaN    NaN        RU15          AB11
1      RU35        AB11      P2       NaN    NaN        RU18          AB12
2      RU40        AB11      P4       NaN    NaN        RU19          AB13

  StartPort
0        P1
1        P2
2        P3

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1.columns)
print (df3)
  EndDevice EndLocation EndPort LinkType   Speed StartDevice StartLocation  \
0   Switch2         AD1      P2      MTP  1000.0     Switch1           DD1
1      RU25        AJ11      P2      NaN     NaN        RU15          AB11
2   Switch3         AD2      P2      MTP  1000.0     Switch2           DD2
3      RU35        AB11      P2      NaN     NaN        RU18          AB12
4   Switch4         AD3      P6      MTP  1000.0     Switch3           DD3
5      RU40        AB11      P4      NaN     NaN        RU19          AB13

  StartPort
0        P1
1        P1
2        P3
3        P2
4        P5
5        P3

Another idea with Index.union and DataFrame.reindex:

cols = df1.columns.union(df2.columns, sort=False)

df1 = df1.reindex(cols, axis=1)
df2 = df2.reindex(cols, axis=1)
print (df1)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1           DD2     Switch2        P3         AD2   Switch3      P2      MTP
2           DD3     Switch3        P5         AD3   Switch4      P6      MTP

   Speed
0   1000
1   1000
2   1000

print (df2)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort  LinkType  \
0          AB11        RU15        P1        AJ11      RU25      P2       NaN
1          AB12        RU18        P2        AB11      RU35      P2       NaN
2          AB13        RU19        P3        AB11      RU40      P4       NaN

   Speed
0    NaN
1    NaN
2    NaN

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=cols)
print (df3)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P2      NaN
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P2      NaN
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4      NaN

    Speed
0  1000.0
1     NaN
2  1000.0
3     NaN
4  1000.0
5     NaN


来源: stackexchange

问:
Not able to find error in my Heap Sort Code. Not executing properly. C++
Please help. I have reviewed it and seem to be missing the error. It seems to be exiting out of the function Max_Heapify and not running my second loop to print the sorted array. This was for an assignment I have already turned in but I am trying to learn the error of my ways to make sure I can do well on the test. </p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

// declare global variable of heap size
int heap_size = 7;

// function to determine left child node of the tree
int Left(int i){
    return 2*i+1;
}

// function to determine right child node of the tree
int Right(int i){
    return 2*i + 2;
}

// create heap tree
void Max_Heapify (int array[], int index){
    int left_child_index = Left(index);
    int right_child_index = Right(index);
    int largest;

    // check if left child is smaller than heap size and if left child is bigger than parent
    // if so, save variable as largest value, otherwise, largest value will stay as index
    if ( (left_child_index < heap_size) && (array[left_child_index] > array[index]) )
        largest = left_child_index;
    else largest = index;
    // check if right child is smaller than heap and if bigger than largest value
    if ((right_child_index < heap_size) && (array[right_child_index] > array[largest]) )
        largest = right_child_index;
    // exchange largest values
    if (largest != index)
        swap(array[index], array[largest]);

    Max_Heapify(array,largest);

}

// check leaves
void Build_Max_Heap(int array[]){

    for (int i = (heap_size / 2 ) - 1; i >= 0; i--)
        Max_Heapify (array, i);
}

void Heapsort(int array[]) {
    Build_Max_Heap(array);
    for (int i = heap_size-1; i >= 0; i--){
        swap(array[0], array[i]);
        Max_Heapify(array,0);
    }
}

int main(){

    int arr[7] = {21, 9, 50, 7, 6, 33, 77};

    cout << "Non Heapified Array: " << endl;
    for (int i = 0; i < heap_size; i++){
        cout << arr[i] << endl;
    }

    Heapsort(arr);

    for (int i = 0; i < heap_size; i++){
        cout << arr[i]<< endl;
    }

}
</code>```

答:
Your MaxHeapify never terminates. You should call MaxHeapify only if largest is not i. If largest is i, then nothing needs to be done here as the elements are already heapified.

```<code>if (largest != index){
    swap(array[index], array[largest]);
    Max_Heapify(array,largest);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Please help. I have reviewed it and seem to be missing the error. It seems to be exiting out of the function Max_Heapify and not running my second loop to print the sorted array. This was for an assignment I have already turned in but I am trying to learn the error of my ways to make sure I can do well on the test.

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

// declare global variable of heap size
int heap_size = 7;

// function to determine left child node of the tree
int Left(int i){
    return 2*i+1;
}

// function to determine right child node of the tree
int Right(int i){
    return 2*i + 2;
}

// create heap tree
void Max_Heapify (int array[], int index){
    int left_child_index = Left(index);
    int right_child_index = Right(index);
    int largest;

    // check if left child is smaller than heap size and if left child is bigger than parent
    // if so, save variable as largest value, otherwise, largest value will stay as index
    if ( (left_child_index < heap_size) && (array[left_child_index] > array[index]) )
        largest = left_child_index;
    else largest = index;
    // check if right child is smaller than heap and if bigger than largest value
    if ((right_child_index < heap_size) && (array[right_child_index] > array[largest]) )
        largest = right_child_index;
    // exchange largest values
    if (largest != index)
        swap(array[index], array[largest]);

    Max_Heapify(array,largest);

}

// check leaves
void Build_Max_Heap(int array[]){

    for (int i = (heap_size / 2 ) - 1; i >= 0; i--)
        Max_Heapify (array, i);
}

void Heapsort(int array[]) {
    Build_Max_Heap(array);
    for (int i = heap_size-1; i >= 0; i--){
        swap(array[0], array[i]);
        Max_Heapify(array,0);
    }
}

int main(){

    int arr[7] = {21, 9, 50, 7, 6, 33, 77};

    cout << "Non Heapified Array: " << endl;
    for (int i = 0; i < heap_size; i++){
        cout << arr[i] << endl;
    }

    Heapsort(arr);

    for (int i = 0; i < heap_size; i++){
        cout << arr[i]<< endl;
    }

}

Body:
Your MaxHeapify never terminates. You should call MaxHeapify only if largest is not i. If largest is i, then nothing needs to be done here as the elements are already heapified.

if (largest != index){
    swap(array[index], array[largest]);
    Max_Heapify(array,largest);
}


问:
Property 'paramMap' does not exist on type 'ActivatedRoute'. /node_modules/@angular/router/index"' has no exported member 'ParamMap'
hero-detail.component.ts

```<code>import { Component, Input, OnInit } from '@angular/core';
import 'rxjs/add/operator/switchMap';
import { ActivatedRoute} from '@angular/router';
import {  ParamMap } from '@angular/router';
import { Location }                 from '@angular/common';
import { Hero } from '../hero';
import { HeroService } from '../services/hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  @Input() hero: Hero;

  constructor(
    private heroService: HeroService,
  private route: ActivatedRoute,
  private location: Location
  ) { }

  ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) =>     this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);
}

goBack(): void {
  this.location.back();
}

}
</code>```

Error: 1> node_modules/@angular/router/index"' has no exported member 'ParamMap'.

2>  Property 'paramMap' does not exist on type 'ActivatedRoute'.

答:
On latest version you can now write :

```<code>import { ActivatedRoute } from '@angular/router';
//...
constructor(private activatedRoute: ActivatedRoute) {}
//...
ngOnInit() {
    const id = this.activatedRoute.snapshot.paramMap.get('id');
    if (id) {
        console.log ('id parameter: ', id);
    } else {
          console.log ('no id parameter');
    }
}
</code>```

Hope it can help.

ContentLicense: CC BY-SA 3.0

Body:
hero-detail.component.ts

import { Component, Input, OnInit } from '@angular/core';
import 'rxjs/add/operator/switchMap';
import { ActivatedRoute} from '@angular/router';
import {  ParamMap } from '@angular/router';
import { Location }                 from '@angular/common';
import { Hero } from '../hero';
import { HeroService } from '../services/hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  @Input() hero: Hero;

  constructor(
    private heroService: HeroService,
  private route: ActivatedRoute,
  private location: Location
  ) { }

  ngOnInit(): void {
  this.route.paramMap
    .switchMap((params: ParamMap) =>     this.heroService.getHero(+params.get('id')))
    .subscribe(hero => this.hero = hero);
}

goBack(): void {
  this.location.back();
}

}

Error: 1> node_modules/@angular/router/index"' has no exported member 'ParamMap'.

2>  Property 'paramMap' does not exist on type 'ActivatedRoute'.

Body:
On latest version you can now write :

import { ActivatedRoute } from '@angular/router';
//...
constructor(private activatedRoute: ActivatedRoute) {}
//...
ngOnInit() {
    const id = this.activatedRoute.snapshot.paramMap.get('id');
    if (id) {
        console.log ('id parameter: ', id);
    } else {
          console.log ('no id parameter');
    }
}

Hope it can help.


问:
Problems with generating SAS manually for blob file
I'm trying to make a downloader attached to the service bus that is going to download the files from blob storage. But I'm having some problems with generating the SAS token manually, please se the error message below.

I'm getting error <AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>

```<code>    private static string createToken(string resourceUri, string keyName, string key)
    {
        var now = DateTime.UtcNow;

        TimeSpan sinceEpoch = now - new DateTime(1970, 1, 1);

        var time = 60 * 2;

        var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + time);
        var expiryDateString = now.AddSeconds(time).ToUniversalTime().ToString("u");

        string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;

        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

        var sasToken = String.Format(
            CultureInfo.InvariantCulture,
            "{0}?sp={1}&st={2}&se={3}&spr={4}&sv={5}&sr={6}&sig={7}",
            resourceUri,
            "r",
            DateTime.UtcNow.ToUniversalTime().ToString("u"),
            expiryDateString,
            "https",
            "2019-02-02",
            "b",
            HttpUtility.UrlEncode(signature));

        return sasToken;
    }
</code>```

Is it the stringToSign? Or signature as a whole? I'm a but unusre, to maybe I need to use the HttpUtility.UrlEncoder on all fields?

答:
Please try the code below, it generates a working sas token for me:

```<code>static void Main(string[] args)
{
    string resourceUri = "https://xx.blob.core.windows.net/test1/1.txt";
    string account_name= "storage account name";
    string key = "storage account key";

    string s1 = createToken(resourceUri,account_name,key);

    Console.WriteLine(s1);

    Console.ReadLine();
}

private static string createToken(string resourceUri, string account_name, string key)
{
    var accountName = account_name;
    var accountKey = key;
    var start = DateTime.UtcNow.AddHours(-2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var end = DateTime.UtcNow.AddHours(2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var permission = "rwdlac";
    var serviceType = "b";
    var resourceTypes = "sco";
    var protocol = "https";
    var serviceVersion = "2019-02-02";

    //here is the difference from your code.
    var stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n",accountName, permission,serviceType,resourceTypes,start,end,"",protocol,serviceVersion);

    HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(accountKey));
    string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    var sasToken = string.Format("?sv={0}&ss={1}&srt={2}&sp={3}&se={4}&st={5}&spr={6}&sig={7}", serviceVersion,
        serviceType, resourceTypes, permission, end, start, protocol, HttpUtility.UrlEncode(signature));

    var urlToListTables = resourceUri + sasToken;

    return urlToListTables;
}
</code>```

Please let me know if you still have any issues.

Body:
I'm trying to make a downloader attached to the service bus that is going to download the files from blob storage. But I'm having some problems with generating the SAS token manually, please se the error message below.

I'm getting error <AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>

    private static string createToken(string resourceUri, string keyName, string key)
    {
        var now = DateTime.UtcNow;

        TimeSpan sinceEpoch = now - new DateTime(1970, 1, 1);

        var time = 60 * 2;

        var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + time);
        var expiryDateString = now.AddSeconds(time).ToUniversalTime().ToString("u");

        string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;

        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

        var sasToken = String.Format(
            CultureInfo.InvariantCulture,
            "{0}?sp={1}&st={2}&se={3}&spr={4}&sv={5}&sr={6}&sig={7}",
            resourceUri,
            "r",
            DateTime.UtcNow.ToUniversalTime().ToString("u"),
            expiryDateString,
            "https",
            "2019-02-02",
            "b",
            HttpUtility.UrlEncode(signature));

        return sasToken;
    }

Is it the stringToSign? Or signature as a whole? I'm a but unusre, to maybe I need to use the HttpUtility.UrlEncoder on all fields?

Body:
Please try the code below, it generates a working sas token for me:

static void Main(string[] args)
{
    string resourceUri = "https://xx.blob.core.windows.net/test1/1.txt";
    string account_name= "storage account name";
    string key = "storage account key";

    string s1 = createToken(resourceUri,account_name,key);

    Console.WriteLine(s1);

    Console.ReadLine();
}

private static string createToken(string resourceUri, string account_name, string key)
{
    var accountName = account_name;
    var accountKey = key;
    var start = DateTime.UtcNow.AddHours(-2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var end = DateTime.UtcNow.AddHours(2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var permission = "rwdlac";
    var serviceType = "b";
    var resourceTypes = "sco";
    var protocol = "https";
    var serviceVersion = "2019-02-02";

    //here is the difference from your code.
    var stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n",accountName, permission,serviceType,resourceTypes,start,end,"",protocol,serviceVersion);

    HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(accountKey));
    string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    var sasToken = string.Format("?sv={0}&ss={1}&srt={2}&sp={3}&se={4}&st={5}&spr={6}&sig={7}", serviceVersion,
        serviceType, resourceTypes, permission, end, start, protocol, HttpUtility.UrlEncode(signature));

    var urlToListTables = resourceUri + sasToken;

    return urlToListTables;
}

Please let me know if you still have any issues.


问:
How to get the latest folder that contains a specific file of interest in Linux and download that file using Paramiko in Python?
I am trying to scp a specific file from a remote server to my local machine using Paramiko in Python 3.

Background:
There is a directory mydir on the destination machine 198.18.2.2 that contains many timestamp directories that start with the name 2020...

Destination machine: 198.18.2.2

Source Machine: 198.18.1.1

So far I have managed to construct the command to be executed as follows -

cd "$(ls -1d /mydir/20* | tail -1)"; scp -o StrictHostKeyChecking=no email_summary.log root@198.18.1.1:/mydir/work/logs/email_summary_198.18.2.2.log
```

<p>Code:</p>

```def remote_execute(dest_ip, cmd):
    """API to execute command on remote machine"""
    result = []
    sys.stderr = open('/dev/null')
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh_client.connect(dest_ip, username='root')
        stdin, stdout, stderr = ssh_client.exec_command(cmd)
        for line in stdout.readlines():
            result.append(line.strip())
        ssh_client.close()
        return result
    except paramiko.AuthenticationException:
        print("Authentication with the remote machine failed")
        return
    except paramiko.SSHException:
        print("Connection to remote machine failed")
        return
    except paramiko.BadHostKeyException:
        print("Bad host key exception for remote machine")
        return
```

Call: remote_execute('198.18.1.1', cmd)

The problem is ls -1d /mydir/20* | tail -1 always gives me the latest timestamp folder. But if the email_summary.log file is not present in that folder, I would like to look into next latest timestamp folder that has the file email_summary.log.

Essentially, scp the file from the latest timestamp folder that contains the file "email_summary.log". Can someone please help me with this?

Thanks in advance.

答:
Executing scp command on the remote machine to push the file back to the local machine is an overkill. And in general relying on shell commands is very fragile approach. You better use native Python code only, to identify the latest remote file and pull it to your local machine. Your code will be way more robust and readable.

```<code>sftp = ssh.open_sftp()
sftp.chdir('/mydir')

files = sftp.listdir_attr()

dirs = [f for f in files if S_ISDIR(f.st_mode)]
dirs.sort(key = lambda d: d.st_mtime, reverse = True)

filename = 'email_summary.log'

for d in dirs:
    print('Checking ' + d.filename)
    try:
        path = d.filename + '/' + filename
        sftp.stat(path)
        print('File exists, downloading...')
        sftp.get(path, filename)
        break
    except IOError:
        print('File does not exist, will try the next folder')
</code>```

The above is based on:

How to download only the latest file from SFTP server with Paramiko?

Paramiko get sorted directory listing

Side note: Do not use AutoAddPolicy. You  lose security by doing so. See Paramiko "Unknown Server".

Body:
I am trying to scp a specific file from a remote server to my local machine using Paramiko in Python 3.

Background:
There is a directory mydir on the destination machine 198.18.2.2 that contains many timestamp directories that start with the name 2020...

Destination machine: 198.18.2.2

Source Machine: 198.18.1.1

So far I have managed to construct the command to be executed as follows -

cd "$(ls -1d /mydir/20* | tail -1)"; scp -o StrictHostKeyChecking=no email_summary.log root@198.18.1.1:/mydir/work/logs/email_summary_198.18.2.2.log

Code:

def remote_execute(dest_ip, cmd):
    """API to execute command on remote machine"""
    result = []
    sys.stderr = open('/dev/null')
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh_client.connect(dest_ip, username='root')
        stdin, stdout, stderr = ssh_client.exec_command(cmd)
        for line in stdout.readlines():
            result.append(line.strip())
        ssh_client.close()
        return result
    except paramiko.AuthenticationException:
        print("Authentication with the remote machine failed")
        return
    except paramiko.SSHException:
        print("Connection to remote machine failed")
        return
    except paramiko.BadHostKeyException:
        print("Bad host key exception for remote machine")
        return

Call: remote_execute('198.18.1.1', cmd)

The problem is ls -1d /mydir/20* | tail -1 always gives me the latest timestamp folder. But if the email_summary.log file is not present in that folder, I would like to look into next latest timestamp folder that has the file email_summary.log.

Essentially, scp the file from the latest timestamp folder that contains the file "email_summary.log". Can someone please help me with this?

Thanks in advance.

Body:
Executing scp command on the remote machine to push the file back to the local machine is an overkill. And in general relying on shell commands is very fragile approach. You better use native Python code only, to identify the latest remote file and pull it to your local machine. Your code will be way more robust and readable.

sftp = ssh.open_sftp()
sftp.chdir('/mydir')

files = sftp.listdir_attr()

dirs = [f for f in files if S_ISDIR(f.st_mode)]
dirs.sort(key = lambda d: d.st_mtime, reverse = True)

filename = 'email_summary.log'

for d in dirs:
    print('Checking ' + d.filename)
    try:
        path = d.filename + '/' + filename
        sftp.stat(path)
        print('File exists, downloading...')
        sftp.get(path, filename)
        break
    except IOError:
        print('File does not exist, will try the next folder')

The above is based on:

How to download only the latest file from SFTP server with Paramiko?

Paramiko get sorted directory listing

Side note: Do not use AutoAddPolicy. You  lose security by doing so. See Paramiko "Unknown Server".


问:
Purging numpy.memmap
Given a numpy.memmap object created with mode='r' (i.e. read-only), is there a way to force it to purge all loaded pages out of physical RAM, without deleting the object itself?

In other words, I'd like the reference to the memmap instance to remain valid, but all physical memory that's being used to cache the on-disk data to be uncommitted. Any views onto to the memmap array must also remain valid.

I am hoping to use this as a diagnostic tool, to help separate "real" memory requirements of a script from "transient" requirements induced by the use of memmap.

I'm using Python 2.7 on RedHat.

答:
If you run "pmap SCRIPT-PID", the "real" memory shows as "[ anon ]" blocks, and all memory-mapped files show up with the file name in the last column.

Purging the pages is possible at C level, if you manage to get ahold of the pointer to the beginning of the mapping and call madvise(ptr, length, MADV_DONTNEED) on it, but it's going to be cludgy.

Title: Purging numpy.memmap


问:
Display result in graph based on combination of year and month selection in laravel
i am display graph of sum of qty datewise it works but now i want to display graph in which sum of qty of month and year combine selection. My date is stored in format 2020-02-14 and i want to display sum of qty of 2020-02 that is from 2019-02 to 2020-09. I tried lot of works. I am getting graph date wise but now i want to year and month combine

For date selection the query as

```<code>$get_details=DB::select('SELECT sum(orders_qty) as sum_of_qty,deliver_date FROM `orders` WHERE deliver_date between ? AND ? GROUP BY deliver_date',[$data['start_date'],$data['end_date']]);
</code>```

For yearand month selection i need query
I tried like this

    $data=$req->all();

    $results = DB::table('orders')
                         ->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
                         ->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
                         ->groupBy('deliver_date')
                         ->get();
    $date[start_year_month]='2019-02' $date[end_year_month]='2019-05' and actual database date='2019-02-14'
```

plz need query

答:
First, use %Y-%m instead of %y-%m;

Secondly, you are rewrite your field's name, so group by will not using the name that has been rewritten, you need to specify DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")

So the query like this:

$data=$req->all();

$results = DB::table('orders')
                ->select(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m") as delivery_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
                         ->whereBetween(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'), [$data['start_year_month'],$data['end_year_month']])
                         ->groupBy(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'))
                         ->get();
```

Body:
i am display graph of sum of qty datewise it works but now i want to display graph in which sum of qty of month and year combine selection. My date is stored in format 2020-02-14 and i want to display sum of qty of 2020-02 that is from 2019-02 to 2020-09. I tried lot of works. I am getting graph date wise but now i want to year and month combine

For date selection the query as

$get_details=DB::select('SELECT sum(orders_qty) as sum_of_qty,deliver_date FROM `orders` WHERE deliver_date between ? AND ? GROUP BY deliver_date',[$data['start_date'],$data['end_date']]);

For yearand month selection i need query
I tried like this

    $data=$req->all();

    $results = DB::table('orders')
                         ->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
                         ->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
                         ->groupBy('deliver_date')
                         ->get();
    $date[start_year_month]='2019-02' $date[end_year_month]='2019-05' and actual database date='2019-02-14'

plz need query


问:
How to use one template of google data studio for multiple accounts dynamically?
I've been looking for a while how to do this:

I have a datasource with the information o multiple clients, I want to create a template of Google Data Studio to show some reports. However, I want that template to be unique and some how show the information per client in the Datasource. Is this possible? Should I use another tool?

答:
What's the Data Source? One way it could be achieved is by email address:

Is it possible to add a column that links clients names / ID with an email address on each row, so that each row will have one email address? If an additional column could be added to your Data Set (e.g. if it's an SQL based Data Source then perhaps using a JOIN with a table that has the contact details of the client) that only lists the email address, then, at the Data Source, you could filter by email address.


问:
TF/KERAS : passing a list as loss for single output
I have only one output for my model, but I would like to combine two different loss functions, (Note: number of CLASSES = 24).

c = 0.8
lamda = 32

# My personalized loss function
def selective_loss(y_true, y_pred): .
    loss = K.categorical_crossentropy(
        K.repeat_elements(y_pred[:, -1:], CLASSES, axis=1) * y_true[:, :-1],
        y_pred[:, :-1]) + lamda * K.maximum(-K.mean(y_pred[:, -1]) + c, 0) ** 2
    return loss

p = np.ones(CLASSES) / CLASSES#The weights of class.

#And doing de model compile.
model.compile(loss = ['categorical_crossentropy', selective_loss],
              loss_weights = p,
              optimizer= sgd,
              metrics = ['accuracy'])

```

<p>But it complains that I need two outputs because I defined two losses:</p>

<pre class="lang-py prettyprint-override"><code>ValueError: When passing a list as loss, it should have one entry per model outputs. The model has 1 outputs, but you passed loss=['categorical_crossentropy', <function selective_loss at 0x7fcfb68daa60>]
</code>```

Would you have to combine the two losses into one? And if so, how would you do it?

Or better to have two outputs? Would this affect the prediction? How would it be?

答:
I perform a weighting between the two loss functions, use alpha 0.5 but other float is valid too:

#Private loss is the selective_loss.
def total_loss(y_true, y_pred):
    alpha = 0.5
    return (1-alpha)*categorical_crossentropy(y_true, y_pred) + alpha*selective_loss(y_true, y_pred)

#Compile the model with weighting loss.
model.compile(loss = total_loss,
              loss_weights = p,
              optimizer= sgd,
              metrics = ['accuracy'])
```

Body:
I have only one output for my model, but I would like to combine two different loss functions, (Note: number of CLASSES = 24).

c = 0.8
lamda = 32

# My personalized loss function
def selective_loss(y_true, y_pred): .
    loss = K.categorical_crossentropy(
        K.repeat_elements(y_pred[:, -1:], CLASSES, axis=1) * y_true[:, :-1],
        y_pred[:, :-1]) + lamda * K.maximum(-K.mean(y_pred[:, -1]) + c, 0) ** 2
    return loss

p = np.ones(CLASSES) / CLASSES#The weights of class.

#And doing de model compile.
model.compile(loss = ['categorical_crossentropy', selective_loss],
              loss_weights = p,
              optimizer= sgd,
              metrics = ['accuracy'])

But it complains that I need two outputs because I defined two losses:

ValueError: When passing a list as loss, it should have one entry per model outputs. The model has 1 outputs, but you passed loss=['categorical_crossentropy', <function selective_loss at 0x7fcfb68daa60>]

Would you have to combine the two losses into one? And if so, how would you do it?

Or better to have two outputs? Would this affect the prediction? How would it be?


问:
how to map multiple OBJECTS to one object using AutoMapper - asp.net mvc 3
Hi All  / very new to Auto-Mapper. i can map one to one objects but was wondering is it possible to map multiple objects to one object or multiple objects to multiple objects?

consider i have a following scenario...

User Model

```<code>public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Company Company { get; set; }  // 1 user work in 1 company
    }
</code>```

Company Model

```<code>public class Company
        {
            public string CompanyName { get; set; }
            public string Website { get; set; }
            public ICollection<User> Users { get; set; }  // 1 Company can have many users
        }
</code>```

UserCompanyViewModel

i want to show List of users with their company details in one view..

```<code>public class UserCompanyViewModel
            {
                 public ICollection<User> Users { get; set; }
                 ppublic ICollection<Company> Companies { get; set; }
            }
</code>```

Now, is it possible to map in this situation and if yes, i can show in one view and when editing that view i want to map again with the updated fields back to their respective Models.

any help would be appreciated...thx

答:
you can use modelMapper

```<code>@Autowired
private ModelMapper modelMapper;
</code>```

and in function

```<code>Desination desination = modelMapper.map(obj1, Desination.class);
modelMapper.map(obj2, desination);
</code>```

Body:
Hi All  / very new to Auto-Mapper. i can map one to one objects but was wondering is it possible to map multiple objects to one object or multiple objects to multiple objects?

consider i have a following scenario...

User Model

public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Company Company { get; set; }  // 1 user work in 1 company
    }

Company Model

public class Company
        {
            public string CompanyName { get; set; }
            public string Website { get; set; }
            public ICollection<User> Users { get; set; }  // 1 Company can have many users
        }

UserCompanyViewModel

i want to show List of users with their company details in one view..

public class UserCompanyViewModel
            {
                 public ICollection<User> Users { get; set; }
                 ppublic ICollection<Company> Companies { get; set; }
            }

Now, is it possible to map in this situation and if yes, i can show in one view and when editing that view i want to map again with the updated fields back to their respective Models.

any help would be appreciated...thx

Body:
you can use modelMapper

@Autowired
private ModelMapper modelMapper;

and in function

Desination desination = modelMapper.map(obj1, Desination.class);
modelMapper.map(obj2, desination);


问:
read JSON to PHP from javascript
I have an API that is available only in javascript (no PHP). It fetches some data of which I made a JSON string. What I need to know is how do I read this string in other page?

I tried using following :

```<code>$json = file_get_contents($url);
</code>```

but of course the string I get is not JSON but is actually the javascript code that will generate json in original page. Any suggestions ?
Thank you.

P.S. I also tried set cookie + redirect. Though that worked, I'd like to know a better solution.

Here is the javascript code

```<code>            function searchComplete() {

                 if (imageSearch.results && imageSearch.results.length > 0)
                 {
                    var contentDiv = document.getElementById('content');
                    contentDiv.innerHTML = '';
                    var results = imageSearch.results;

                    var data = "{['data' : [\n";

                    for (var i = 0; i < results.length; i++) {
                        //var result = results[i];
                        var result = results[i];

                        data += "{\n";
                        data += "'url' : '"+result.url+"'";
                        data += "\n},\n";

                   }
                   data += "]]}";
                   setCookie("datajson", data, 1); // This is how i set the cookie and redirected
                   window.location = "JSPHP.php?data="+data;

                document.getElementById('body').innerHTML = data;
                  }
            }
</code>```

答: Make yourself a web page that executes the javascript and saves the JSON result. Then post the JSON data to a PHP script (via XmlHttpRequest or regular form POST). Now your PHP code has access to the JSON data, and you can use json_decode to access it.

Title: read JSON to PHP from javascript

Body:
I have an API that is available only in javascript (no PHP). It fetches some data of which I made a JSON string. What I need to know is how do I read this string in other page?

I tried using following :

$json = file_get_contents($url);

but of course the string I get is not JSON but is actually the javascript code that will generate json in original page. Any suggestions ?
Thank you.

P.S. I also tried set cookie + redirect. Though that worked, I'd like to know a better solution.

Here is the javascript code

            function searchComplete() {

                 if (imageSearch.results && imageSearch.results.length > 0)
                 {
                    var contentDiv = document.getElementById('content');
                    contentDiv.innerHTML = '';
                    var results = imageSearch.results;

                    var data = "{['data' : [\n";

                    for (var i = 0; i < results.length; i++) {
                        //var result = results[i];
                        var result = results[i];

                        data += "{\n";
                        data += "'url' : '"+result.url+"'";
                        data += "\n},\n";

                   }
                   data += "]]}";
                   setCookie("datajson", data, 1); // This is how i set the cookie and redirected
                   window.location = "JSPHP.php?data="+data;

                document.getElementById('body').innerHTML = data;
                  }
            }


问:
How to postion an image inside a div
I'm trying to put an image in top of my div like in the picture bellow, but I'm having a hard time trying to figure out whats wrong with my css.

#testimonials-cards-container {
    margin: 0;
    width: 95%;
    margin-left: 43px;
}

.testimonials-cards {
    box-shadow: 2px 4px 30px rgba(0, 0, 0, 0.25);
    border-radius: 30px;
    margin: 50px 26px 33px 27px;
    height: 337px;
}

#testimonials-cards-container .testimonials-cards img{
    width: 200px;
    display: table;
    margin: 10px auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sectionSeven">
        <div id="testimonials-cards-container" class="owl-carousel owl-theme">
            <div class="testimonials-cards">
                <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Circle_-_black_simple.svg/1200px-Circle_-_black_simple.svg.png
" alt="">
                <h1>test</h1>
            </div>

        </div>
    </div></code>```

答:
You can use flex to align texts in center and position absolute to align the image.
Css Code is

```<code>        #testimonials-cards-container {
        position: relative;
        margin: 0;
        width: 95%;
        margin-left: 43px;
    }

    .testimonials-cards {
        box-shadow: 2px 4px 30px rgba(0, 0, 0, 0.25);
        border-radius: 30px;
        margin: 50px 26px 33px 27px;
        height: 337px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    #testimonials-cards-container .testimonials-cards img{
        position: absolute;
        top: -50%;
        left: 50%;
        width: 200px;
        display: table;
        margin: 10px auto;
        transform: translate(-50%, 30%);
        z-index: 2;
    }
</code>```

Html Code is

```<code>        <div class="sectionSeven">
            <div id="testimonials-cards-container" class="owl-carousel owl-theme">
                <div class="testimonials-cards">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Circle_-_black_simple.svg/1200px-Circle_-_black_simple.svg.png
    " alt="">
                    <h1>test</h1>
                </div>

            </div>
        </div>
</code>```

You can use this approach at any place in your code. You do not have to worry about height or width of container any more.

Title: How to postion an image inside a div

Body:
I'm trying to put an image in top of my div like in the picture bellow, but I'm having a hard time trying to figure out whats wrong with my css.

#testimonials-cards-container {
    margin: 0;
    width: 95%;
    margin-left: 43px;
}

.testimonials-cards {
    box-shadow: 2px 4px 30px rgba(0, 0, 0, 0.25);
    border-radius: 30px;
    margin: 50px 26px 33px 27px;
    height: 337px;
}

#testimonials-cards-container .testimonials-cards img{
    width: 200px;
    display: table;
    margin: 10px auto;
}

test

Body:
You can use flex to align texts in center and position absolute to align the image.
Css Code is

        #testimonials-cards-container {
        position: relative;
        margin: 0;
        width: 95%;
        margin-left: 43px;
    }

    .testimonials-cards {
        box-shadow: 2px 4px 30px rgba(0, 0, 0, 0.25);
        border-radius: 30px;
        margin: 50px 26px 33px 27px;
        height: 337px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    #testimonials-cards-container .testimonials-cards img{
        position: absolute;
        top: -50%;
        left: 50%;
        width: 200px;
        display: table;
        margin: 10px auto;
        transform: translate(-50%, 30%);
        z-index: 2;
    }

Html Code is

        <div class="sectionSeven">
            <div id="testimonials-cards-container" class="owl-carousel owl-theme">
                <div class="testimonials-cards">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Circle_-_black_simple.svg/1200px-Circle_-_black_simple.svg.png
    " alt="">
                    <h1>test</h1>
                </div>

            </div>
        </div>

You can use this approach at any place in your code. You do not have to worry about height or width of container any more.


问:
OpenCV TypeError: Expected Ptr<cv::UMat> for argument 'img' - What is this?
I am not able to understand what type of error this is..i have written a python script which accepts image input from the user and runs emotion detection.
here's the code:

```<code>import numpy as np
import os
import sys
import tensorflow as tf
import json
from PIL import Image

sys.path.append("..")
from object_detection.utils import ops as utils_ops

from utils import label_map_util
from utils import visualization_utils as vis_util

def Image_tensorflow(xa,ya):
    PATH_TO_FROZEN_GRAPH = 'frozen_inference_graph.pb'
    PATH_TO_LABELS = 'object-detection.pbtxt'
    NUM_CLASSES = 4

    detection_graph = tf.Graph()
    with detection_graph.as_default():
        od_graph_def = tf.GraphDef()
        with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
            serialized_graph = fid.read()
            od_graph_def.ParseFromString(serialized_graph)
            tf.import_graph_def(od_graph_def, name='')

    label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
    categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
                                                                use_display_name=True)
    category_index = label_map_util.create_category_index(categories)

    def load_image_into_numpy_array(image):
        (im_width, im_height) = image.size
        return np.array(image.getdata()).reshape(
            (im_height, im_width, 3)).astype(np.uint8)

    def image_url(xa, ya):
        file_path = 'images/'
        file_name = ya
        image = xa
        f = open((file_path + str(file_name) + ".json"), "w")
        f.close
        return_dict = {'image': image, 'file': f};
        return return_dict

    get_image_data = image_url(xa,ya)
    image_path= get_image_data['image']

    IMAGE_SIZE = (12, 8)

    def run_inference_for_single_image(image, graph):
        with graph.as_default():
            with tf.Session() as sess:
                # Get handles to input and output tensors
                ops = tf.get_default_graph().get_operations()
                all_tensor_names = {output.name for op in ops for output in op.outputs}
                tensor_dict = {}
                for key in [
                    'num_detections', 'detection_boxes', 'detection_scores',
                    'detection_classes', 'detection_masks'
                ]:
                    tensor_name = key + ':0'
                    if tensor_name in all_tensor_names:
                        tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                            tensor_name)
                if 'detection_masks' in tensor_dict:
                    # The following processing is only for single image
                    detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
                    detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
                    # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
                    real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
                    detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
                    detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
                    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                        detection_masks, detection_boxes, image.shape[0], image.shape[1])
                    detection_masks_reframed = tf.cast(
                        tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                    tensor_dict['detection_masks'] = tf.expand_dims(
                        detection_masks_reframed, 0)
                image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

                output_dict = sess.run(tensor_dict,
                                       feed_dict={image_tensor: np.expand_dims(image, 0)})

                output_dict['num_detections'] = int(output_dict['num_detections'][0])
                output_dict['detection_classes'] = output_dict[
                    'detection_classes'][0].astype(np.uint8)
                output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
                output_dict['detection_scores'] = output_dict['detection_scores'][0]
                if 'detection_masks' in output_dict:
                    output_dict['detection_masks'] = output_dict['detection_masks'][0]
        return output_dict

    for img in xa:
        image = Image.open(img)
    image_np = load_image_into_numpy_array(image)
    image_np_expanded = np.expand_dims(image_np, axis=0)
    # Actual detection.
    output_dict = run_inference_for_single_image(image_np, detection_graph)
    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        output_dict['detection_boxes'],
        output_dict['detection_classes'],
        output_dict['detection_scores'],
        category_index,
        instance_masks=output_dict.get('detection_masks'),
        use_normalized_coordinates=True,
        line_thickness=8)

    # get_image_data = image_url(sys.argv[1],sys.argv[2])
    # image_file = get_image_data['image']

    # pass values

    import cv2 as cv

    image_file = image_path
    img = cv.imread('image_file')
    i = 0
    j = 0
    limiter = 0.3

    while (i < 100):
        if (output_dict['detection_scores'][i] > limiter):
            j = j + 1
        i = i + 1

    # In[17]:

    # store the pass values in lists
    i = 0
    detection_classes = []
    detection_boxes = [[]] * j
    detection_scores = []
    while (i < j):
        detection_classes.append(output_dict['detection_classes'][i])
        detection_scores.append(output_dict['detection_scores'][i])
        detection_boxes[i].append(output_dict['detection_boxes'][i])
        i = i + 1

    list1 = []
    for items in detection_classes:
        if items == 1:
            list1.append("Angry")
        elif items == 2:
            list1.append("Sad")
        elif items == 3:
            list1.append("Neutral")
        elif items == 4:
            list1.append("Happy")

    final_dict = {'DETECTION': list1}

    file_to_write_to = get_image_data['file'].name
    file_to_write_to = str(file_to_write_to)
    text_file = open(file_to_write_to, "w")
    text_file.write(json.dumps(final_dict))
    text_file.close()
    final_path = "images/" + str(ya) + "_annotated" + ".jpg"

    # draw bounding boxes
    img = cv.imread('xa')
    i = 0
    for item in detection_classes:
        width, height = image.size
        ymin = int(detection_boxes[0][i][0] * height)
        xmin = int(detection_boxes[0][i][1] * width)
        ymax = int(detection_boxes[0][i][2] * height)
        xmax = int(detection_boxes[0][i][3] * width)
        font = cv.FONT_HERSHEY_SIMPLEX
        panel_colour = (182, 182, 42)
        bumper_colour = (241, 239, 236)
        damage_colour = (0, 255, 0)
        text_colour = (255, 255, 255)
        bumper_text = (0, 0, 0)
        buffer = int(5 * width / 1000)
        if (detection_classes[i] == 1):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
            cv.putText(img, 'angry', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
                       int(2 * (height / 400)), cv.LINE_AA)
        elif (detection_classes[i] == 2):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
            cv.putText(img, 'sad', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
                       int(2 * (height / 400)), cv.LINE_AA)
        elif (detection_classes[i] == 3):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), bumper_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), bumper_colour, -1)
            cv.putText(img, 'neutral', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), bumper_text,
                       int(2 * (height / 400)), cv.LINE_AA)
        elif (detection_classes[i] == 4):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
            cv.putText(img, 'happy', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
                       int(2 * (height / 400)), cv.LINE_AA)
        i = i + 1

    final_path = "/home/mayureshk/PycharmProjects/ImageDetection/venv/models/research/object_detection/images/" + str(ya) + "_annotated" + ".jpg"
    cv.imwrite(final_path, img)
</code>```

Stuck on this problem since 2 days and i am unable to solve it by myself. Need help from an OpenCV expert.. What exactly am I doing wrong here?

答:
Try to print your image and check if it is None or corrupted.

```<code>import cv2 as cv

image_file = image_path
img = cv.imread('image_file') # here is mistake image_file  is variable but you have taken it as string.
</code>```

cv2.imread('image_file')
try with
cv2.imread(image_file)

Body:
I am not able to understand what type of error this is..i have written a python script which accepts image input from the user and runs emotion detection.
here's the code:

import numpy as np
import os
import sys
import tensorflow as tf
import json
from PIL import Image

sys.path.append("..")
from object_detection.utils import ops as utils_ops

from utils import label_map_util
from utils import visualization_utils as vis_util

def Image_tensorflow(xa,ya):
    PATH_TO_FROZEN_GRAPH = 'frozen_inference_graph.pb'
    PATH_TO_LABELS = 'object-detection.pbtxt'
    NUM_CLASSES = 4

    detection_graph = tf.Graph()
    with detection_graph.as_default():
        od_graph_def = tf.GraphDef()
        with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
            serialized_graph = fid.read()
            od_graph_def.ParseFromString(serialized_graph)
            tf.import_graph_def(od_graph_def, name='')

    label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
    categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
                                                                use_display_name=True)
    category_index = label_map_util.create_category_index(categories)

    def load_image_into_numpy_array(image):
        (im_width, im_height) = image.size
        return np.array(image.getdata()).reshape(
            (im_height, im_width, 3)).astype(np.uint8)

    def image_url(xa, ya):
        file_path = 'images/'
        file_name = ya
        image = xa
        f = open((file_path + str(file_name) + ".json"), "w")
        f.close
        return_dict = {'image': image, 'file': f};
        return return_dict

    get_image_data = image_url(xa,ya)
    image_path= get_image_data['image']

    IMAGE_SIZE = (12, 8)

    def run_inference_for_single_image(image, graph):
        with graph.as_default():
            with tf.Session() as sess:
                # Get handles to input and output tensors
                ops = tf.get_default_graph().get_operations()
                all_tensor_names = {output.name for op in ops for output in op.outputs}
                tensor_dict = {}
                for key in [
                    'num_detections', 'detection_boxes', 'detection_scores',
                    'detection_classes', 'detection_masks'
                ]:
                    tensor_name = key + ':0'
                    if tensor_name in all_tensor_names:
                        tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                            tensor_name)
                if 'detection_masks' in tensor_dict:
                    # The following processing is only for single image
                    detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
                    detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
                    # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
                    real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
                    detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
                    detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
                    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                        detection_masks, detection_boxes, image.shape[0], image.shape[1])
                    detection_masks_reframed = tf.cast(
                        tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                    tensor_dict['detection_masks'] = tf.expand_dims(
                        detection_masks_reframed, 0)
                image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

                output_dict = sess.run(tensor_dict,
                                       feed_dict={image_tensor: np.expand_dims(image, 0)})

                output_dict['num_detections'] = int(output_dict['num_detections'][0])
                output_dict['detection_classes'] = output_dict[
                    'detection_classes'][0].astype(np.uint8)
                output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
                output_dict['detection_scores'] = output_dict['detection_scores'][0]
                if 'detection_masks' in output_dict:
                    output_dict['detection_masks'] = output_dict['detection_masks'][0]
        return output_dict

    for img in xa:
        image = Image.open(img)
    image_np = load_image_into_numpy_array(image)
    image_np_expanded = np.expand_dims(image_np, axis=0)
    # Actual detection.
    output_dict = run_inference_for_single_image(image_np, detection_graph)
    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        output_dict['detection_boxes'],
        output_dict['detection_classes'],
        output_dict['detection_scores'],
        category_index,
        instance_masks=output_dict.get('detection_masks'),
        use_normalized_coordinates=True,
        line_thickness=8)

    # get_image_data = image_url(sys.argv[1],sys.argv[2])
    # image_file = get_image_data['image']

    # pass values

    import cv2 as cv

    image_file = image_path
    img = cv.imread('image_file')
    i = 0
    j = 0
    limiter = 0.3

    while (i < 100):
        if (output_dict['detection_scores'][i] > limiter):
            j = j + 1
        i = i + 1

    # In[17]:

    # store the pass values in lists
    i = 0
    detection_classes = []
    detection_boxes = [[]] * j
    detection_scores = []
    while (i < j):
        detection_classes.append(output_dict['detection_classes'][i])
        detection_scores.append(output_dict['detection_scores'][i])
        detection_boxes[i].append(output_dict['detection_boxes'][i])
        i = i + 1

    list1 = []
    for items in detection_classes:
        if items == 1:
            list1.append("Angry")
        elif items == 2:
            list1.append("Sad")
        elif items == 3:
            list1.append("Neutral")
        elif items == 4:
            list1.append("Happy")

    final_dict = {'DETECTION': list1}

    file_to_write_to = get_image_data['file'].name
    file_to_write_to = str(file_to_write_to)
    text_file = open(file_to_write_to, "w")
    text_file.write(json.dumps(final_dict))
    text_file.close()
    final_path = "images/" + str(ya) + "_annotated" + ".jpg"

    # draw bounding boxes
    img = cv.imread('xa')
    i = 0
    for item in detection_classes:
        width, height = image.size
        ymin = int(detection_boxes[0][i][0] * height)
        xmin = int(detection_boxes[0][i][1] * width)
        ymax = int(detection_boxes[0][i][2] * height)
        xmax = int(detection_boxes[0][i][3] * width)
        font = cv.FONT_HERSHEY_SIMPLEX
        panel_colour = (182, 182, 42)
        bumper_colour = (241, 239, 236)
        damage_colour = (0, 255, 0)
        text_colour = (255, 255, 255)
        bumper_text = (0, 0, 0)
        buffer = int(5 * width / 1000)
        if (detection_classes[i] == 1):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
            cv.putText(img, 'angry', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
                       int(2 * (height / 400)), cv.LINE_AA)
        elif (detection_classes[i] == 2):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
            cv.putText(img, 'sad', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
                       int(2 * (height / 400)), cv.LINE_AA)
        elif (detection_classes[i] == 3):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), bumper_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), bumper_colour, -1)
            cv.putText(img, 'neutral', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), bumper_text,
                       int(2 * (height / 400)), cv.LINE_AA)
        elif (detection_classes[i] == 4):
            img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), panel_colour, int(2 * (height / 600)))
            cv.rectangle(img, (xmin, (ymin + (buffer * 8))), (xmax, ymin), panel_colour, -1)
            cv.putText(img, 'happy', (xmin, (ymin + (buffer * 6))), font, 0.8 * (height / 500), text_colour,
                       int(2 * (height / 400)), cv.LINE_AA)
        i = i + 1

    final_path = "/home/mayureshk/PycharmProjects/ImageDetection/venv/models/research/object_detection/images/" + str(ya) + "_annotated" + ".jpg"
    cv.imwrite(final_path, img)

Stuck on this problem since 2 days and i am unable to solve it by myself. Need help from an OpenCV expert.. What exactly am I doing wrong here?

Body:
Try to print your image and check if it is None or corrupted.

import cv2 as cv

image_file = image_path
img = cv.imread('image_file') # here is mistake image_file  is variable but you have taken it as string.

cv2.imread('image_file')
try with
cv2.imread(image_file)


问:
How to use ISNULL on multiple fields in a Infromatica filter condition?
I have scenario where i have to check for the null values in multiple fields based on that i informatica should whether to load the record into target or not.

Example: I have col1, col2,col3,col4 fields. If any of these fields isnull then ignore that record else load the record.

Please suggest me how to approach this scenario.

TIA!

答:
Create an expression with an output field named e.g. ToBeRemoved with the following expression:

```<code>DECODE(TRUE,
ISNULL(col1), 1,
ISNULL(col2), 1,
ISNULL(col3), 1,
...
ISNULL(colN), 1,
0)
</code>```

Next use a filter with a condition ToBeRemoved=0.

Body:
Create an expression with an output field named e.g. ToBeRemoved with the following expression:

DECODE(TRUE,
ISNULL(col1), 1,
ISNULL(col2), 1,
ISNULL(col3), 1,
...
ISNULL(colN), 1,
0)

Next use a filter with a condition ToBeRemoved=0.


问:
Send html email with multiple embedded images using python script
I am newbie to Python. I wanted to send html based email with multiple embedded images

With the following code the email is absolutely working but able to view only one embedded image and another one as undefined

```<code>def addMultipleEmbeddedImages(self, nbMsg=1):

        attachedFiles = ["giga_logo_300x225.png", "phone_logo.jpg"]

        self.imgHtml = ""

        for file1 in attachedFiles:
            file = os.path.join(pathToAttachments, file1)

            self.__msg = MIMEMultipart('related')

            self.imgHtml +='<p <u>Embedded Images</u></p><br><img src="cid:%s"><br>'%file

            self.__msg.attach(MIMEText(self.imgHtml, 'html'))

            fp = open(file, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()

            msgImage.add_header('Content-ID', '<%s>'%file)
            self.__msg.attach(msgImage)

        self.__fillInAddressFields()

        # Attach the email in the body
        self.__buildBody(self.__msg)

        # Send the email with the embedded image
        self.__sendMessages(nbMsg)

        return
</code>```

答:
```<code>msgImage = MIMEImage(fp.read(),name = os.path.basename(file1))
</code>```

here i set the name for every image.

Body:
I am newbie to Python. I wanted to send html based email with multiple embedded images

With the following code the email is absolutely working but able to view only one embedded image and another one as undefined

def addMultipleEmbeddedImages(self, nbMsg=1):

        attachedFiles = ["giga_logo_300x225.png", "phone_logo.jpg"]

        self.imgHtml = ""

        for file1 in attachedFiles:
            file = os.path.join(pathToAttachments, file1)

            self.__msg = MIMEMultipart('related')

            self.imgHtml +='<p Embedded Images

'%file

            self.__msg.attach(MIMEText(self.imgHtml, 'html'))

            fp = open(file, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()

            msgImage.add_header('Content-ID', '<%s>'%file)
            self.__msg.attach(msgImage)

        self.__fillInAddressFields()

        # Attach the email in the body
        self.__buildBody(self.__msg)

        # Send the email with the embedded image
        self.__sendMessages(nbMsg)

        return

Body:
msgImage = MIMEImage(fp.read(),name = os.path.basename(file1))

here i set the name for every image.


问:
window.onload vs $(document).ready()
What are the differences between JavaScript's window.onload and jQuery's $(document).ready() method?

答:
window.onload is provided by DOM api and it says " the load event fires when a given resource has loaded".

"The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading."
DOM onload

But in jQuery $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. This does not include images, scripts, iframes etc. jquery ready event

So the jquery ready method will run earlier than the dom onload event.

Title: window.onload vs $(document).ready()


问:
Create new columns for duplicate row values based on column ID duplicate in sql
I have a table with 2 columns, the first column is called ID and the second is called TRACKING. The ID column has duplicates, I want to to take all of those duplicates and consolidate them into one row where each value from TRACKING from the duplicate row is placed into a new column within the same row and I no longer have duplicates.

I have tried a few suggested things where all of the values would be concatenated into one column but I want these TRACKING values for the duplicate IDs to be in separate columns. The code below did not do what I intended it to.

```<code>SELECT ID, TRACKING =
    STUFF((SELECT DISTINCT ', ' + TRACKING
       FROM #t b
       WHERE b.ID = a.ID
      FOR XML PATH('')), 1, 2, '')
FROM #t a
GROUP BY ID
</code>```

I am looking to take this:

```<code>| ID | TRACKING |
-----------------
| 5  | 13t3in3i |
| 5  | g13g13gg |
| 3  | egqegqgq |
| 2  | 14y2y24y |
| 2  | 42yy44yy |
| 5  | 8i535i35 |
</code>```

And turn it into this:

```<code>| ID |  TRACKING  | TRACKING1 | TRACKING2 |
-----------------
| 5  |  13t3in3i  | g13g13gg  | 8i535i35  |
| 3  |  egqegqgq  |           |           |
| 2  |  14y2y24y  | 42yy44yy  |           |
</code>```

答:
```<code>with test_tbl as
(
    select 5 id, 'goog' tracking,'goog' tracking1
    union all
    select 5 id, 'goog1','goo'
    union all
    select 2 , 'yahoo','yah'
    union all
    select 2, 'yahoo1','ya'
    union all
    select 3,'azure','azu'
), modified_tbl as
(
    select id,array_agg(concat(tracking)) Tracking,array_agg(concat(tracking1)) Tracking1 from test_tbl group by 1
)

select id, tracking[safe_offset(0)]  Tracking_1,tracking1[safe_offset(0)]  Tracking_2, tracking[safe_offset(1)] Tracking_3,tracking1[safe_offset(1)] Tracking_4 from modified_tbl where array_length(Tracking) > 1
</code>```

Body:
I have a table with 2 columns, the first column is called ID and the second is called TRACKING. The ID column has duplicates, I want to to take all of those duplicates and consolidate them into one row where each value from TRACKING from the duplicate row is placed into a new column within the same row and I no longer have duplicates.

I have tried a few suggested things where all of the values would be concatenated into one column but I want these TRACKING values for the duplicate IDs to be in separate columns. The code below did not do what I intended it to.

SELECT ID, TRACKING =
    STUFF((SELECT DISTINCT ', ' + TRACKING
       FROM #t b
       WHERE b.ID = a.ID
      FOR XML PATH('')), 1, 2, '')
FROM #t a
GROUP BY ID

I am looking to take this:

| ID | TRACKING |
-----------------
| 5  | 13t3in3i |
| 5  | g13g13gg |
| 3  | egqegqgq |
| 2  | 14y2y24y |
| 2  | 42yy44yy |
| 5  | 8i535i35 |

And turn it into this:

| ID |  TRACKING  | TRACKING1 | TRACKING2 |
-----------------
| 5  |  13t3in3i  | g13g13gg  | 8i535i35  |
| 3  |  egqegqgq  |           |           |
| 2  |  14y2y24y  | 42yy44yy  |           |


问:
Explicit line joining in Python
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

```<code>file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))
</code>```

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

答:
there are several ways to do this. for example just using + should do the trick.

"abc" + "def" # produces "abcdef"

If you try to concatenate multiple strings you can do this with the join method:

```<code>', '.join(('abc', 'def', 'ghi')) # produces 'abc, def, ghi'
</code>```

If you want no delimiter, use the empty string ''.join() method.

Title: Explicit line joining in Python

Body:
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

Body:
there are several ways to do this. for example just using + should do the trick.

"abc" + "def" # produces "abcdef"

If you try to concatenate multiple strings you can do this with the join method:

', '.join(('abc', 'def', 'ghi')) # produces 'abc, def, ghi'

If you want no delimiter, use the empty string ''.join() method.


问:
why in the for loop in the example below the result isn't the same exactly in the second for loop in each of the two examples
Alliteration refers to a sequence of words that begin with the same letter. For this exercise, a sentence is correctly alliterated if all words strictly greater than 3 characters begin with the same letter.

Examples:

```<code>alliteration_correct("She swam to the shore.") ➞ True
# All words >= 4 letters long begins with "s"

alliteration_correct("Maybel manages money well.") ➞ False
# "well" does not begin with an "m"

alliteration_correct("He helps harness happiness.") ➞ True

alliteration_correct("There are many animals.") ➞ False
</code>```

Notes:

```<code>def alliteration_correct(sentence):
    sentence = sentence.split(" ")
    ll = []
    for i in sentence:
        if len(i) > 3:
            ll.append(i)
    for x in ll:
        if x.lower()[0] == ll[0][0].lower():
            return True
    return False

print(alliteration_correct("He helps harness happiness."))

print(alliteration_correct("There are many animals."))

</code>```

```<code>def alliteration_correct(sentence):
    sentence = sentence.split(" ")
    ll = []
    for i in sentence:
        if len(i) > 3:
            ll.append(i)
    for x in ll:
        if x.lower()[0] != ll[0][0].lower():
            return False
    return True

print(alliteration_correct("He helps harness happiness."))

print(alliteration_correct("There are many animals."))

</code>```

答:
What you seem to be doing is check for the occurrence of first character of the words with length greater than 3.

The case where you return false for a mismatch is valid as you don't need to check any further, and you return false simply.
But in the opposite returning true for just making a check for the first word of length > 3, is not valid.

This makes logic different.
Hope it helps.

Body:
Alliteration refers to a sequence of words that begin with the same letter. For this exercise, a sentence is correctly alliterated if all words strictly greater than 3 characters begin with the same letter.

Examples:

alliteration_correct("She swam to the shore.") ➞ True
# All words >= 4 letters long begins with "s"

alliteration_correct("Maybel manages money well.") ➞ False
# "well" does not begin with an "m"

alliteration_correct("He helps harness happiness.") ➞ True

alliteration_correct("There are many animals.") ➞ False

Notes:

def alliteration_correct(sentence):
    sentence = sentence.split(" ")
    ll = []
    for i in sentence:
        if len(i) > 3:
            ll.append(i)
    for x in ll:
        if x.lower()[0] == ll[0][0].lower():
            return True
    return False

print(alliteration_correct("He helps harness happiness."))

print(alliteration_correct("There are many animals."))

def alliteration_correct(sentence):
    sentence = sentence.split(" ")
    ll = []
    for i in sentence:
        if len(i) > 3:
            ll.append(i)
    for x in ll:
        if x.lower()[0] != ll[0][0].lower():
            return False
    return True

print(alliteration_correct("He helps harness happiness."))

print(alliteration_correct("There are many animals."))


问:
Flutter - Error compiling application after upgrading Flutter
I've had problems compiling my application since I upgraded Flutter from v1.9.1+hotfix.2 to v1.14.7-pre.113. I've looked online for a few days now and I haven't been able to find anybody who's getting the same problem. I don't really know what's wrong and I can't seem to find anything, I'm hoping someone who comes across this might know what's wrong.

This is the error I'm getting in the debug console:

```<code>Compiler message:
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_storage_image-0.4.0/lib/firebase_storage_image.dart:54:24: Error: The method 'FirebaseStorageImage.load' has fewer positional arguments than those of overridden method 'ImageProvider.load'.
  ImageStreamCompleter load(FirebaseStorageImage key) =>
                       ^
/C:/src/flutter/packages/flutter/lib/src/painting/image_provider.dart:489:24: Context: This is the overridden method ('load').
  ImageStreamCompleter load(T key, DecoderCallback decode);
                       ^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 803

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 40s
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

Here's my pubspec.yaml:

```<code>name: orders_app
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  carousel_pro: ^1.0.0
  flutter_signin_button: ^1.0.0
  provider: ^4.0.3
  scoped_model: ^1.0.1
  shared_preferences: ^0.5.6
  firebase_auth: ^0.15.3
  cloud_firestore: ^0.13.0+1
  firebase_storage_image: ^0.4.0
  google_sign_in: ^4.1.1

  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter
</code>```

答:
You should see what new version of Flutter needs Gridel. So you better create a new project with a new version of Flutter then see what changes have been made to your project in the build.gradle , gradle-wrapper.properties , gradle.properties files.
and use flutter clean.

Body:
I've had problems compiling my application since I upgraded Flutter from v1.9.1+hotfix.2 to v1.14.7-pre.113. I've looked online for a few days now and I haven't been able to find anybody who's getting the same problem. I don't really know what's wrong and I can't seem to find anything, I'm hoping someone who comes across this might know what's wrong.

This is the error I'm getting in the debug console:

Compiler message:
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_storage_image-0.4.0/lib/firebase_storage_image.dart:54:24: Error: The method 'FirebaseStorageImage.load' has fewer positional arguments than those of overridden method 'ImageProvider.load'.
  ImageStreamCompleter load(FirebaseStorageImage key) =>
                       ^
/C:/src/flutter/packages/flutter/lib/src/painting/image_provider.dart:489:24: Context: This is the overridden method ('load').
  ImageStreamCompleter load(T key, DecoderCallback decode);
                       ^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 803

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 40s
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

Here's my pubspec.yaml:

name: orders_app
description: A new Flutter project.

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  carousel_pro: ^1.0.0
  flutter_signin_button: ^1.0.0
  provider: ^4.0.3
  scoped_model: ^1.0.1
  shared_preferences: ^0.5.6
  firebase_auth: ^0.15.3
  cloud_firestore: ^0.13.0+1
  firebase_storage_image: ^0.4.0
  google_sign_in: ^4.1.1

  cupertino_icons: ^0.1.2

dev_dependencies:
  flutter_test:
    sdk: flutter


问:
How to read data from file for NetworkX graph
I am having issues trying to read in the following data from a file into NetworkX to build a graph.

Example Data:

The pipe '|' separates the source node (user) from the destination nodes (users). As an example  entry:

s1|d1,d2,d3

means that there is an edge between user s1 and user d1, and there is also an edge between user s1 and user d2, etc.

答:
You can use str.split() to split the lines and parse accordingly. Example:</p>

```<code>G = nx.Graph()
with open('g.txt') as f:
   for line in f:
      u, destinations = line.split('|')
         for v in destinations.split(','):
            G.add_edge(u,v)
</code>```

Body:
You can use str.split() to split the lines and parse accordingly. Example:

G = nx.Graph()
with open('g.txt') as f:
   for line in f:
      u, destinations = line.split('|')
         for v in destinations.split(','):
            G.add_edge(u,v)


问:
Document and Graph database choices
I have needs for my system:

1) Friends - need to calculate distance between users upto N degrees, find work related common items between users. Can't scale this onmysql well. So the choice i assume is a Graph database?

2) I have user profile fields, about 120 fields with 80% of them being 1:M fields, so in mysql this means about 96 tables to store the 1:M. If i need to pull all user info then i need to reach all these tables. So a solution here is a document database, colunm database or key value database?

Currently I have seen OrientDB which can act as a document and graph database. Can this be used for the above needs or are there better DB options for this?

Thanks.

EDIT:
Req for Profile is User fields: IT is career social network so lots of portfolia like fields which are 1:M. So if there are 120 fields with 96 of them being 1:M how best to store it? Exqample is Companies you worked at. Schools you studied at. Magazines you read. Articles you have written, etc. Each of these are 1:M and there are 96ish fields like this = 96 Mysql tables. I cannot combine because some of these have unique metadata. I need to search on the fields and allow for quick read to keep user experience good.

For graphing: It is about connecting people. For launch I am only using one feature that is when yu view someone the system will say how many degrees seperate you from the person. Rest of 'social' features are for post launch. Eitherways in MySQL I cant do this well enough to scale. IF I have 100 friends and each person as 100 friends and so forst how to best find my way around these people, i assume a graph DB.

Platform is codeignitor PHP / Mysql for core DB.

答:
Calculate distance between nodes sounds a lot like graph database. OrientDB looks very impressive, I personally have played around with Neo4j, which you might have a look at.

To give a definitive answer, you would have to provide more of your requirements.

Title: Document and Graph database choices


问:
How can I get table name from passed parameter in Oracle DB?
I created a function in oracle db with (In parameter), the parameter determined what table that I passed when calling the function, so I need to get table name from the parameter and use it in my query inside function. Example as below:</p>

```<code>CREATE OR REPLACE TYPE EMP_OBJ_TYPE AS OBJECT

(

column1 varchar2(20),

column2 varchar2(20),

column3 varchar2(20)

)
;

CREATE OR REPLACE TYPE EMP_TBL_TYPE IS TABLE OF EMP_OBJ_TYPE;

CREATE OR REPLACE FUNCTION EMPLOYEE_FUNCTION (table_name varchar2)

RETURN EMP_TBL_TYPE IS

EMP_DETAILS EMP_TBL_TYPE := EMP_TBL_TYPE();

BEGIN

EMP_DETAILS.EXTEND();

SELECT EMP_OBJ_TYPE (column1, column2, colmn3)

BULK COLLECT
INTO EMP_DETAILS

FROM (SELECT column1, column2, column3

From emloyees a

join table_name b

on a.emp_id = b.emp_id);

RETURN EMP_DETAILS;

END;
</code>```

答:
You'll need dynamic SQL for that. Here's how: I'm using Scott's sample schema, trying to mimic what you have.

```<code>SQL> CREATE TABLE employees
  2  AS
  3     SELECT deptno emp_id,
  4            ename column1,
  5            job column2,
  6            TO_CHAR (hiredate, 'dd.mm.yyyy') column3
  7       FROM emp;

Table created.
</code>```

Your types:

```<code>SQL> CREATE OR REPLACE TYPE emp_obj_type AS OBJECT
  2  (
  3     column1 VARCHAR2 (20),
  4     column2 VARCHAR2 (20),
  5     column3 VARCHAR2 (20)
  6  );
  7  /

Type created.

SQL> CREATE OR REPLACE TYPE emp_tbl_type IS TABLE OF emp_obj_type;
  2  /

Type created.
</code>```

Function: it is a good idea to first display statement you're about to execute, to visually verify it is correct (line #14); remove it when it is not needed any more.

```<code>SQL> CREATE OR REPLACE FUNCTION employee_function (par_table_name VARCHAR2)
  2     RETURN emp_tbl_type
  3  IS
  4     emp_details  emp_tbl_type := emp_tbl_type ();
  5     l_str        VARCHAR2 (1000);
  6  BEGIN
  7     l_str :=
  8           'SELECT EMP_OBJ_TYPE (column1, column2, column3) '
  9        || '  FROM (SELECT column1, column2, column3 '
 10        || '        FROM employees a JOIN '
 11        || par_table_name
 12        || ' b ON a.emp_id = b.deptno)';
 13
 14     -- DBMS_OUTPUT.put_line (l_str);
 15
 16     EXECUTE IMMEDIATE l_str BULK COLLECT INTO emp_details;
 17
 18     RETURN emp_details;
 19  END;
 20  /

Function created.
</code>```

Testing:

```<code>SQL> SELECT employee_function ('dept') FROM DUAL;

EMPLOYEE_FUNCTION('DEPT')(COLUMN1, COLUMN2, COLUMN3)
--------------------------------------------------------------------------------
EMP_TBL_TYPE(EMP_OBJ_TYPE('SMITH', 'CLERK', '17.12.1980'), EMP_OBJ_TYPE('ALLEN',
 'SALESMAN', '20.02.1981'), EMP_OBJ_TYPE('WARD', 'SALESMAN', '22.02.1981'), EMP_
OBJ_TYPE('JONES', 'MANAGER', '02.04.1981'), EMP_OBJ_TYPE('MARTIN', 'SALESMAN', '
28.09.1981'), EMP_OBJ_TYPE('BLAKE', 'MANAGER', '01.05.1981'), EMP_OBJ_TYPE('CLAR
K', 'MANAGER', '09.06.1981'), EMP_OBJ_TYPE('SCOTT', 'ANALYST', '09.12.1982'), EM
P_OBJ_TYPE('KING', 'PRESIDENT', '17.11.1981'), EMP_OBJ_TYPE('TURNER', 'SALESMAN'
, '08.09.1981'), EMP_OBJ_TYPE('ADAMS', 'CLERK', '12.01.1983'), EMP_OBJ_TYPE('JAM
ES', 'CLERK', '03.12.1981'), EMP_OBJ_TYPE('FORD', 'ANALYST', '03.12.1981'), EMP_
OBJ_TYPE('MILLER', 'CLERK', '23.01.1982'))

SQL>
</code>```

Body:
I created a function in oracle db with (In parameter), the parameter determined what table that I passed when calling the function, so I need to get table name from the parameter and use it in my query inside function. Example as below:

CREATE OR REPLACE TYPE EMP_OBJ_TYPE AS OBJECT

(

column1 varchar2(20),

column2 varchar2(20),

column3 varchar2(20)

)
;

CREATE OR REPLACE TYPE EMP_TBL_TYPE IS TABLE OF EMP_OBJ_TYPE;

CREATE OR REPLACE FUNCTION EMPLOYEE_FUNCTION (table_name varchar2)

RETURN EMP_TBL_TYPE IS

EMP_DETAILS EMP_TBL_TYPE := EMP_TBL_TYPE();

BEGIN

EMP_DETAILS.EXTEND();

SELECT EMP_OBJ_TYPE (column1, column2, colmn3)

BULK COLLECT
INTO EMP_DETAILS

FROM (SELECT column1, column2, column3

From emloyees a

join table_name b

on a.emp_id = b.emp_id);

RETURN EMP_DETAILS;

END;

Body:
You'll need dynamic SQL for that. Here's how: I'm using Scott's sample schema, trying to mimic what you have.

SQL> CREATE TABLE employees
  2  AS
  3     SELECT deptno emp_id,
  4            ename column1,
  5            job column2,
  6            TO_CHAR (hiredate, 'dd.mm.yyyy') column3
  7       FROM emp;

Table created.

Your types:

SQL> CREATE OR REPLACE TYPE emp_obj_type AS OBJECT
  2  (
  3     column1 VARCHAR2 (20),
  4     column2 VARCHAR2 (20),
  5     column3 VARCHAR2 (20)
  6  );
  7  /

Type created.

SQL> CREATE OR REPLACE TYPE emp_tbl_type IS TABLE OF emp_obj_type;
  2  /

Type created.

Function: it is a good idea to first display statement you're about to execute, to visually verify it is correct (line #14); remove it when it is not needed any more.

SQL> CREATE OR REPLACE FUNCTION employee_function (par_table_name VARCHAR2)
  2     RETURN emp_tbl_type
  3  IS
  4     emp_details  emp_tbl_type := emp_tbl_type ();
  5     l_str        VARCHAR2 (1000);
  6  BEGIN
  7     l_str :=
  8           'SELECT EMP_OBJ_TYPE (column1, column2, column3) '
  9        || '  FROM (SELECT column1, column2, column3 '
 10        || '        FROM employees a JOIN '
 11        || par_table_name
 12        || ' b ON a.emp_id = b.deptno)';
 13
 14     -- DBMS_OUTPUT.put_line (l_str);
 15
 16     EXECUTE IMMEDIATE l_str BULK COLLECT INTO emp_details;
 17
 18     RETURN emp_details;
 19  END;
 20  /

Function created.

Testing:

SQL> SELECT employee_function ('dept') FROM DUAL;

EMPLOYEE_FUNCTION('DEPT')(COLUMN1, COLUMN2, COLUMN3)
--------------------------------------------------------------------------------
EMP_TBL_TYPE(EMP_OBJ_TYPE('SMITH', 'CLERK', '17.12.1980'), EMP_OBJ_TYPE('ALLEN',
 'SALESMAN', '20.02.1981'), EMP_OBJ_TYPE('WARD', 'SALESMAN', '22.02.1981'), EMP_
OBJ_TYPE('JONES', 'MANAGER', '02.04.1981'), EMP_OBJ_TYPE('MARTIN', 'SALESMAN', '
28.09.1981'), EMP_OBJ_TYPE('BLAKE', 'MANAGER', '01.05.1981'), EMP_OBJ_TYPE('CLAR
K', 'MANAGER', '09.06.1981'), EMP_OBJ_TYPE('SCOTT', 'ANALYST', '09.12.1982'), EM
P_OBJ_TYPE('KING', 'PRESIDENT', '17.11.1981'), EMP_OBJ_TYPE('TURNER', 'SALESMAN'
, '08.09.1981'), EMP_OBJ_TYPE('ADAMS', 'CLERK', '12.01.1983'), EMP_OBJ_TYPE('JAM
ES', 'CLERK', '03.12.1981'), EMP_OBJ_TYPE('FORD', 'ANALYST', '03.12.1981'), EMP_
OBJ_TYPE('MILLER', 'CLERK', '23.01.1982'))

SQL>


问:
Can we use soft assert in Junit as like TestNG...?
Can we use soft assert in Junit as like TestNG:

I dont want to fail my Test Case if Assert Condition fail

Any way to solve this use case

答:
Yes we can do:

```<code>softAssertions = new SoftAssertions();
</code>```

Body:
Yes we can do:

softAssertions = new SoftAssertions();


问:
How to list names of all pods serving traffic behind a service in kubernetes
I want to list names of all pods which are actually serving traffic behind a kubernetes service.My question is how to achieve this by executing a single kubectl command.</p>

答:
There are two ways to list the pods behind a service.

The easier way but with two commands

Find the selector by running the below command

```<code>kubectl get services -o=wide
</code>```

Output:

```<code>NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE   SELECTOR
hello-world-service   ClusterIP   172.21.xxx.xx   <none>        80/TCP    13m   run=nginx
</code>```

Pass the selector to the command below

```<code>kubectl get pods --selector=run=nginx -o=name
</code>```

To see the exact pod names without pod/

```<code>kubectl get pods --selector=run=nginx  --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
</code>```

In a single command but using the endpoints information for the service hello-world-service

```<code>kubectl get endpoints hello-world-service -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
</code>```

Body:
There are two ways to list the pods behind a service.

The easier way but with two commands

Find the selector by running the below command

kubectl get services -o=wide

Output:

NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE   SELECTOR
hello-world-service   ClusterIP   172.21.xxx.xx   <none>        80/TCP    13m   run=nginx

Pass the selector to the command below

kubectl get pods --selector=run=nginx -o=name

To see the exact pod names without pod/

kubectl get pods --selector=run=nginx  --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'

In a single command but using the endpoints information for the service hello-world-service

kubectl get endpoints hello-world-service -o=jsonpath='{.subsets[*].addresses[*].ip}' | tr ' ' '\n' | kubectl get pods --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'