问:
create a dictionary combining other dictionaries python
I have two dictionaries of the type:

```<code>dict1 = {NTID: (ID, CN)}

dict2 = {NTID: INCHI}
</code>```

and I want to get:

```<code>dict3 = {NTID: (ID, CN, INCHI)}
</code>```

I have tried to use zip, as follows:

```<code>dict_3 = dict(zip(dict1, dict2))
</code>```

BUt I get NTID as keys and values. Please note that there are multiple values per each dictionary, but the order of the values between dict1 and dict2 is consistent

EDIT:

An example from dict1 is (keys: '1-4-HYDROXYPHENYL', '4-AMINO-BUTYRATE', 'ACETYLCHOLINE', 'ASN')

```<code>{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'),
  ('172', 'alpha-ketoglutarate'),
  ('173', 'succinate'),
  ('399', 'Succinate semialdehyde'),
  ('111', 'putrescine'),
  ('114', '4-guanidinobutanoate'),
  ('115', '4-acetamidobutanoate')],
 'ACETYLCHOLINE': [],
 'ASN': [('1', 'glycine'),
  ('45', 'tyrosine'),
  ('74', 'leucine'),
  ('90', 'methionine'),
  ('80', 'valine')]}
</code>```

dict2:

```<code>{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)',
  'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2',
  'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2',
  'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1',
  'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2',
  'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)',
  'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'],
 'ACETYLCHOLINE': [],
 'ASN': ['InChI=1S/C9H11NO3',
  'InChI=1S/C9H11NO2/c10-8',
  'InChI=1S/C3H7NO2/c1-2(4)3(5)6',
  'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3',
  'InChI=1S/C4H9NO3/c1-2(6)3',
  'InChI=1S/C4H8N2O3/c5-2(4(8)',
  'InChI=1S/C6H13NO2/c1-3-4(2)',
  'InChI=1S/C6H9N3O2/c7-5(6(10)',
  'InChI=1S/C4H7NO4/c5-2(4(8)9)',
  'InChI=1S/C4H4O5/c5-2(4(8)9)1-',
  'InChI=1S/C3H7NO2S/c4-2(1-7)3(5)',
  'InChI=1S/C5H10N2O3/c6-3(5(9)'}
</code>```

dict3 (output) should look like:

```<code>{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)', 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)'),
  ('172', 'alpha-ketoglutarate', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'),
  ('173', 'succinate', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'),
  etc...
</code>```

答:
You can try this code:

```<code>dict1 = {'NTID': ('ID', 'CN')}

dict2 = {'NTID': 'INCHI'}

    final_dict={}
    for key,value in dict1.items():
        final_dict[key]=[value[0],value[1]]
        if key in dict2:
            final_dict[key].append(dict2.get(key))

    print(final_dict)
</code>```

output:

```<code>{'NTID': ['ID', 'CN', 'INCHI']}
</code>```

if you want result in tuple as you shown then:

```<code>final_dict={}
for key,value in dict1.items():
    final_dict[key]=value
    if key in dict2:
        final_dict[key]+=(dict2.get(key),)

print(final_dict)
</code>```

output:

```<code>{'NTID': ('ID', 'CN', 'INCHI')}
</code>```

second you can use defaultdict:

```<code>dict1 = {'NTID': ('ID', 'CN')}

dict2 = {'NTID': 'INCHI'}

from collections import defaultdict

d=defaultdict(list)
for item in (dict1,dict2):
    for key,value in item.items():
        d[key].append(value)

print(d)
</code>```

Updated as per question edit :

```<code>dict_1={'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'),
  ('172', 'alpha-ketoglutarate'),
  ('173', 'succinate'),
  ('399', 'Succinate semialdehyde'),
  ('111', 'putrescine'),
  ('114', '4-guanidinobutanoate'),
  ('115', '4-acetamidobutanoate')],
 'ACETYLCHOLINE': [],
 'ASN': [('1', 'glycine'),
  ('45', 'tyrosine'),
  ('74', 'leucine'),
  ('90', 'methionine'),
  ('80', 'valine')]}

dict_2={'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)',
  'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2',
  'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2',
  'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1',
  'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2',
  'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)',
  'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'],
 'ACETYLCHOLINE': [],
 'ASN': ['InChI=1S/C9H11NO3',
  'InChI=1S/C9H11NO2/c10-8',
  'InChI=1S/C3H7NO2/c1-2(4)3(5)6',
  'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3',
  'InChI=1S/C4H9NO3/c1-2(6)3',
  'InChI=1S/C4H8N2O3/c5-2(4(8)',
  'InChI=1S/C6H13NO2/c1-3-4(2)',
  'InChI=1S/C6H9N3O2/c7-5(6(10)',
  'InChI=1S/C4H7NO4/c5-2(4(8)9)',
  'InChI=1S/C4H4O5/c5-2(4(8)9)1-',
  'InChI=1S/C3H7NO2S/c4-2(1-7)3(5)',
  'InChI=1S/C5H10N2O3/c6-3(5(9)']}

final_dict={}
for key,value in dict_1.items():
    if key in dict_2:
        for zip_value in zip(value,dict_2.get(key)):
            if key not in final_dict:
                final_dict[key]=[zip_value]
            else:
                final_dict[key].append(zip_value)

print(final_dict)
</code>```

output:

```<code>{'ASN': [(('1', 'glycine'), 'InChI=1S/C9H11NO3'), (('45', 'tyrosine'), 'InChI=1S/C9H11NO2/c10-8'), (('74', 'leucine'), 'InChI=1S/C3H7NO2/c1-2(4)3(5)6'), (('90', 'methionine'), 'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3'), (('80', 'valine'), 'InChI=1S/C4H9NO3/c1-2(6)3')], '4-AMINO-BUTYRATE': [(('24', 'gamma-aminobutyrate (GABA)'), 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)'), (('172', 'alpha-ketoglutarate'), 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2'), (('173', 'succinate'), 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'), (('399', 'Succinate semialdehyde'), 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'), (('111', 'putrescine'), 'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2'), (('114', '4-guanidinobutanoate'), 'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)'), (('115', '4-acetamidobutanoate'), 'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1')]}
</code>```

Little modifed if you don't want those extra brackets :

```<code>final_dict={}
for key,value in dict_1.items():
    if key in dict_2:
        for zip_value in zip(value,dict_2.get(key)):

            if key not in final_dict:
                final_dict[key]=[zip_value[0][0],zip_value[0][1],zip_value[1]]
            else:
                final_dict[key].append((zip_value[0][0],zip_value[0][1],zip_value[1]))

print(final_dict)
</code>```

output:

```<code>{'ASN': ['1', 'glycine', 'InChI=1S/C9H11NO3', ('45', 'tyrosine', 'InChI=1S/C9H11NO2/c10-8'), ('74', 'leucine', 'InChI=1S/C3H7NO2/c1-2(4)3(5)6'), ('90', 'methionine', 'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3'), ('80', 'valine', 'InChI=1S/C4H9NO3/c1-2(6)3')], '4-AMINO-BUTYRATE': ['24', 'gamma-aminobutyrate (GABA)', 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)', ('172', 'alpha-ketoglutarate', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2'), ('173', 'succinate', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'), ('399', 'Succinate semialdehyde', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'), ('111', 'putrescine', 'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2'), ('114', '4-guanidinobutanoate', 'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)'), ('115', '4-acetamidobutanoate', 'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1')]}
</code>```

Body:
I have two dictionaries of the type:

dict1 = {NTID: (ID, CN)}

dict2 = {NTID: INCHI}

and I want to get:

dict3 = {NTID: (ID, CN, INCHI)}

I have tried to use zip, as follows:

dict_3 = dict(zip(dict1, dict2))

BUt I get NTID as keys and values. Please note that there are multiple values per each dictionary, but the order of the values between dict1 and dict2 is consistent

EDIT:

An example from dict1 is (keys: '1-4-HYDROXYPHENYL', '4-AMINO-BUTYRATE', 'ACETYLCHOLINE', 'ASN')

{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'),
  ('172', 'alpha-ketoglutarate'),
  ('173', 'succinate'),
  ('399', 'Succinate semialdehyde'),
  ('111', 'putrescine'),
  ('114', '4-guanidinobutanoate'),
  ('115', '4-acetamidobutanoate')],
 'ACETYLCHOLINE': [],
 'ASN': [('1', 'glycine'),
  ('45', 'tyrosine'),
  ('74', 'leucine'),
  ('90', 'methionine'),
  ('80', 'valine')]}

dict2:

{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)',
  'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2',
  'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2',
  'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1',
  'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2',
  'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)',
  'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'],
 'ACETYLCHOLINE': [],
 'ASN': ['InChI=1S/C9H11NO3',
  'InChI=1S/C9H11NO2/c10-8',
  'InChI=1S/C3H7NO2/c1-2(4)3(5)6',
  'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3',
  'InChI=1S/C4H9NO3/c1-2(6)3',
  'InChI=1S/C4H8N2O3/c5-2(4(8)',
  'InChI=1S/C6H13NO2/c1-3-4(2)',
  'InChI=1S/C6H9N3O2/c7-5(6(10)',
  'InChI=1S/C4H7NO4/c5-2(4(8)9)',
  'InChI=1S/C4H4O5/c5-2(4(8)9)1-',
  'InChI=1S/C3H7NO2S/c4-2(1-7)3(5)',
  'InChI=1S/C5H10N2O3/c6-3(5(9)'}

dict3 (output) should look like:

{'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)', 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)'),
  ('172', 'alpha-ketoglutarate', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'),
  ('173', 'succinate', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'),
  etc...

Body:
You can try this code:

dict1 = {'NTID': ('ID', 'CN')}

dict2 = {'NTID': 'INCHI'}

    final_dict={}
    for key,value in dict1.items():
        final_dict[key]=[value[0],value[1]]
        if key in dict2:
            final_dict[key].append(dict2.get(key))

    print(final_dict)

output:

{'NTID': ['ID', 'CN', 'INCHI']}

if you want result in tuple as you shown then:

final_dict={}
for key,value in dict1.items():
    final_dict[key]=value
    if key in dict2:
        final_dict[key]+=(dict2.get(key),)

print(final_dict)

output:

{'NTID': ('ID', 'CN', 'INCHI')}

second you can use defaultdict:

dict1 = {'NTID': ('ID', 'CN')}

dict2 = {'NTID': 'INCHI'}

from collections import defaultdict

d=defaultdict(list)
for item in (dict1,dict2):
    for key,value in item.items():
        d[key].append(value)

print(d)

Updated as per question edit :

dict_1={'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': [('24', 'gamma-aminobutyrate (GABA)'),
  ('172', 'alpha-ketoglutarate'),
  ('173', 'succinate'),
  ('399', 'Succinate semialdehyde'),
  ('111', 'putrescine'),
  ('114', '4-guanidinobutanoate'),
  ('115', '4-acetamidobutanoate')],
 'ACETYLCHOLINE': [],
 'ASN': [('1', 'glycine'),
  ('45', 'tyrosine'),
  ('74', 'leucine'),
  ('90', 'methionine'),
  ('80', 'valine')]}

dict_2={'1-4-HYDROXYPHENYL': [],
 '4-AMINO-BUTYRATE': ['InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)',
  'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2',
  'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2',
  'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1',
  'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2',
  'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)',
  'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1'],
 'ACETYLCHOLINE': [],
 'ASN': ['InChI=1S/C9H11NO3',
  'InChI=1S/C9H11NO2/c10-8',
  'InChI=1S/C3H7NO2/c1-2(4)3(5)6',
  'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3',
  'InChI=1S/C4H9NO3/c1-2(6)3',
  'InChI=1S/C4H8N2O3/c5-2(4(8)',
  'InChI=1S/C6H13NO2/c1-3-4(2)',
  'InChI=1S/C6H9N3O2/c7-5(6(10)',
  'InChI=1S/C4H7NO4/c5-2(4(8)9)',
  'InChI=1S/C4H4O5/c5-2(4(8)9)1-',
  'InChI=1S/C3H7NO2S/c4-2(1-7)3(5)',
  'InChI=1S/C5H10N2O3/c6-3(5(9)']}

final_dict={}
for key,value in dict_1.items():
    if key in dict_2:
        for zip_value in zip(value,dict_2.get(key)):
            if key not in final_dict:
                final_dict[key]=[zip_value]
            else:
                final_dict[key].append(zip_value)

print(final_dict)

output:

{'ASN': [(('1', 'glycine'), 'InChI=1S/C9H11NO3'), (('45', 'tyrosine'), 'InChI=1S/C9H11NO2/c10-8'), (('74', 'leucine'), 'InChI=1S/C3H7NO2/c1-2(4)3(5)6'), (('90', 'methionine'), 'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3'), (('80', 'valine'), 'InChI=1S/C4H9NO3/c1-2(6)3')], '4-AMINO-BUTYRATE': [(('24', 'gamma-aminobutyrate (GABA)'), 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)'), (('172', 'alpha-ketoglutarate'), 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2'), (('173', 'succinate'), 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'), (('399', 'Succinate semialdehyde'), 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'), (('111', 'putrescine'), 'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2'), (('114', '4-guanidinobutanoate'), 'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)'), (('115', '4-acetamidobutanoate'), 'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1')]}

Little modifed if you don't want those extra brackets :

final_dict={}
for key,value in dict_1.items():
    if key in dict_2:
        for zip_value in zip(value,dict_2.get(key)):

            if key not in final_dict:
                final_dict[key]=[zip_value[0][0],zip_value[0][1],zip_value[1]]
            else:
                final_dict[key].append((zip_value[0][0],zip_value[0][1],zip_value[1]))

print(final_dict)

output:

{'ASN': ['1', 'glycine', 'InChI=1S/C9H11NO3', ('45', 'tyrosine', 'InChI=1S/C9H11NO2/c10-8'), ('74', 'leucine', 'InChI=1S/C3H7NO2/c1-2(4)3(5)6'), ('90', 'methionine', 'InChI=1S/C5H9NO2/c7-5(8)4-2-1-3'), ('80', 'valine', 'InChI=1S/C4H9NO3/c1-2(6)3')], '4-AMINO-BUTYRATE': ['24', 'gamma-aminobutyrate (GABA)', 'InChI=1S/C4H9NO2/c5-3-1-2-4(6)7/h1-3,5H2,(H,6,7)', ('172', 'alpha-ketoglutarate', 'InChI=1S/C5H6O5/c6-3(5(9)10)1-2-4(7)8/h1-2H2,(H,7,8)(H,9,10)/p-2'), ('173', 'succinate', 'InChI=1S/C4H6O4/c5-3(6)1-2-4(7)8/h1-2H2,(H,5,6)(H,7,8)/p-2'), ('399', 'Succinate semialdehyde', 'InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)/p-1'), ('111', 'putrescine', 'InChI=1S/C4H12N2/c5-3-1-2-4-6/h1-6H2/p+2'), ('114', '4-guanidinobutanoate', 'InChI=1S/C5H11N3O2/c6-5(7)8-3-1-2-4(9)10/h1-3H2,(H,9,10)(H4,6,7,8)'), ('115', '4-acetamidobutanoate', 'InChI=1S/C6H11NO3/c1-5(8)7-4-2-3-6(9)10/h2-4H2,1H3,(H,7,8)(H,9,10)/p-1')]}


来源: stackexchange

问:
Xamarin Forms iOS11 Large Title text Extra Blank space
I am trying to update my app to support iOS 11 Large Texts feature. In my custom Navigation Page renderer I have set
NavigationBar.PrefersLargeTitles = true;

The Large Title texts are displayed fine and on scroll they get smaller too.
However on scroll when the Large Title becomes smaller, I am seeing an extra white space at the bottom. (Highlighted in the attached screen shot).
I have read and browsed a lot of posts regarding the issue but my bad luck that none of them works.

I am pretty sure someone would have encountered the error and would have found a workaround or it's solution.
I have also posted the same question in Xamarin Forums but no responses.
https://forums.xamarin.com/discussion/104457/xamarin-forms-ios11-large-title-text-extra-blank-space

答:
As of Xamarin Forms - 2.5.0.91635. This issue is resolved.

For any queries follow the thread on Xamarin Forums -
https://forums.xamarin.com/discussion/comment/307295

ContentLicense: CC BY-SA 3.0


问:
MySQL indexing with a two columns, one of which is a foreign key
I have table T1 where col A is primary key and col B is a foreign key which is a primary key in table T2. I want to create an index in T1, a composite one as (B,A). But MySQL is allowing me to create the index as (A,B) only. Is it because col B is a foreign key ?? Please explain</p>

答:
This works fine for me:

```<code>CREATE TABLE t2 (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB;
CREATE TABLE t1 (a INT NOT NULL PRIMARY KEY, b INT NOT NULL REFERENCES t2(id)) ENGINE=InnoDB;
CREATE INDEX ix_t1_b_a ON t1 (b, a);
</code>```

Though InnoDB does include clustered key as a row pointer in the indexes, there is nothing that prevents adding the field explicitly and sometimes it is required to optimize some queries.

Please check your syntax.

ContentLicense: CC BY-SA 2.5

Body:
This works fine for me:

CREATE TABLE t2 (id INT NOT NULL PRIMARY KEY) ENGINE=InnoDB;
CREATE TABLE t1 (a INT NOT NULL PRIMARY KEY, b INT NOT NULL REFERENCES t2(id)) ENGINE=InnoDB;
CREATE INDEX ix_t1_b_a ON t1 (b, a);

Though InnoDB does include clustered key as a row pointer in the indexes, there is nothing that prevents adding the field explicitly and sometimes it is required to optimize some queries.

Please check your syntax.


问:
Could not find Id of Hidden Text in javascript
This is my aspx page

```<code><telerik:GridTemplateColumn SortExpression="PrintColumn" DataField="PrintColumn" HeaderText=""
    HeaderStyle-Font-Bold="true">
    <ItemTemplate>
        <asp:HiddenField ClientIDMode="Static" ID="lblIDSIDPrint" runat="server" Value='<%# Eval("DSID") %>'/>
        <asp:HiddenField ID="lblDataDSPrint" runat="server" Value='<%# Eval("DataDS")%>'/>
        <asp:LinkButton Style="text-align: right; float: right;" ID="lbDSPrint" runat="server"
            OnClientClick="popWin">Print</asp:LinkButton>
    </ItemTemplate>
</telerik:GridTemplateColumn>
</code>```

This is my javascript

```<code>function popWin() {
    var Dsid = document.getElementById('<%=lblIDSIDPrint.ClientID %>').value;
    var DataDs = document.getElementById('<%=lblDataDSPrint.ClientID %>').value;
    alert(Dsid);
    alert(DataDs);
}
</code>```

But I am getting an error

"CS0103: The name 'lblIDSIDPrint' does not exist in the current context"

Any suggestions on this.

答:
Try like this:-</p>

```<code>var Dsid = document.getElementById('lblIDSIDPrint').value; alert(Dsid);
</code>```

Body:
This is my aspx page

<telerik:GridTemplateColumn SortExpression="PrintColumn" DataField="PrintColumn" HeaderText=""
    HeaderStyle-Font-Bold="true">
    <ItemTemplate>
        <asp:HiddenField ClientIDMode="Static" ID="lblIDSIDPrint" runat="server" Value='<%# Eval("DSID") %>'/>
        <asp:HiddenField ID="lblDataDSPrint" runat="server" Value='<%# Eval("DataDS")%>'/>
        <asp:LinkButton Style="text-align: right; float: right;" ID="lbDSPrint" runat="server"
            OnClientClick="popWin">Print</asp:LinkButton>
    </ItemTemplate>
</telerik:GridTemplateColumn>

This is my javascript

function popWin() {
    var Dsid = document.getElementById('<%=lblIDSIDPrint.ClientID %>').value;
    var DataDs = document.getElementById('<%=lblDataDSPrint.ClientID %>').value;
    alert(Dsid);
    alert(DataDs);
}

But I am getting an error

"CS0103: The name 'lblIDSIDPrint' does not exist in the current context"

Any suggestions on this.

Body:
Try like this:-

var Dsid = document.getElementById('lblIDSIDPrint').value; alert(Dsid);


问:
How to pick top value from tie-break group using Unix sort
I have the following text file:

```<code>$ cat myfile.txt
foo,a,10
bar,c,33
foo,b,50
bar,a,9
foo,a,20
bar,b,20
</code>```

What I want to do is to sort by 2nd column and 3rd (numeric descending) and finally pick the top of each 2nd column group, resulting in

```<code>foo,a,20
foo,b,50
bar,c,33
</code>```

I'm stuck with this:

```<code>$ sort -t"," -k2 -k3r   test.txt
foo,a,10
foo,a,20
bar,a,9
bar,b,20
foo,b,50
bar,c,33
</code>```

Whats the right way to do it?

答:
Your sort command is close. -k actually takes a range of fields, so your -k2 is being interpreted as "sort on everything from the second field to the end of the line," and it's ignoring the -k3 entirely. You have to be explicit about where the ranges start and end. You also want to sort on the third numerically.

Here's all that put together:

```<code>$ sort -t, -k2,2 -k3,3nr myfile.txt
foo,a,20
foo,a,10
bar,a,9
foo,b,50
bar,b,20
bar,c,33
</code>```

Now you want to pick the first line of each group, based on the second field. Although sort has the ability to dedup a stream, it's not smart enough to handle complex scenarios like this. Fortunately, we have awk:

```<code>$ sort -t, -k2,2 -k3,3nr myfile.txt | awk -F, 'x != $2 { print; x = $2 }'
foo,a,20
foo,b,50
bar,c,33
</code>```

Body:
I have the following text file:

$ cat myfile.txt
foo,a,10
bar,c,33
foo,b,50
bar,a,9
foo,a,20
bar,b,20

What I want to do is to sort by 2nd column and 3rd (numeric descending) and finally pick the top of each 2nd column group, resulting in

foo,a,20
foo,b,50
bar,c,33

I'm stuck with this:

$ sort -t"," -k2 -k3r   test.txt
foo,a,10
foo,a,20
bar,a,9
bar,b,20
foo,b,50
bar,c,33

Whats the right way to do it?

Body:
Your sort command is close. -k actually takes a range of fields, so your -k2 is being interpreted as "sort on everything from the second field to the end of the line," and it's ignoring the -k3 entirely. You have to be explicit about where the ranges start and end. You also want to sort on the third numerically.

Here's all that put together:

$ sort -t, -k2,2 -k3,3nr myfile.txt
foo,a,20
foo,a,10
bar,a,9
foo,b,50
bar,b,20
bar,c,33

Now you want to pick the first line of each group, based on the second field. Although sort has the ability to dedup a stream, it's not smart enough to handle complex scenarios like this. Fortunately, we have awk:

$ sort -t, -k2,2 -k3,3nr myfile.txt | awk -F, 'x != $2 { print; x = $2 }'
foo,a,20
foo,b,50
bar,c,33


问:
Protractor and headless chrome: Could not find Angular on page
I can run my e2e test on my Angular2 app with chrome and it works just fine. When I try to use headless chrome with just the additional chromeOptions it fails to find the angular app. I've tried with directConnect:true and also starting the selenium server with webdriver-manager first but both fail the same.

The first thing the test does is call browser().get('/');

yarn run v1.3.2

$ protractor protractor.conf.js

[10:51:34] I/launcher - Running 1 instances of WebDriver

[10:51:34] I/direct - Using ChromeDriver directly...

Jasmine started

[10:51:48] E/protractor - Could not find Angular on page https://localhost:4200/ : retries looking for angular exceeded

Here's my versions

Node Version: 6.11.0

Protractor Version: 5.2.0

Angular Version: 1.4.4

Browser(s): chrome headless

Operating System and Version Windows 7

This is my protractor.conf.js

```<code>var SpecReporter = require('jasmine-spec-reporter').SpecReporter;
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome',
    chromeOptions: {
      args: ["--headless", "--disable-gpu", "--window-size=800,600"]
    }
  },
  directConnect: true,
  baseUrl: 'https://localhost:4200/',
  framework: 'jasmine2',
  useAllAngular2AppRoots: true,
  jasmineNodeOpts: {
    showColors: true,
   defaultTimeoutInterval: 30000,
    print: function () { }
  },
  onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.json'
    });
    jasmine.getEnv().addReporter(new SpecReporter({
      spec: { displayStacktrace: true }
    }));
    jasmine.getEnv().addReporter(new Jasmine2HtmlReporter({
      savePath: './protractor-results/e2e'
    }));
  }
};
</code>```

答:
Did you check this Issue on Protractor here and this Chrome-Bug here?

Did you check, if there is angular present on the page?

See this answer to know, what to look after. Basically check, if your browser console returns anything on either window.angular.version (AngularJS) or window.getAllAngularRootElements (Angular).

If one of the two returns results, but your tests still don't work, I'd suggest to open an Issue on Protractor Github.

Body:
I can run my e2e test on my Angular2 app with chrome and it works just fine. When I try to use headless chrome with just the additional chromeOptions it fails to find the angular app. I've tried with directConnect:true and also starting the selenium server with webdriver-manager first but both fail the same.

The first thing the test does is call browser().get('/');

yarn run v1.3.2

$ protractor protractor.conf.js

[10:51:34] I/launcher - Running 1 instances of WebDriver

[10:51:34] I/direct - Using ChromeDriver directly...

Jasmine started

[10:51:48] E/protractor - Could not find Angular on page https://localhost:4200/ : retries looking for angular exceeded

Here's my versions

Node Version: 6.11.0

Protractor Version: 5.2.0

Angular Version: 1.4.4

Browser(s): chrome headless

Operating System and Version Windows 7

This is my protractor.conf.js

var SpecReporter = require('jasmine-spec-reporter').SpecReporter;
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome',
    chromeOptions: {
      args: ["--headless", "--disable-gpu", "--window-size=800,600"]
    }
  },
  directConnect: true,
  baseUrl: 'https://localhost:4200/',
  framework: 'jasmine2',
  useAllAngular2AppRoots: true,
  jasmineNodeOpts: {
    showColors: true,
   defaultTimeoutInterval: 30000,
    print: function () { }
  },
  onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.json'
    });
    jasmine.getEnv().addReporter(new SpecReporter({
      spec: { displayStacktrace: true }
    }));
    jasmine.getEnv().addReporter(new Jasmine2HtmlReporter({
      savePath: './protractor-results/e2e'
    }));
  }
};


问:
Conditional Tab/FormTab rendering in TabbedShowLayout/TabbedForm
I would like to display a Tab inside the TabbedShowLayout only if the record has a specific property. I tried to create a custom component as below:

```<code>const EventsTab = ({...props, record}) => {
  return record && record.hasEvents &&
  <Tab label="Tab2">
    test
  </Tab>
}
</code>```

and then add it inside the Show layout as:

```<code><Show {...props}>
  <TabbedShowLayout>
    <Tab label="Tab1">
      <MetricsComp {...props} />
    </Tab>
    <EventsTab {...props}/>
  </TabbedShowLayout>
</Show>
</code>```

but I get the following error: uncaught at finalize Invariant Violation: EventsTab(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Admin-on-rest allows conditional rendering of a component (like in How to access record's internals in Show/Edit/Create) but not a Tab. Is there any workaround?

答:
I am not sure and I may be being presumptuous but you component EventsTab will basically return a boolean and not a valid react component. Is the below what you are looking for?</p>

```<code>const EventsTab = ({...props, record}) => {
  return record ? record.hasEvents ?
  (<Tab label="Tab2">
    test
  </Tab>): null: null
}
</code>```

Body:
I would like to display a Tab inside the TabbedShowLayout only if the record has a specific property. I tried to create a custom component as below:

const EventsTab = ({...props, record}) => {
  return record && record.hasEvents &&
  <Tab label="Tab2">
    test
  </Tab>
}

and then add it inside the Show layout as:

<Show {...props}>
  <TabbedShowLayout>
    <Tab label="Tab1">
      <MetricsComp {...props} />
    </Tab>
    <EventsTab {...props}/>
  </TabbedShowLayout>
</Show>

but I get the following error: uncaught at finalize Invariant Violation: EventsTab(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Admin-on-rest allows conditional rendering of a component (like in How to access record's internals in Show/Edit/Create) but not a Tab. Is there any workaround?

Body:
I am not sure and I may be being presumptuous but you component EventsTab will basically return a boolean and not a valid react component. Is the below what you are looking for?

const EventsTab = ({...props, record}) => {
  return record ? record.hasEvents ?
  (<Tab label="Tab2">
    test
  </Tab>): null: null
}


问:
How to query the most recent row for each value in column X?
I'm trying to query the most recent row for each value in a column X.

My current attempt is:

```<code>SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X
</code>```

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?

答:
```<code>SELECT M.*
from
(
 SELECT X, max(mytimestamp) MaxT
 FROM mytable
 GROUP BY X
) N
inner join mytable M on M.X = N.X and M.mytimestamp = N.MaxT
</code>```

While MySQL allows you to mix aggregate and non-aggregate columns in a GROUP BY query.. please don't.  Consider the scenario similar to what you have:

```<code> SELECT max(mytimestamp) MaxT, min(mytimestamp) MinT, mytable.*
 FROM mytable
 GROUP BY X
</code>```

Think about it and let me know which record the columns should come from (hint: max or min).

Body:
I'm trying to query the most recent row for each value in a column X.

My current attempt is:

SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?

Body:
SELECT M.*
from
(
 SELECT X, max(mytimestamp) MaxT
 FROM mytable
 GROUP BY X
) N
inner join mytable M on M.X = N.X and M.mytimestamp = N.MaxT

While MySQL allows you to mix aggregate and non-aggregate columns in a GROUP BY query.. please don't.  Consider the scenario similar to what you have:

 SELECT max(mytimestamp) MaxT, min(mytimestamp) MinT, mytable.*
 FROM mytable
 GROUP BY X

Think about it and let me know which record the columns should come from (hint: max or min).


问:
same slug for different sub category in wordpress
I have a eCommerce website , and i want same slug for different sub category.
For Example:

First i create men parent category in product .And its slug is men and its url is website_url/men

Then i create shirt sub category. His parent is men and its slug is shirt and URL of this website_url/men/shirt

After that i create second women parent category. And its slug is men and its url is website_url/women

Then i create shirt sub category. His parent is women and its slug is shirt-women and URL of this website_url/men/shirt-women

But i need sub category url  like :

```<code>        For men shirt=  website_url/men/shirt
        For women shirt=  website_url/women/shirt
</code>```

答:
How to add the category and product that means you have to develop the product section as per plugin or manually??

After I will give you the solution for same...

Body:
I have a eCommerce website , and i want same slug for different sub category.
For Example:

First i create men parent category in product .And its slug is men and its url is website_url/men

Then i create shirt sub category. His parent is men and its slug is shirt and URL of this website_url/men/shirt

After that i create second women parent category. And its slug is men and its url is website_url/women

Then i create shirt sub category. His parent is women and its slug is shirt-women and URL of this website_url/men/shirt-women

But i need sub category url  like :

        For men shirt=  website_url/men/shirt
        For women shirt=  website_url/women/shirt


问:
how to find out what recipe failed
I'm building a Xilinx image for an FPGA with Yocto. I'm somewhat new to Yocto. One of the recipes failed. From the output I can't figure out which one. Unfortunately I can't paste the log. For some reason stackoverflow won't allow me to do it.

答:
for first of all during building Yocto provides You only last few lines of execution of failed task, for more information You are always gets information which recipe was failed, location to recipe and location to error log file from the task execution - how to view logs from failed tasks.
Even that in summary output at the end of whole build, there is information how many errors, warnings You have with path to recipes and information which function was failed.</p>

Title: how to find out what recipe failed


问:
Uiaotomator.bat file is not open, Opened only for millisecond
My uiaotomator.bat isn't open, whenever I clicked on my bat file it open for millisecond & then disappeared. How do i open this file.
Thanks</p>

答:
It might have encountered an error during running, try opening instead your command line and run the bat file from there, you will see the error it encountered.</p>

```<code>cmd> uiaotomator.bat
.... some message here..
... or error message will be displayed ...
</code>```

Body:
It might have encountered an error during running, try opening instead your command line and run the bat file from there, you will see the error it encountered.

cmd> uiaotomator.bat
.... some message here..
... or error message will be displayed ...


问:
How to remove special characters?
How to remove special characters?

```<code>foreach ($login_and_logout_list['rval'] as $k => $v) {
  $login_time[] = $v['login_time'];
  $logout_time[] = $v['logout_time'];
  $create_time[] = $v['create_time'];
  $i++;
}
var_dump($login_time);
</code>```

What i am getting in var_dump

```<code>array (size=3)
  0 => string '{09:46},{09:48}'
  1 => string '{05:04},{07:04},{08:40},{08:54}'
  2 => string '{05:20}'
</code>```

What i want in var_dump is

```<code>array (size=3)
  0 => string '09:46 | 09:48'
  1 => string '05:04 | 07:04 | 08:40 | 08:54'
  2 => string '05:20'
</code>```

Title: How to remove special characters?

Body:
How to remove special characters?

foreach ($login_and_logout_list['rval'] as $k => $v) {
  $login_time[] = $v['login_time'];
  $logout_time[] = $v['logout_time'];
  $create_time[] = $v['create_time'];
  $i++;
}
var_dump($login_time);

What i am getting in var_dump

array (size=3)
  0 => string '{09:46},{09:48}'
  1 => string '{05:04},{07:04},{08:40},{08:54}'
  2 => string '{05:20}'

What i want in var_dump is

array (size=3)
  0 => string '09:46 | 09:48'
  1 => string '05:04 | 07:04 | 08:40 | 08:54'
  2 => string '05:20'

Body:
I assume you want to port your code from PHP to JavaScript.

var a = ['{09:46},{09:48}', '{05:04},{07:04},{08:40},{08:54}', '{05:20}']

a = a.map(o => {
   return o.replace(/(}\,{)/mg, ' | ').replace(/(}|{)/mg, '');
})

console.log(a);

Here's the PHP solution:

<?php

$a = ['{09:46},{09:48}', '{05:04},{07:04},{08:40},{08:54}', '{05:20}'];

$a = array_map( function($o){

    $o = preg_replace('/(}\,{)/m', ' | ', $o);

    $o = preg_replace('/(}|{)/m', '', $o);

    return $o;

}, $a);

var_dump($a);

// output
// array(3) {
//      [0]=> string(13) "09:46 | 09:48"
//      [1]=> string(29) "05:04 | 07:04 | 08:40 | 08:54"
//      [2]=> string(5) "05:20"
// }


问:
soap web service with symfony
I write a web service with symfony2 that is in this tutorial.

my rout is :

```<code>_soap:
path:      /soap
defaults:  { _controller: AcmeSoapBundle:Default:index}
</code>```

my config :

```<code>services:
hello_service:
    class: Acme\SoapBundle\Services\HelloService
    arguments: ["@mailer"]
</code>```

my service :

```<code>namespace Acme\SoapBundle\Services;

class HelloService
{
    private $mailer;

    public function __construct(\Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function hello($name)
    {

        $message = \Swift_Message::newInstance()
            ->setTo('me@example.com')
            ->setSubject('Hello Service')
            ->setBody($name . ' says hi!');

        $this->mailer->send($message);

        return 'Hello, '.$name;
    }
}
</code>```

my controller :

```<code>namespace Acme\SoapBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $server = new \SoapServer('hello.wsdl');
        $server->setObject($this->get('hello_service'));

        $response = new Response();
        $response->headers->set('Content-Type', 'text/xml; charset=ISO-8859-1');

        ob_start();
        $server->handle();
        $response->setContent(ob_get_clean());

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

hello.wsdl ( web/hello.wsdl )

```<code>    <?xml version="1.0" encoding="ISO-8859-1"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:tns="urn:arnleadservicewsdl"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    targetNamespace="urn:helloservicewsdl">

    <types>
        <xsd:schema targetNamespace="urn:hellowsdl">
            <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
            <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
        </xsd:schema>
    </types>

    <message name="helloRequest">
        <part name="name" type="xsd:string" />
    </message>

    <message name="helloResponse">
        <part name="return" type="xsd:string" />
    </message>

    <portType name="hellowsdlPortType">
        <operation name="hello">
            <documentation>Hello World</documentation>
            <input message="tns:helloRequest"/>
            <output message="tns:helloResponse"/>
        </operation>
    </portType>

    <binding name="hellowsdlBinding" type="tns:hellowsdlPortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="hello">
            <soap:operation soapAction="urn:arnleadservicewsdl#hello" style="rpc"/>

            <input>
                <soap:body use="encoded" namespace="urn:hellowsdl"
                    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </input>

            <output>
                <soap:body use="encoded" namespace="urn:hellowsdl"
                    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </output>
        </operation>
    </binding>

    <service name="hellowsdl">
        <port name="hellowsdlPort" binding="tns:hellowsdlBinding">
            <soap:address location="http://example.com/app.php/soap" />
        </port>
    </service>
</definitions>
</code>```

but I see bellow error:

```<code>XML Parsing Error: no element found
Location: http://xxx.xxxx.xxx/unproject/web/app_dev.php/soap
Line Number 1, Column 1:
</code>```

How can I fix this problem ?
Thanks for your help

答:
Edit this line in Your WSDL to that of the URL In which you are exposing SoapServer : soap:address location="http://example.com/app.php/soap"

Also Replace :

targetNamespace="urn:helloservicewsdl"

to That of

targetNamespace="urn:arnleadservicewsdl"

Also See That in your php.ini that

soap.wsdl_cache_enabled=0 && soap.wsdl_cache_ttl=0

Making this changes Worked for me.

Title: soap web service with symfony

Body:
I write a web service with symfony2 that is in this tutorial.

my rout is :

_soap:
path:      /soap
defaults:  { _controller: AcmeSoapBundle:Default:index}

my config :

services:
hello_service:
    class: Acme\SoapBundle\Services\HelloService
    arguments: ["@mailer"]

my service :

namespace Acme\SoapBundle\Services;

class HelloService
{
    private $mailer;

    public function __construct(\Swift_Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    public function hello($name)
    {

        $message = \Swift_Message::newInstance()
            ->setTo('me@example.com')
            ->setSubject('Hello Service')
            ->setBody($name . ' says hi!');

        $this->mailer->send($message);

        return 'Hello, '.$name;
    }
}

my controller :

namespace Acme\SoapBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $server = new \SoapServer('hello.wsdl');
        $server->setObject($this->get('hello_service'));

        $response = new Response();
        $response->headers->set('Content-Type', 'text/xml; charset=ISO-8859-1');

        ob_start();
        $server->handle();
        $response->setContent(ob_get_clean());

        return $response;
    }
}

hello.wsdl ( web/hello.wsdl )

    <?xml version="1.0" encoding="ISO-8859-1"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:tns="urn:arnleadservicewsdl"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    targetNamespace="urn:helloservicewsdl">

    <types>
        <xsd:schema targetNamespace="urn:hellowsdl">
            <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
            <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
        </xsd:schema>
    </types>

    <message name="helloRequest">
        <part name="name" type="xsd:string" />
    </message>

    <message name="helloResponse">
        <part name="return" type="xsd:string" />
    </message>

    <portType name="hellowsdlPortType">
        <operation name="hello">
            <documentation>Hello World</documentation>
            <input message="tns:helloRequest"/>
            <output message="tns:helloResponse"/>
        </operation>
    </portType>

    <binding name="hellowsdlBinding" type="tns:hellowsdlPortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="hello">
            <soap:operation soapAction="urn:arnleadservicewsdl#hello" style="rpc"/>

            <input>
                <soap:body use="encoded" namespace="urn:hellowsdl"
                    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </input>

            <output>
                <soap:body use="encoded" namespace="urn:hellowsdl"
                    encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </output>
        </operation>
    </binding>

    <service name="hellowsdl">
        <port name="hellowsdlPort" binding="tns:hellowsdlBinding">
            <soap:address location="http://example.com/app.php/soap" />
        </port>
    </service>
</definitions>

but I see bellow error:

XML Parsing Error: no element found
Location: http://xxx.xxxx.xxx/unproject/web/app_dev.php/soap
Line Number 1, Column 1:

How can I fix this problem ?
Thanks for your help


问:
Explicit conversion int to SqlInt32
Does anybody knows how to explicitly convert int to SqlInt32? Compiler throws error of conversion.</p>

```<code>using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction()]
    static public int RarFiles(SqlString TARGET, SqlString SRC, SqlString SIZE)
    {
        ProcessStartInfo p = new ProcessStartInfo();
        p.FileName = @"C:\Program Files\WinRAR\rar.exe";
        p.Arguments = String.Format("a -cfg- -ep1 -idcdp -m5 -r -s -v{0} {1} {2}", SIZE, TARGET, SRC);
        Process x = Process.Start(p);
        SqlInt32 res = x.ExitCode;
        return res;
   }
}
</code>```

答:
If you want your method to return an SqlInt32, you'll need to declare it as returning one. Your current code defines the return type of the method as int

```<code>static public int RarFiles(SqlString TARGET, SqlString SRC, SqlString SIZE)
              ^^^
</code>```

This line of code will work fine:

```<code>SqlInt32 res = x.ExitCode;
</code>```

Because as John has noted, there's an implicit conversion from int to SqlInt32

But then the next time:

```<code>return res;
</code>```

Will try to convert the SqlInt32 to int, because the method returns an int, but in that direction, the conversion is explicit (you have to cast) and as you haven't supplied an explicit conversion, you'll get an error. The solution you seek is probably not to make the explicit conversion, but to fix the problem with the declared return type of the method

Title: Explicit conversion int to SqlInt32

Body:
Does anybody knows how to explicitly convert int to SqlInt32? Compiler throws error of conversion.

using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction()]
    static public int RarFiles(SqlString TARGET, SqlString SRC, SqlString SIZE)
    {
        ProcessStartInfo p = new ProcessStartInfo();
        p.FileName = @"C:\Program Files\WinRAR\rar.exe";
        p.Arguments = String.Format("a -cfg- -ep1 -idcdp -m5 -r -s -v{0} {1} {2}", SIZE, TARGET, SRC);
        Process x = Process.Start(p);
        SqlInt32 res = x.ExitCode;
        return res;
   }
}

Body:
If you want your method to return an SqlInt32, you'll need to declare it as returning one. Your current code defines the return type of the method as int

static public int RarFiles(SqlString TARGET, SqlString SRC, SqlString SIZE)
              ^^^

This line of code will work fine:

SqlInt32 res = x.ExitCode;

Because as John has noted, there's an implicit conversion from int to SqlInt32

But then the next time:

return res;

Will try to convert the SqlInt32 to int, because the method returns an int, but in that direction, the conversion is explicit (you have to cast) and as you haven't supplied an explicit conversion, you'll get an error. The solution you seek is probably not to make the explicit conversion, but to fix the problem with the declared return type of the method


问:
R: duplicate data in a dataframe
Mars:

```<code>ticket  Name    Fare
  A3    Emily    50
  A4    Jack     50
  A5    Sam      25
  A6    Lara     25
  A4    Julie    50
  A3    Kevin    50
</code>```

When we go to the movies, sometimes we buy one ticket for two people's price. Now I need to count the repeated data. I know how to count it, but not sure how to put it back into the data frame since the length will be different.

My code:

```<code>a <- as.data.frame(table(Mars$ticket))
Mars$Count <- Mars$ticket[a$Var2]
</code>```

Output:

```<code>var1   Var2
A3      2
A4      2
A5      1
A6      1

Error
  replacement has 4 rows, data has 6
</code>```

Expected output:

Mars:

```<code>ticket  Name    Fare  Count
  A3    Emily    50     2
  A4    Jack     50     2
  A5    Sam      25     1
  A6    Lara     25     1
  A4    Julie    50     2
  A3    Kevin    50     2
</code>```

答:
Assuming that 'ticket' is character class, we use the 'ticket' to match the names of 'table' and expand the values

```<code>Mars$Count <- with(Mars, as.vector(table(ticket)[ticket]))
Mars$Count
#[1] 2 2 1 1 2 2
</code>```

Title: R: duplicate data in a dataframe

Body:
Mars:

ticket  Name    Fare
  A3    Emily    50
  A4    Jack     50
  A5    Sam      25
  A6    Lara     25
  A4    Julie    50
  A3    Kevin    50

When we go to the movies, sometimes we buy one ticket for two people's price. Now I need to count the repeated data. I know how to count it, but not sure how to put it back into the data frame since the length will be different.

My code:

a <- as.data.frame(table(Mars$ticket))
Mars$Count <- Mars$ticket[a$Var2]

Output:

var1   Var2
A3      2
A4      2
A5      1
A6      1

Error
  replacement has 4 rows, data has 6

Expected output:

Mars:

ticket  Name    Fare  Count
  A3    Emily    50     2
  A4    Jack     50     2
  A5    Sam      25     1
  A6    Lara     25     1
  A4    Julie    50     2
  A3    Kevin    50     2

Body:
Assuming that 'ticket' is character class, we use the 'ticket' to match the names of 'table' and expand the values

Mars$Count <- with(Mars, as.vector(table(ticket)[ticket]))
Mars$Count
#[1] 2 2 1 1 2 2


问:
Effective clustering algorithm
I need help (preferably a full algorithm, but any hint or reference will be appreciated) with the following algorithmic problem:

We have a set of N elements. I can define a distance between any two elements, which satisfies the metric conditions. I need to group these elements into disjoint subsets (each element belonging to exactly one subset) according to the following rules:

The maximum distance between any two elements in each subset does not exceed specified threshold.

The number of the subsets is as small as possible.

If there is more than one possible grouping satisfying conditions (1) and (2), the maximum distance between any two elements in each subset should be as small as possible.

Example:

Assume we have the following points on a number axis: 1, 11, 12, 13, 23. The distance is simple the the difference between the points. Our distance threshold is 10. The two possible grouping satisfying conditions (1) and (2) are: (1, 11), (12), (13, 23) or (1), (11, 12, 13), (23). However, the condition (3) says that the latter grouping is the correct one.

答:
In 1 dimensional data, sort your data, and divide into the desired number of bins, then move bin boundaries to optimize.

It gets more interesting in higher dimensionality. There, the problem will be NP hard. So finding the optimum will be expensive. You can indeed use clustering here: use complete-linkage clustering. For a O(n²) and O(n) memory approach, try CLINK. But in my experience, you will need to run this algorithm several times, on shuffled data, to get a good solution.

Title: Effective clustering algorithm


问:
React Native : Handling Async calls to sqllite db
I am having a bit of struggle trying to understand how async functions work in React Native.

In this example I am invoking a sqllite db call via a async call and get values of height and standard and return both these values as an object called result.

Values exist in sqllite db as can be seen in the console output shown below.

The method invoked from componentDidMount lifecycle method is an async method.

As can be seen I am using await to wait for the actual execution (aka getting data from sqllite) to complete.

Line X always returns as undefined.

Line Y does not seem to execute at all as the state does not get changed from the initial values of 100 & "asasd" at all.

I have eyeballed the code and I am not sure what I am missing here.

Can someone take a look at it and let me know ?

App.js

```<code>import React, { Component } from 'react';
import { View, Text } from 'react-native';
import {
  dropLogsTable,
  createLogsTable,
  getProfileHeightStandardfromDB,
  getProfileHeightStandardPremade,
  saveLogsRecord
} from '../src/helper';

export default class App extends Component {
  state = {
    logarray: [],
    profileobject: {profileheight: 100, profilestandard: "asasd"},

  };

  componentDidMount() {

    dropLogsTable();
    createLogsTable();
    this.fetchProfileData();

  }

  async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    return result; //Line X
    this.setState({profileobject:result}); //Line Y
  }

  render() {
    return (
      <View>
        <Text>This is a test</Text>
        <Text>Profile Height : {this.state.profileobject.profileheight} </Text>
        <Text>Profile Standard : {this.state.profileobject.profilestandard}</Text>
      </View>
    );
  }
}
</code>```

helper.js

```<code>import { SQLite } from 'expo';

const db = SQLite.openDatabase({ name: 'swlt.db' });

let profileheight, profilestandard;

export function getProfileHeightStandardfromDB()
          {
        db.transaction(
          tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) =>
              {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>'+profileheight);
                console.log('Profilestandard ===>'+profilestandard);
              }
            );
          },
          null,
          null
        );

        const profileobject = {profileheight, profilestandard};
        console.log(profileobject);
        return profileobject;

      }
</code>```

Output from Device and Console

答:
You seem to have the this.setState after a return statement; no code after the return statement will execute. Just put the this.setState call before the return block

Also, the function getProfileHeightStandardfromDB() needs to be an async function or needs to return a Promise. Currently the method does not return a Promise so theres no point awaiting it. So heres what you would need to do

```<code>function getProfileHeightStandardfromDB() {
  return new Promise((resolve, reject) => {
    db.transaction(
      tx => {
        tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) => {
          //console.log(rows);
          console.log(rows);

          //console.log(parseFloat(rows._array[0].metricheight));
          profileheight = parseFloat(rows._array[0].metricheight);
          profilestandard = rows._array[0].standard;
          console.log('Profileheight ===>'+profileheight);
          console.log('Profilestandard ===>'+profilestandard);

          // what you resolve here is what will be the result of
          // await getProfileHeightStandardfromDB();
          resolve({ profileheight, profilestandard });
      });
    }, null, null);
  });
}
</code>```

Body:
I am having a bit of struggle trying to understand how async functions work in React Native.

In this example I am invoking a sqllite db call via a async call and get values of height and standard and return both these values as an object called result.

Values exist in sqllite db as can be seen in the console output shown below.

The method invoked from componentDidMount lifecycle method is an async method.

As can be seen I am using await to wait for the actual execution (aka getting data from sqllite) to complete.

Line X always returns as undefined.

Line Y does not seem to execute at all as the state does not get changed from the initial values of 100 & "asasd" at all.

I have eyeballed the code and I am not sure what I am missing here.

Can someone take a look at it and let me know ?

App.js

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import {
  dropLogsTable,
  createLogsTable,
  getProfileHeightStandardfromDB,
  getProfileHeightStandardPremade,
  saveLogsRecord
} from '../src/helper';

export default class App extends Component {
  state = {
    logarray: [],
    profileobject: {profileheight: 100, profilestandard: "asasd"},

  };

  componentDidMount() {

    dropLogsTable();
    createLogsTable();
    this.fetchProfileData();

  }

  async fetchProfileData() {
    console.log('Before Profile Fetch');
    const result = await getProfileHeightStandardfromDB();
    console.log('After Profile Fetch');
    console.log('Height : '+result.profileheight);
    console.log('Standard: '+result.profilestandard);
    return result; //Line X
    this.setState({profileobject:result}); //Line Y
  }

  render() {
    return (
      <View>
        <Text>This is a test</Text>
        <Text>Profile Height : {this.state.profileobject.profileheight} </Text>
        <Text>Profile Standard : {this.state.profileobject.profilestandard}</Text>
      </View>
    );
  }
}

helper.js

import { SQLite } from 'expo';

const db = SQLite.openDatabase({ name: 'swlt.db' });

let profileheight, profilestandard;

export function getProfileHeightStandardfromDB()
          {
        db.transaction(
          tx => {

            tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) =>
              {
                //console.log(rows);
                console.log(rows);

                //console.log(parseFloat(rows._array[0].metricheight));
                profileheight = parseFloat(rows._array[0].metricheight);
                profilestandard = rows._array[0].standard;
                console.log('Profileheight ===>'+profileheight);
                console.log('Profilestandard ===>'+profilestandard);
              }
            );
          },
          null,
          null
        );

        const profileobject = {profileheight, profilestandard};
        console.log(profileobject);
        return profileobject;

      }

Output from Device and Console

Body:
You seem to have the this.setState after a return statement; no code after the return statement will execute. Just put the this.setState call before the return block

Also, the function getProfileHeightStandardfromDB() needs to be an async function or needs to return a Promise. Currently the method does not return a Promise so theres no point awaiting it. So heres what you would need to do

function getProfileHeightStandardfromDB() {
  return new Promise((resolve, reject) => {
    db.transaction(
      tx => {
        tx.executeSql('select standard, metricweight, metricheight, imperialheight, imperialweight, bmi, metricgoalweight, imperialgoalweight from profile', [], (_, { rows }) => {
          //console.log(rows);
          console.log(rows);

          //console.log(parseFloat(rows._array[0].metricheight));
          profileheight = parseFloat(rows._array[0].metricheight);
          profilestandard = rows._array[0].standard;
          console.log('Profileheight ===>'+profileheight);
          console.log('Profilestandard ===>'+profilestandard);

          // what you resolve here is what will be the result of
          // await getProfileHeightStandardfromDB();
          resolve({ profileheight, profilestandard });
      });
    }, null, null);
  });
}


问:
Sample Cocoa app, ref counting, [pool drain] yields EXC_BAD_ACCESS?
I'm working through Cocoa Programming for Mac OS X (3rd ed) and in chapter 4 I wrote this app:

```<code>int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //create the date object
    NSCalendarDate *now = [[NSCalendarDate alloc] init];

    //seed random # generator
    srandom(time(NULL));

    NSMutableArray *array;
    array = [[NSMutableArray alloc] init];
    int i;
    for (i=0; i<10; i++){
        //create a date/time that is 'i' weeks from now
        NSCalendarDate *iWeeksFromNow;
        iWeeksFromNow = [now dateByAddingYears:0
                                        months:0
                                          days:(i*7)
                                         hours:0
                                       minutes:0
                                       seconds:0];

        //create a new instance of lottery entry
        LotteryEntry *entry = [[LotteryEntry alloc] init];
        [entry setEntryDate:iWeeksFromNow];

        [array addObject:entry];
        [entry release];
    }
    [now release];
    now = nil;

    for (LotteryEntry *entryToPrint in array) {
        NSLog(@"%@", entryToPrint);
    }
    [array release];
    array = nil;

    NSLog(@"about to drain the pool... (%@)", pool);
    [pool drain];
    NSLog(@"done");
    NSLog(@"GC = %@", [NSGarbageCollector defaultCollector]);
    return 0;
}
</code>```

The LotteryEntry class looks like this:

```<code>@implementation LotteryEntry

- (void)setEntryDate:(NSCalendarDate *)date
{
    entryDate = date;
}

- (NSCalendarDate *)entryDate
{
    return entryDate;
}

- (int)firstNumber
{
    return firstNumber;
}

- (int)secondNumber
{
    return secondNumber;
}

- (id)init
{
    return [self initWithDate:[NSCalendarDate calendarDate]];
}

- (id)initWithDate:(NSCalendarDate *)date
{
    if(![super init])
        return nil;

    NSAssert(date != nil, @"Argument must be non-nil");

    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    entryDate = [date retain];
    return self;
}

- (NSString *)description
{
    NSString *result;
    result = [[NSString alloc] initWithFormat:@"%@ = %d and %d",
              [entryDate descriptionWithCalendarFormat:@"%b %d %Y"],
              firstNumber,
              secondNumber];
    return result;
}

- (void)dealloc
{
    NSLog(@"deallocating %@", self);
    [entryDate release];
    [super dealloc];
}

@end
</code>```

As you can see I'm retaining and releasing the objects here.  I'm pretty sure my code matches the book's, however when I run the app, at the [pool drain] I get this message:

Program received signal:
  “EXC_BAD_ACCESS”.

I'm not sure what's causing this.  I'm hoping it's something stupid that I missed, but I'd sure appreciate a few other pairs of eyes on it.  Thanks in advance!

(side note:  I'm a .NET developer, so ref counting is pretty foreign to me!)

答: It's not related to your issue at hand but you should avoid using NSCalendarDate, it's been deprecated for a while now and will probably be removed from the API entirely soon.

OwnerDisplayName: Ben Scheirman

Body:
I'm working through Cocoa Programming for Mac OS X (3rd ed) and in chapter 4 I wrote this app:

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //create the date object
    NSCalendarDate *now = [[NSCalendarDate alloc] init];

    //seed random # generator
    srandom(time(NULL));

    NSMutableArray *array;
    array = [[NSMutableArray alloc] init];
    int i;
    for (i=0; i<10; i++){
        //create a date/time that is 'i' weeks from now
        NSCalendarDate *iWeeksFromNow;
        iWeeksFromNow = [now dateByAddingYears:0
                                        months:0
                                          days:(i*7)
                                         hours:0
                                       minutes:0
                                       seconds:0];

        //create a new instance of lottery entry
        LotteryEntry *entry = [[LotteryEntry alloc] init];
        [entry setEntryDate:iWeeksFromNow];

        [array addObject:entry];
        [entry release];
    }
    [now release];
    now = nil;

    for (LotteryEntry *entryToPrint in array) {
        NSLog(@"%@", entryToPrint);
    }
    [array release];
    array = nil;

    NSLog(@"about to drain the pool... (%@)", pool);
    [pool drain];
    NSLog(@"done");
    NSLog(@"GC = %@", [NSGarbageCollector defaultCollector]);
    return 0;
}

The LotteryEntry class looks like this:

@implementation LotteryEntry

- (void)setEntryDate:(NSCalendarDate *)date
{
    entryDate = date;
}

- (NSCalendarDate *)entryDate
{
    return entryDate;
}

- (int)firstNumber
{
    return firstNumber;
}

- (int)secondNumber
{
    return secondNumber;
}

- (id)init
{
    return [self initWithDate:[NSCalendarDate calendarDate]];
}

- (id)initWithDate:(NSCalendarDate *)date
{
    if(![super init])
        return nil;

    NSAssert(date != nil, @"Argument must be non-nil");

    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    entryDate = [date retain];
    return self;
}

- (NSString *)description
{
    NSString *result;
    result = [[NSString alloc] initWithFormat:@"%@ = %d and %d",
              [entryDate descriptionWithCalendarFormat:@"%b %d %Y"],
              firstNumber,
              secondNumber];
    return result;
}

- (void)dealloc
{
    NSLog(@"deallocating %@", self);
    [entryDate release];
    [super dealloc];
}

@end

As you can see I'm retaining and releasing the objects here.  I'm pretty sure my code matches the book's, however when I run the app, at the [pool drain] I get this message:

Program received signal:
  “EXC_BAD_ACCESS”.

I'm not sure what's causing this.  I'm hoping it's something stupid that I missed, but I'd sure appreciate a few other pairs of eyes on it.  Thanks in advance!

(side note:  I'm a .NET developer, so ref counting is pretty foreign to me!)

OwnerDisplayName: Ashley Clark


问:
how i can show object in gridview or in any usful contro
```<code>public class EventDetail
{
    private Int64 logID;

    public Int64 LogID
    {
        get { return logID; }
        set { logID = value; }
    }
    private Object logedObject;

    public Object LogedObject
    {
        get { return logedObject; }
        set { logedObject = value; }
    }

}
</code>```

答:
Instead of returning collection of class EventDetail, if you only have to bind logedevent, then do the following. Extract the collection of LogedObject in some other collection or

directly bind it to grid

```<code>protected void BindGrid()
{
   gv.DataSource = EventDetail_Object.LogedObect_Property_Of_Class;
   gv.DataBind();
}
</code>```

Body:
Instead of returning collection of class EventDetail, if you only have to bind logedevent, then do the following. Extract the collection of LogedObject in some other collection or

directly bind it to grid

protected void BindGrid()
{
   gv.DataSource = EventDetail_Object.LogedObect_Property_Of_Class;
   gv.DataBind();
}


问:
Looping through rows of a particular column by searching for a string
I imported some data from a txt file:

```<code>df <- read.table(file.choose(),
                               sep = "\t",
                               skip = 2,
                               fill = T)
df <- cdf[,c(6,11)]
colnames(df) <- c("area", "population")
</code>```

A shortened version of my data looks like this in the environment in RStudio

```<code>     area                                      population
[1]  area0                                     0
[2]  area1:                                    59,859
[3]  area0:                                    56000
[4]  area0:                                    25
[5]  area0:                                    Unknown
[6]  area0:                                    1,400
</code>```

This is in a data.frame class and I want to loop through the state to find if it contains the phrase area0. If it does, I want to go to population on that same row and add the populations up via a cumulative sum. My end result should be like this:
area0 57425 in a new data.frame

答:
As Ronak Shah stated in the comments, this problem can be solved using
sum(as.numeric(as.character(df$population[grepl("area0", df$state])), na.rm = T)

This avoids the need need for a for loop.

A second thing that should be implemented is getting rid of the commas in the population column so the sum can be calculated correctly. This can be done using gsub:

```<code>df$population <- gsub(",", "", df$population)
</code>```

Body:
I imported some data from a txt file:

df <- read.table(file.choose(),
                               sep = "\t",
                               skip = 2,
                               fill = T)
df <- cdf[,c(6,11)]
colnames(df) <- c("area", "population")

A shortened version of my data looks like this in the environment in RStudio

     area                                      population
[1]  area0                                     0
[2]  area1:                                    59,859
[3]  area0:                                    56000
[4]  area0:                                    25
[5]  area0:                                    Unknown
[6]  area0:                                    1,400

This is in a data.frame class and I want to loop through the state to find if it contains the phrase area0. If it does, I want to go to population on that same row and add the populations up via a cumulative sum. My end result should be like this:
area0 57425 in a new data.frame

Body:
As Ronak Shah stated in the comments, this problem can be solved using
sum(as.numeric(as.character(df$population[grepl("area0", df$state])), na.rm = T)

This avoids the need need for a for loop.

A second thing that should be implemented is getting rid of the commas in the population column so the sum can be calculated correctly. This can be done using gsub:

df$population <- gsub(",", "", df$population)


答:
Simple code use this </p>

```<code>func storeLatitudeAndLongnitude()
{
    let yourArray = NSArray()
    var arr_latitude_1 = [String]()
    var arr_latitude_2 = [String]()

    for item in yourArray
    {
        let dictData = item as! NSDictionary
        let status = dictData["status"] as? Int ?? 1
        let latitude = dictData["latitude"] as? String ?? "default_value"

        if status == 1
        {
            arr_latitude_1.append(latitude)
        }else
        {//For 2
            arr_latitude_2.append(latitude)
        }
    }
}
</code>```

Title: How to find value from dictionary

Body:
I have following simple dictionary and I want latitude array when status 1 it is store one array and status 2 it store second array
Please help me out

 data =     (
            {
        created = "2017-11-13 09:04:18";
        "end_date" = "2017-11-13 11:49:08";
        id = 878;
        latitude = "23.032190322875977000";
        longitude = "72.565238952636720000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 11:49:08";
        "end_date" = "2017-11-13 13:13:15";
        id = 888;
        latitude = "23.032133102416992000";
        longitude = "72.565208435058600000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:13:15";
        "end_date" = "2017-11-13 13:26:26";
        id = 891;
        latitude = "23.032199859619140000";
        longitude = "72.565269470214840000";
        status = 2;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:26:26";
        "end_date" = "2017-11-13 16:54:20";
        id = 892;
        latitude = "23.032056808471680000";
        longitude = "72.565223693847660000";
        status = 2;
        "user_id" = 21;
    }

)

Body:
Simple code use this

func storeLatitudeAndLongnitude()
{
    let yourArray = NSArray()
    var arr_latitude_1 = [String]()
    var arr_latitude_2 = [String]()

    for item in yourArray
    {
        let dictData = item as! NSDictionary
        let status = dictData["status"] as? Int ?? 1
        let latitude = dictData["latitude"] as? String ?? "default_value"

        if status == 1
        {
            arr_latitude_1.append(latitude)
        }else
        {//For 2
            arr_latitude_2.append(latitude)
        }
    }
}


问:
Xamarin Forms iOS Local Notifications not displaying
I'm building an application in Xamarin.Forms, and am having trouble getting the Local Notifications to display in iOS.
I've followed the guide from https://developer.xamarin.com/guides/ios/platform_features/user-notifications/enhanced-user-notifications/ and the notification still doesnt display.
I've added the following to my FinishedLaunching method in AppDelegate:

```<code>    UNUserNotificationCenter.Current.RequestAuthorization (UNAuthorizationOptions.Alert, (approved, err) => {});
</code>```

And in my page where I'd like the notification to display:

```<code>using UserNotifications;

var content = new UNMutableNotificationContent ();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "Test Notification.";
content.Badge = 1;

var trigger =  UNTimeIntervalNotificationTrigger.CreateTrigger (5, false);

var requestID = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier (requestID, content,
trigger);

UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => {
if (err != null) {
    // Do something with error...
}
});
</code>```

All of my nuGet packages are up to date, and I've tried testing on both iOS iPhone simulators, and a physical iPad device.

Is there something I am missing here?

答:
Actually, if your app is in the foreground, the iOS system will silence notifications by default.

Solutions:

There're two solutions for you:

Go to the background via clicking the Home button, when you trigger the delayed notification. Then the notification will show up.

Implement the delegate userNotificationCenter:willPresentNotification:withCompletionHandler:, it will be called when there's a notification arrives in your app when it is in the foreground.
For example, here's the code snippet for enabling the notification when the app is in the foreground:

```<code>UNUserNotificationCenter.Current.Delegate = new MyNotificationDelegate();

public class MyNotificationDelegate: UNUserNotificationCenterDelegate
{
    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,  Action<UNNotificationPresentationOptions> completionHandler)
    {
        completionHandler(UNNotificationPresentationOptions.Alert);
    }
}
</code>```

Body:
I'm building an application in Xamarin.Forms, and am having trouble getting the Local Notifications to display in iOS.
I've followed the guide from https://developer.xamarin.com/guides/ios/platform_features/user-notifications/enhanced-user-notifications/ and the notification still doesnt display.
I've added the following to my FinishedLaunching method in AppDelegate:

    UNUserNotificationCenter.Current.RequestAuthorization (UNAuthorizationOptions.Alert, (approved, err) => {});

And in my page where I'd like the notification to display:

using UserNotifications;

var content = new UNMutableNotificationContent ();
content.Title = "Notification Title";
content.Subtitle = "Notification Subtitle";
content.Body = "Test Notification.";
content.Badge = 1;

var trigger =  UNTimeIntervalNotificationTrigger.CreateTrigger (5, false);

var requestID = "sampleRequest";
var request = UNNotificationRequest.FromIdentifier (requestID, content,
trigger);

UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => {
if (err != null) {
    // Do something with error...
}
});

All of my nuGet packages are up to date, and I've tried testing on both iOS iPhone simulators, and a physical iPad device.

Is there something I am missing here?

Body:
Actually, if your app is in the foreground, the iOS system will silence notifications by default.

Solutions:

There're two solutions for you:

Go to the background via clicking the Home button, when you trigger the delayed notification. Then the notification will show up.

Implement the delegate userNotificationCenter:willPresentNotification:withCompletionHandler:, it will be called when there's a notification arrives in your app when it is in the foreground.
For example, here's the code snippet for enabling the notification when the app is in the foreground:

UNUserNotificationCenter.Current.Delegate = new MyNotificationDelegate();

public class MyNotificationDelegate: UNUserNotificationCenterDelegate
{
    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,  Action<UNNotificationPresentationOptions> completionHandler)
    {
        completionHandler(UNNotificationPresentationOptions.Alert);
    }
}


问:
Postgresql Transaction ID Not Found
Whenever I am executing a query in postgresql, this is the error message I receive

Transaction ID not found in the session.

Does anyone have any idea how to resolve this? I recently created a new user, but I was unable to find documentation that even shows this as a valid error.

Additional Details:
I've managed to resolve the error by re-connecting with admin credentials.

I was using PG Admin V4 with Postgres V9.6, and that was the only message appearing in any query I executed, even if it was a basic query like 'SELECT NOW()'.

At the same time, this was the error message being received by the client device (an iOS device with a AWS Lambda / NodeJS backend) :

```<code>'message' : {
  'name' : 'error',
  'length' : 114,
  'severity' : 'fatal',
  'code' : '28000',
  'file' : 'miscinit.c',
  'line' : '587',
  'routine' : 'InitializeSessionUserId'
}
</code>```

答:
So I don't know the exact specifics of my solution, but I found this issue in the following circumstance:

Database user was created.

Role was assigned for the user.

A transaction was used

I'm still not entirely sure I discovered the solution of the root problem, but if others have the same scenario, it might help troubleshoot it further. If any of those three are not used, then I never encountered the issue.

Title: Postgresql Transaction ID Not Found

Body:
Whenever I am executing a query in postgresql, this is the error message I receive

Transaction ID not found in the session.

Does anyone have any idea how to resolve this? I recently created a new user, but I was unable to find documentation that even shows this as a valid error.

Additional Details:
I've managed to resolve the error by re-connecting with admin credentials.

I was using PG Admin V4 with Postgres V9.6, and that was the only message appearing in any query I executed, even if it was a basic query like 'SELECT NOW()'.

At the same time, this was the error message being received by the client device (an iOS device with a AWS Lambda / NodeJS backend) :

'message' : {
  'name' : 'error',
  'length' : 114,
  'severity' : 'fatal',
  'code' : '28000',
  'file' : 'miscinit.c',
  'line' : '587',
  'routine' : 'InitializeSessionUserId'
}


问:
Log file for mysql database
How can I create a log file for mysql, and maintain the log for each database transaction?</p>

答:
There are a variety of MySQL logs. If you're just after a record of changes, the binary log should be ideal for your requirements.

Information on log maintenance is also reference from the page linked above.

Title: Log file for mysql database


问:
AudioKit playground AudioKitUI views not showing
Just downloaded AudioKitPlaygrounds-4.0.3 and built it. I am getting audio just fine but none of the UI views show in the playgrounds. For example Mixing Nodes, the audio plays perfectly but I don't see any AudioKitUI views in the right pane. Tried clean and build again still no ui elements. I believe I should see them. I'm sure I missed something so I would appreciate help or pointer to docs that clears this up. Using Xcode 9.1 Mac OS X 10.12.6.
Thanks
Chris</p>

答: It sounds like you are not showing the timeline view in your playgrounds.</p>


问:
ng-repeat - copy of objects rather than direct reference
If I want the object from ng-repeat to be a copy of the actual object in the list, how would I do so?

For example:

```<code><div ng-repeat="thing in model.things">
    <input ng-model="thing.field"/>
    <button> // clicking this button would update that thing </button>
</div>
</code>```

If I type in that input field, it will directly modify the object inside model.things. I would like it to modify a copy of the thing, and then only update the actual one when I click an update button.

I tried doing something like model.getThings() which will angular.copy() the list, but that triggers an infinite loop of $digest when a new thing is added.

How is this best done? Thanks!

答:
I have created a plnkr for the solution that you are looking for. Please find it here https://plnkr.co/edit/MgDroW3e6hqkg2LNAtik?p=preview

Controller

```<code>$scope.data = [
  {name: 'Perry'},
  {name: 'Sam'},
  {name: 'Ron'}
];
$scope.cloned = angular.copy($scope.data);
$scope.update = function () {
  $scope.data = angular.copy($scope.cloned);
}
</code>```

It clones the actual data and uses it in ng-repeat. And upon update it assigns back the copy of the changed data to your original data.

Body:
If I want the object from ng-repeat to be a copy of the actual object in the list, how would I do so?

For example:

    <input ng-model="thing.field"/>
    <button> // clicking this button would update that thing </button>

If I type in that input field, it will directly modify the object inside model.things. I would like it to modify a copy of the thing, and then only update the actual one when I click an update button.

I tried doing something like model.getThings() which will angular.copy() the list, but that triggers an infinite loop of $digest when a new thing is added.

How is this best done? Thanks!

Body:
I have created a plnkr for the solution that you are looking for. Please find it here https://plnkr.co/edit/MgDroW3e6hqkg2LNAtik?p=preview

Controller

$scope.data = [
  {name: 'Perry'},
  {name: 'Sam'},
  {name: 'Ron'}
];
$scope.cloned = angular.copy($scope.data);
$scope.update = function () {
  $scope.data = angular.copy($scope.cloned);
}

It clones the actual data and uses it in ng-repeat. And upon update it assigns back the copy of the changed data to your original data.


问:
How to send string from one activity to another?
I have a string in activity2

```<code>String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng);
</code>```

I want to insert this string into text field in activity1. How can I do that?

答:
```<code> Intent intent = new Intent(activity1.this, activity2.class);
 intent.putExtra("message", message);
 startActivity(intent);
</code>```

In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :

```<code>  Bundle bundle = getIntent().getExtras();
  String message = bundle.getString("message");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a string in activity2

String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng);

I want to insert this string into text field in activity1. How can I do that?

Body:
 Intent intent = new Intent(activity1.this, activity2.class);
 intent.putExtra("message", message);
 startActivity(intent);

In activity2, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :

  Bundle bundle = getIntent().getExtras();
  String message = bundle.getString("message");


问:
I want to add two columns in a dataframe with incremental values
I want to add two columns in a dataframe, let say we have 50 rows in the dataframe, so my Column 1 values should be 1 to 50, and Column 2 values should be 51 to 100.

```<code>def insertId(new_df, str):
    df.insertId(0, str, range(1, 1 + len(df)))
    return df
</code>```

The above function needs correction in order to meet my requirement, but unable to do so, as i am a beginner in Python.

答:
Create first numpy array and pass it to DataFrame constructor:

```<code>a = np.arange(1, 101).reshape(2,-1).T
df1 = pd.DataFrame(a, columns=['a','b'])

print(df1.head())

   a   b
0  1  51
1  2  52
2  3  53
3  4  54
4  5  55
</code>```

Last add it to original DataFrame:

```<code>df = df.join(df1)
</code>```

Solution with your function with insert - is possible specify position of column pos, then column name col and last start number start:

```<code>#some Dataframe
a = np.arange(1, 101).reshape(2,-1).T
df = pd.DataFrame(a, columns=['a','b'])
print (df.head())
   a   b
0  1  51
1  2  52
2  3  53
3  4  54
4  5  55

def insertId(new_df, pos, col, start):
    new_df.insert(pos, col, range(start, len(new_df) + start))
    return new_df

#insert new column called s to DataFrame df in position 0 and values starts in 50
df = insertId(df, 0, 's', 50)
df = insertId(df, 2, 'new', 14)
print (df.head())

    s  a  new   b
0  50  1   14  51
1  51  2   15  52
2  52  3   16  53
3  53  4   17  54
4  54  5   18  55
</code>```

Body:
I want to add two columns in a dataframe, let say we have 50 rows in the dataframe, so my Column 1 values should be 1 to 50, and Column 2 values should be 51 to 100.

def insertId(new_df, str):
    df.insertId(0, str, range(1, 1 + len(df)))
    return df

The above function needs correction in order to meet my requirement, but unable to do so, as i am a beginner in Python.

Body:
Create first numpy array and pass it to DataFrame constructor:

a = np.arange(1, 101).reshape(2,-1).T
df1 = pd.DataFrame(a, columns=['a','b'])

print(df1.head())

   a   b
0  1  51
1  2  52
2  3  53
3  4  54
4  5  55

Last add it to original DataFrame:

df = df.join(df1)

Solution with your function with insert - is possible specify position of column pos, then column name col and last start number start:

#some Dataframe
a = np.arange(1, 101).reshape(2,-1).T
df = pd.DataFrame(a, columns=['a','b'])
print (df.head())
   a   b
0  1  51
1  2  52
2  3  53
3  4  54
4  5  55

def insertId(new_df, pos, col, start):
    new_df.insert(pos, col, range(start, len(new_df) + start))
    return new_df

#insert new column called s to DataFrame df in position 0 and values starts in 50
df = insertId(df, 0, 's', 50)
df = insertId(df, 2, 'new', 14)
print (df.head())

    s  a  new   b
0  50  1   14  51
1  51  2   15  52
2  52  3   16  53
3  53  4   17  54
4  54  5   18  55


问:
tables export into to csv files
In laravel 5.5 project I want some my tables export into to csv files and I get this http://www.maatwebsite.nl/laravel-excel/docs/export#export library
with code like:

```<code>$path = $directoriesArray[count($directoriesArray)-1];
Excel::create($filename, function($excel) use($dataArray) {
    $excel->sheet('file', function($sheet)  use($dataArray) {
        $sheet->fromArray( $dataArray );
    });
})->store('csv', $path)->export('csv');
</code>```

I upload 1 file ok, but as I need to upload several tables any
to the relative file I run the exporting function in a circle
and only the first file is uploaded. Is it restriction of the
browser(I tried in chromium, firefox) or if is the way to upload all files?

1) If there is a way just to write this csv file to disk without uploading?

2) If there is some way to make kind of buffering ( like ob_start ) of output data and write them to the files manually?

3) If there is some other tools that could do this?

Thanks!

答:
I did it like :

```<code><?php

$tablesArray= [  // array of tables to export
    'settings',
    'groups',
    'users',
];
$now_label= '_1';//strftime('%Y-%m-%d_%H_%M_%S');
$directories= [ public_path('uploads'), public_path('uploads/csv') , public_path('uploads/csv/loan_dump_'.$now_label) ];// to which directory export files
foreach( $tablesArray as $next_key=>$next_table_name ) {  // all tables
    $columnListing= \Schema::getColumnListing( $next_table_name );  // table columns

    if ( $next_table_name == 'settings' ) {
        $dataRows = Settings::all();
    }
    if ( $next_table_name == 'groups' ) {
        $dataRows = Group::all();
    }
    if ( $next_table_name == 'users' ) {
        $dataRows = User::all();
    }
    if ($dataRows == null) {
        die("-1 XXZ INVALID DATA");
    }
    $dataRowsArray = $dataRows->toArray();

    $writeRowsArray= [];
    $row= 0;
    foreach( $dataRowsArray as $next_key=>$nextDataRow ) {
        if (!empty($nextDataRow['created_at'])) {
            $nextDataRow['created_at'] = $this->dateTimeToDbFormat($nextDataRow['created_at']);
        }
        if (!empty($nextDataRow['updated_at'])) {
            $nextDataRow['updated_at'] = $this->dateTimeToDbFormat($nextDataRow['updated_at']);
        }
        if ($row == 0) { // first row with keys/file headers
            $writeRowsArray[] = $nextDataRow;
        } else {
            $writeRowsArray[] = array_values($nextDataRow);
        }
        $row++;
    }
    $this->writeArrayToCsvFile($writeRowsArray, $next_table_name, $directories);

} // foreach( $tablesArray as $next_key=>$next_table_name ) {  // all tables

public function writeArrayToCsvFile(array $dataArray, string $filename, array $directoriesArray) : int
{
    self::createDir(  $directoriesArray  );
    $path = $directoriesArray[count($directoriesArray)-1];
    Excel::create($filename, function($excel) use($dataArray) {
        $excel->sheet('file', function($sheet)  use($dataArray) {
            $sheet->fromArray( $dataArray );
        });
    })->store('csv', $path)->export('csv');
    return 1;
}

?>
</code>```

Only 1st file in $tablesArray array is exported ok.
If to comment 1st table, then next table would uploaded ok and so on.

What is strange file is uploaded twice : in $directories path and in "Downloads" directory(I am under kubuntu).

Title: tables export into to csv files

Body:
In laravel 5.5 project I want some my tables export into to csv files and I get this http://www.maatwebsite.nl/laravel-excel/docs/export#export library
with code like:

$path = $directoriesArray[count($directoriesArray)-1];
Excel::create($filename, function($excel) use($dataArray) {
    $excel->sheet('file', function($sheet)  use($dataArray) {
        $sheet->fromArray( $dataArray );
    });
})->store('csv', $path)->export('csv');

I upload 1 file ok, but as I need to upload several tables any
to the relative file I run the exporting function in a circle
and only the first file is uploaded. Is it restriction of the
browser(I tried in chromium, firefox) or if is the way to upload all files?

1) If there is a way just to write this csv file to disk without uploading?

2) If there is some way to make kind of buffering ( like ob_start ) of output data and write them to the files manually?

3) If there is some other tools that could do this?

Thanks!

Body:
I did it like :

<?php

$tablesArray= [  // array of tables to export
    'settings',
    'groups',
    'users',
];
$now_label= '_1';//strftime('%Y-%m-%d_%H_%M_%S');
$directories= [ public_path('uploads'), public_path('uploads/csv') , public_path('uploads/csv/loan_dump_'.$now_label) ];// to which directory export files
foreach( $tablesArray as $next_key=>$next_table_name ) {  // all tables
    $columnListing= \Schema::getColumnListing( $next_table_name );  // table columns

    if ( $next_table_name == 'settings' ) {
        $dataRows = Settings::all();
    }
    if ( $next_table_name == 'groups' ) {
        $dataRows = Group::all();
    }
    if ( $next_table_name == 'users' ) {
        $dataRows = User::all();
    }
    if ($dataRows == null) {
        die("-1 XXZ INVALID DATA");
    }
    $dataRowsArray = $dataRows->toArray();

    $writeRowsArray= [];
    $row= 0;
    foreach( $dataRowsArray as $next_key=>$nextDataRow ) {
        if (!empty($nextDataRow['created_at'])) {
            $nextDataRow['created_at'] = $this->dateTimeToDbFormat($nextDataRow['created_at']);
        }
        if (!empty($nextDataRow['updated_at'])) {
            $nextDataRow['updated_at'] = $this->dateTimeToDbFormat($nextDataRow['updated_at']);
        }
        if ($row == 0) { // first row with keys/file headers
            $writeRowsArray[] = $nextDataRow;
        } else {
            $writeRowsArray[] = array_values($nextDataRow);
        }
        $row++;
    }
    $this->writeArrayToCsvFile($writeRowsArray, $next_table_name, $directories);

} // foreach( $tablesArray as $next_key=>$next_table_name ) {  // all tables

public function writeArrayToCsvFile(array $dataArray, string $filename, array $directoriesArray) : int
{
    self::createDir(  $directoriesArray  );
    $path = $directoriesArray[count($directoriesArray)-1];
    Excel::create($filename, function($excel) use($dataArray) {
        $excel->sheet('file', function($sheet)  use($dataArray) {
            $sheet->fromArray( $dataArray );
        });
    })->store('csv', $path)->export('csv');
    return 1;
}

?>

Only 1st file in $tablesArray array is exported ok.
If to comment 1st table, then next table would uploaded ok and so on.

What is strange file is uploaded twice : in $directories path and in "Downloads" directory(I am under kubuntu).


问:
Hi, i need filter data from 4 table which stored as comma separated in table

Hi, As per image i have 3 table, 1. visits table in this table village_id value find in route_list villagemaster_id and if it available select doctors_id and using this doctors_id i need that all doctors name from user table using doctors id please give me solution.

答:
You can also use directive for it (It uses parseInt):

angular.module('app', [])
.directive('castToInteger', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.unshift(function(value) {
                return parseInt(value, 10);
            });
        }
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="app" ng-init="a=2;b=5">
<input type="text" cast-to-integer="true" name="a" ng-model="a" />
<input type="text" cast-to-integer="true" name="b" ng-model="b" />

<p>Total in dollar: {{ a + b }}</p>
</div>

</body>
</html></code>```

Body:
You can also use directive for it (It uses parseInt):

angular.module('app', [])
.directive('castToInteger', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.unshift(function(value) {
                return parseInt(value, 10);
            });
        }
    };
});

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="app" ng-init="a=2;b=5">
<input type="text" cast-to-integer="true" name="a" ng-model="a" />
<input type="text" cast-to-integer="true" name="b" ng-model="b" />

<p>Total in dollar: {{ a + b }}</p>
</div>

</body>
</html>


问:
One hot encoding with multiple ids, values in a large dataframe
I have a data frame of the following type

```<code>id  alphabet
20  a
20  b
30  b
30  c
</code>```

now, there are multiple non-unique ids. there are multiple non-unique alphabets also.

i would like the result in the following format

```<code>id  alphabet_a  alphabet_b  alphabet_c
    20  1           1         0
    30  0           1         1
</code>```

so, rows have been combined based on unique id, and one-hot encoding has been done on the values (alphabets).

how can this be done on a large scale data frame?

答:
You can use dcast like this

```<code>library(reshape2)

df <- read.table(text = "id  alphabet
             20  a
             20  b
             30  b
             30  c", header = T)

dcast(df, id~alphabet, fun = length)

  id a b c
1 20 1 1 0
2 30 0 1 1
</code>```

Body:
I have a data frame of the following type

id  alphabet
20  a
20  b
30  b
30  c

now, there are multiple non-unique ids. there are multiple non-unique alphabets also.

i would like the result in the following format

id  alphabet_a  alphabet_b  alphabet_c
    20  1           1         0
    30  0           1         1

so, rows have been combined based on unique id, and one-hot encoding has been done on the values (alphabets).

how can this be done on a large scale data frame?

Body:
You can use dcast like this

library(reshape2)

df <- read.table(text = "id  alphabet
             20  a
             20  b
             30  b
             30  c", header = T)

dcast(df, id~alphabet, fun = length)

  id a b c
1 20 1 1 0
2 30 0 1 1