问:
Javascript returning incorrect value from a Javascript object property
So, I have an array of Javascipt objects, that contain extra properties and information corresponding to the items in a select element.

When the user selects an element in the dropdown, it looks the item up in the Javascipt array, and is supposed to populate two other fields on the page with the relevant values from the corresponding Javascipt object.

Here is the js function:

```<code>    function pickedCode(who) {
        who = $(who);
        var opt = who.find(':selected');
        var val = opt.val();

        for (lc = 0; lc < codes.length; lc++) {
            var code = codes[lc];
            if (code.Id == val) {
                var amt = code.Dollars;
                alert(code.Dollars)
                $('input[field=amount]').val((amt > 0 ? amt : ''));
                $('textarea[field=text]').val(code.Text);
                break;
            }
        }
    }
</code>```

... here is the HTML where it is calling the function:

```<code><select onchange="pickedCode(this);" name="ctl00$ContentPlaceHolder1$lstCodes" id="ctl00_ContentPlaceHolder1_lstCodes">
    <option value=""></option>
    <option value="70">3-DAY NOTICE</option>
    <option value="156">A-ABSOLUTE TRANSCRIPT</option>
    <option value="47">ABORTED EVICTION</option>
    <option value="204">ACCESS AGREEMENT</option>
    <option value="174">ADD'L SERVES/MAILINGS</option>
    <option value="124">AFF IN OPP - COMMERCIAL</option>
</select>
</code>```

... and here is the array of Javascipt data:

```<code>var codes = [{
        "Id": 70,
        "Code": "3-DAY NOTICE",
        "Text": "Initiation of Non-Payment Proceeding.",
        "Dollars": "46.20"
    }, {
        "Id": 156,
        "Code": "A-ABSOLUTE TRANSCRIPT",
        "Text": "A-ABSOLUTE TRANSCRIPT",
        "Dollars": "0.00"
    }, {
        "Id": 47,
        "Code": "ABORTED EVICTION",
        "Text": "THE MARSHAL HAD TO ABORT TODAY'S SCHEDULED EVICTION AS ",
        "Dollars": "0.00"
    }, {
        "Id": 204,
        "Code": "ACCESS AGREEMENT",
        "Text": "ACCESS AGREEMENT",
        "Dollars": "0.00"
    }, {
        "Id": 174,
        "Code": "ADD'L SERVES/MAILINGS",
        "Text": "ADD'L MAILINGS",
        "Dollars": "0.00"
    }, {
        "Id": 124,
        "Code": "AFF IN OPP - COMMERCIAL",
        "Text": "Aff in Opp - COMMERCIAL",
        "Dollars": "85.05"
    }
]
</code>```

It is looking up and finding the proper element.

It is getting the text and setting it into the textarea properly.

The problem is with the property Dollars. For some reason it is always returning a value of "0.00" for the Dollars property, even for the items which have an amount greater than 0, and I cannot for the life of me figure out why. Originally, it was named Amount; I thought maybe that was a reserved word or something, so I changed it to Dollars. I also originally had it as an actual number, instead of a string, and still had the same problem (then it always returned 0). I thought maybe it was a problem in assigning it to the variable, so I alerted the actual property itself instead of the variable (the alert is just for debugging), but the property directly is returning 0.

I also thought maybe it was a type issue when checking the code.Id == val, but that can't be the issue, because it is actually finding the right item and getting the property text from it.

I found a couple other questions on here that were similar, but they all seemed to be related to the property itself being an array and the user not indexing into the property. Mine are not arrays though, the individual properties are all just straight up values.

I've tried this in both Firefox (57.0) and Google Chrome (62.0.3202.94) and even tried Opera (49.0.2725.47), and I get the same results in all three browsers.

Just to truly confuse myself, I decided to step through the client-side debugger in Firefox and see what happens. When viewing the source of the page, it clearly has the value of 46.2:

However when stepping through the function, and looking at the variables, when it pulls out that code from the array, it is loading a value of 0.00 into memory:

So, yeah... now I'm completely confused about what is going on, since the values it is loading into memory do not match the actual source. I did a search through the code to make sure the... and BAH! Looking at the screenshot sparked a thought and I figured it out. Details to come in an answer, for posterity.

答:
So it sparked in my thought process and figured this out as a combination of @sandy_22's comments and the screenshots from the Javascript debugger.

The array being held in code was assigned from the code-behind using a literal. such as

var codes = <asp:literal id="ltlCodes" runat="server"/> .

When changing one of the other dropdowns on the page, it would, through AJAX, rebind the literal based on the selected client (different clients have different fee amounts).

This all worked fine, and it would update the literal, the source got updated appropriately, and when I did a View Source I would see the updated array.

It did NOT however cause Javascript to reload the new array into the codes variable. So even though the source code showed the right array data, the in-memory variable itself still held the original copy of the data.

I took out the literal, so the client side code just became var codes = null; .

Then in server-side, when switching clients, and rebinding the codes, I now update them with a Javascript snippet as so:

AjaxManager.ResponseScripts.Add("codes = " & linqForNewArray() & ";") .

This way the in-memory variable actually gets updated, and now it all works fine.

Body:
So, I have an array of Javascipt objects, that contain extra properties and information corresponding to the items in a select element.

When the user selects an element in the dropdown, it looks the item up in the Javascipt array, and is supposed to populate two other fields on the page with the relevant values from the corresponding Javascipt object.

Here is the js function:

    function pickedCode(who) {
        who = $(who);
        var opt = who.find(':selected');
        var val = opt.val();

        for (lc = 0; lc < codes.length; lc++) {
            var code = codes[lc];
            if (code.Id == val) {
                var amt = code.Dollars;
                alert(code.Dollars)
                $('input[field=amount]').val((amt > 0 ? amt : ''));
                $('textarea[field=text]').val(code.Text);
                break;
            }
        }
    }

... here is the HTML where it is calling the function:

<select onchange="pickedCode(this);" name="ctl00$ContentPlaceHolder1$lstCodes" id="ctl00_ContentPlaceHolder1_lstCodes">
    <option value=""></option>
    <option value="70">3-DAY NOTICE</option>
    <option value="156">A-ABSOLUTE TRANSCRIPT</option>
    <option value="47">ABORTED EVICTION</option>
    <option value="204">ACCESS AGREEMENT</option>
    <option value="174">ADD'L SERVES/MAILINGS</option>
    <option value="124">AFF IN OPP - COMMERCIAL</option>
</select>

... and here is the array of Javascipt data:

var codes = [{
        "Id": 70,
        "Code": "3-DAY NOTICE",
        "Text": "Initiation of Non-Payment Proceeding.",
        "Dollars": "46.20"
    }, {
        "Id": 156,
        "Code": "A-ABSOLUTE TRANSCRIPT",
        "Text": "A-ABSOLUTE TRANSCRIPT",
        "Dollars": "0.00"
    }, {
        "Id": 47,
        "Code": "ABORTED EVICTION",
        "Text": "THE MARSHAL HAD TO ABORT TODAY'S SCHEDULED EVICTION AS ",
        "Dollars": "0.00"
    }, {
        "Id": 204,
        "Code": "ACCESS AGREEMENT",
        "Text": "ACCESS AGREEMENT",
        "Dollars": "0.00"
    }, {
        "Id": 174,
        "Code": "ADD'L SERVES/MAILINGS",
        "Text": "ADD'L MAILINGS",
        "Dollars": "0.00"
    }, {
        "Id": 124,
        "Code": "AFF IN OPP - COMMERCIAL",
        "Text": "Aff in Opp - COMMERCIAL",
        "Dollars": "85.05"
    }
]

It is looking up and finding the proper element.

It is getting the text and setting it into the textarea properly.

The problem is with the property Dollars. For some reason it is always returning a value of "0.00" for the Dollars property, even for the items which have an amount greater than 0, and I cannot for the life of me figure out why. Originally, it was named Amount; I thought maybe that was a reserved word or something, so I changed it to Dollars. I also originally had it as an actual number, instead of a string, and still had the same problem (then it always returned 0). I thought maybe it was a problem in assigning it to the variable, so I alerted the actual property itself instead of the variable (the alert is just for debugging), but the property directly is returning 0.

I also thought maybe it was a type issue when checking the code.Id == val, but that can't be the issue, because it is actually finding the right item and getting the property text from it.

I found a couple other questions on here that were similar, but they all seemed to be related to the property itself being an array and the user not indexing into the property. Mine are not arrays though, the individual properties are all just straight up values.

I've tried this in both Firefox (57.0) and Google Chrome (62.0.3202.94) and even tried Opera (49.0.2725.47), and I get the same results in all three browsers.

Just to truly confuse myself, I decided to step through the client-side debugger in Firefox and see what happens. When viewing the source of the page, it clearly has the value of 46.2:

However when stepping through the function, and looking at the variables, when it pulls out that code from the array, it is loading a value of 0.00 into memory:

So, yeah... now I'm completely confused about what is going on, since the values it is loading into memory do not match the actual source. I did a search through the code to make sure the... and BAH! Looking at the screenshot sparked a thought and I figured it out. Details to come in an answer, for posterity.


来源: stackexchange

问:
How do you PIVOT on a Bit datatype in SQL Server?
This is probably a very simple question.  All I want to really do is to make the column into a row whose data type is a bit.  </p>

<p>SUM, MIN, MAX doesn't work on bits.  COUNT works but I really don't want to count. I just want to move all the stuff from columns into rows like if I took a pair of scissors, cut the information and moved it -90 degrees.    </p>

答:
The solution to this is to cast the bit data type to a data type that is accepted in aggregate functions.  For example,

```<code>SELECT MAX(CAST(BitColumn AS TINYINT))
</code>```

casts the BitColumn value to a tinyint datatype.  The statement returns 1 if BitColumn contains at least one value of 1; otherwise, it returns 0 (unless all values are null).

Assuming the following:

```<code>CREATE TABLE MyTable (ID INT, Name VARCHAR(10), BitColumn BIT);

INSERT INTO MyTable VALUES (1, 'Name 1', 1);
INSERT INTO MyTable VALUES (1, 'Name 2', 0);
INSERT INTO MyTable VALUES (1, 'Name 3', 1);
INSERT INTO MyTable VALUES (2, 'Name 1', 1);
INSERT INTO MyTable VALUES (2, 'Name 2', 1);
INSERT INTO MyTable VALUES (2, 'Name 3', 1);
INSERT INTO MyTable VALUES (3, 'Name 1', 0);
INSERT INTO MyTable VALUES (3, 'Name 2', 0);
INSERT INTO MyTable VALUES (3, 'Name 3', 0);
</code>```

You can pivot this data using the following query

```<code>SELECT ID,
    CAST(MAX(CASE Name WHEN 'Name 1' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 1],
    CAST(MAX(CASE Name WHEN 'Name 2' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 2],
    CAST(MAX(CASE Name WHEN 'Name 3' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 3]
FROM MyTable
GROUP BY ID
ORDER BY ID
</code>```

In this case, the max BitColumn value is converted back from tinyint to bit.  This is not required.

The results are

```<code>ID  Name 1  Name 2  Name 3
--------------------------
1   1       0       1
2   1       1       1
3   0       0       0
</code>```

An alternative query, for SQL Server 2005 and later, uses the PIVOT operator

```<code>SELECT ID, [Name 1], [Name 2], [Name 3]
FROM
    (
    SELECT ID, Name, CAST(BitColumn AS TINYINT) AS BitColumn
    FROM MyTable
    ) as SourceTable
PIVOT
(
MAX(BitColumn) FOR Name in ([Name 1], [Name 2], [Name 3])
) AS PivotTable
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is probably a very simple question.  All I want to really do is to make the column into a row whose data type is a bit.

SUM, MIN, MAX doesn't work on bits.  COUNT works but I really don't want to count. I just want to move all the stuff from columns into rows like if I took a pair of scissors, cut the information and moved it -90 degrees.

Body:
The solution to this is to cast the bit data type to a data type that is accepted in aggregate functions.  For example,

SELECT MAX(CAST(BitColumn AS TINYINT))

casts the BitColumn value to a tinyint datatype.  The statement returns 1 if BitColumn contains at least one value of 1; otherwise, it returns 0 (unless all values are null).

Assuming the following:

CREATE TABLE MyTable (ID INT, Name VARCHAR(10), BitColumn BIT);

INSERT INTO MyTable VALUES (1, 'Name 1', 1);
INSERT INTO MyTable VALUES (1, 'Name 2', 0);
INSERT INTO MyTable VALUES (1, 'Name 3', 1);
INSERT INTO MyTable VALUES (2, 'Name 1', 1);
INSERT INTO MyTable VALUES (2, 'Name 2', 1);
INSERT INTO MyTable VALUES (2, 'Name 3', 1);
INSERT INTO MyTable VALUES (3, 'Name 1', 0);
INSERT INTO MyTable VALUES (3, 'Name 2', 0);
INSERT INTO MyTable VALUES (3, 'Name 3', 0);

You can pivot this data using the following query

SELECT ID,
    CAST(MAX(CASE Name WHEN 'Name 1' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 1],
    CAST(MAX(CASE Name WHEN 'Name 2' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 2],
    CAST(MAX(CASE Name WHEN 'Name 3' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 3]
FROM MyTable
GROUP BY ID
ORDER BY ID

In this case, the max BitColumn value is converted back from tinyint to bit.  This is not required.

The results are

ID  Name 1  Name 2  Name 3
--------------------------
1   1       0       1
2   1       1       1
3   0       0       0

An alternative query, for SQL Server 2005 and later, uses the PIVOT operator

SELECT ID, [Name 1], [Name 2], [Name 3]
FROM
    (
    SELECT ID, Name, CAST(BitColumn AS TINYINT) AS BitColumn
    FROM MyTable
    ) as SourceTable
PIVOT
(
MAX(BitColumn) FOR Name in ([Name 1], [Name 2], [Name 3])
) AS PivotTable


问:
Bootstrap "read more" button - how to collapse and change button text with no time difference?
I have a layout created with bootstrap and there is this “read more” button that expands text. When text is expanded it changes to “show less”. My problem is that when user clicks to “show less” button, button-text firstly changes back to “read more” and only THEN text(paragraph) is collapsed. And this time difference is noticeable. But is there a way to make button change its text after the text is collapsed or somehow make this time difference less noticeable?

In my js file there’s only code for button text changing, and text toggling is entirely on bootstrap, maybe I shouldn’t use bootstrap for this particular button?

Note that my problem is not about changing button text from “read more” to “show less” itself, I know there’s a lot of solutions around.

Markup for "read more" button:

```<code><p>Initial text
  <span id="moreText" class="collapse">more text here...</span>
  <a id="readMore" data-toggle="collapse" href="#moreText">
    Read More
  </a>
</p>
</code>```

JS for button:

```<code>$(function() {
    $('#readMore').click(function() {
     $(this).text(function(i,def) {
        return def=='Read More' ?  'Show Less' : 'Read More';
    });
})

});
</code>```

答:
I had the same problem, I solved it through a little of css and Bootstrap 4

```<code>#summary {
  font-size: 14px;
  line-height: 1.5;
}

#summary p.collapse:not(.show) {
    height: 42px !important;
    overflow: hidden;

    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

#summary p.collapsing {
    min-height: 42px !important;
}

#summary a.collapsed:after  {
    content: '+ Read More';
}

#summary a:not(.collapsed):after {
    content: '- Read Less';
}
</code>```

Here example -> Read Less - Bootstrap 4

ContentLicense: CC BY-SA 4.0

Body:
I have a layout created with bootstrap and there is this “read more” button that expands text. When text is expanded it changes to “show less”. My problem is that when user clicks to “show less” button, button-text firstly changes back to “read more” and only THEN text(paragraph) is collapsed. And this time difference is noticeable. But is there a way to make button change its text after the text is collapsed or somehow make this time difference less noticeable?

In my js file there’s only code for button text changing, and text toggling is entirely on bootstrap, maybe I shouldn’t use bootstrap for this particular button?

Note that my problem is not about changing button text from “read more” to “show less” itself, I know there’s a lot of solutions around.

Markup for "read more" button:

Initial text
  more text here...

    Read More

JS for button:

$(function() {
    $('#readMore').click(function() {
     $(this).text(function(i,def) {
        return def=='Read More' ?  'Show Less' : 'Read More';
    });
})

});

Body:
I had the same problem, I solved it through a little of css and Bootstrap 4

#summary {
  font-size: 14px;
  line-height: 1.5;
}

#summary p.collapse:not(.show) {
    height: 42px !important;
    overflow: hidden;

    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

#summary p.collapsing {
    min-height: 42px !important;
}

#summary a.collapsed:after  {
    content: '+ Read More';
}

#summary a:not(.collapsed):after {
    content: '- Read Less';
}

Here example -> Read Less - Bootstrap 4

ContentLicense: CC BY-SA 3.0


问:
BLE hardware in smartphone
I have Micromax canvas Nitro smartphone ,It works on android kitkat 4.4.Based on the specs it supports  Bluetooth 4.0.(no info whether LE is supported)

I was trying to check whether it supports Bluetooth Low Energy by following methods :

1)I downloaded some BLE apps from google playstore & tried opening it. It showed BLE not supported.Most of the apps showed the same info.Before concluding i tried the next method.

2)I opened the settings in the phone and performed a normal scan in Bluetooth menu.I have a BLE transmitter device which advertises often.

To my surprise My phone scanned that ble device and i paired it ! but i couldnt use any android ble apps to scan and see its characteristics !

So does it mean that my phone have BLE hardware which scans BLE devices but no appropiate BLE stack ?.

But why while using most of the BLE apps it is showing BLE not supported  ?

答:
The Discovery phase of Classic Bluetooth and Bluetooth Low Energy (Smart) is almost identical.

Many classic chips can actually enumerate the BLE devices, even down to discovering services, but not actually communicate with them. A good stack will mask out what they cant communicate with, but looks like you have found some sloppy code.

Title: BLE hardware in smartphone


问:
Python cmd timer creation
I have the following code:

```<code>class OCP(cmd.Cmd):
    intro = 'Welcome to the  OCP shell.   Type help or ? to list commands.\n'
    prompt = '> '
    file = None

    def do_connect(self, arg):
        'connect'

        logging.debug('> connect')
        connect()
</code>```

I have this code that uses cmd from python. What I want is to run a timer everytime the user enters connect for 30 secs.
If after the 30 secs the user still didn't type anything, it prints a "disconnected" state.

How should I do this?

答:
Just to get you started...

```<code>import time

time.sleep(30)

print('Disconnected')
</code>```

Afiak there is no monitor for "any" key press without input(), which stops your code from running.

Title: Python cmd timer creation

Body:
I have the following code:

class OCP(cmd.Cmd):
    intro = 'Welcome to the  OCP shell.   Type help or ? to list commands.\n'
    prompt = '> '
    file = None

    def do_connect(self, arg):
        'connect'

        logging.debug('> connect')
        connect()

I have this code that uses cmd from python. What I want is to run a timer everytime the user enters connect for 30 secs.
If after the 30 secs the user still didn't type anything, it prints a "disconnected" state.

How should I do this?

Body:
Just to get you started...

import time

time.sleep(30)

print('Disconnected')

Afiak there is no monitor for "any" key press without input(), which stops your code from running.


问:
Ionic 3 local notification every few hours
So I want my app to fire notification every 3 hours by users choice when to start this,
there is a Toggle on the HTML that if the user turn it on I want it to pop up dialog that will ask him the first time he eats on the day and then the app will notify him to eat every 3 hours from this hour.
SO I tried to start this and it looks really hard.
so far I got the notification and didn't figure how to fire the notification every 3 hours,
this is my code:

```<code>import { Component } from '@angular/core';
import { NavController, NavParams, IonicPage , AlertController , Platform } from 'ionic-angular';
import { LocalNotifications } from '@ionic-native/local-notifications';

@IonicPage()
@Component({
  selector: 'page-settings',
  templateUrl: 'settings.html'
})
export class Settings {

  mealNotifierToggle : boolean = false ;

  constructor(public navCtrl: NavController, public navParams: NavParams , private plt: Platform,
  private localNotifications: LocalNotifications) {
  }

  scheduleNotification(){
    this.localNotifications.schedule({
      id: 1,
      title: "Meal Time",
      text: "Time to eat !",
      every: 'minute'
    });
  }
}
</code>```

There is any good explanations about how to save the 'Toggle' state even when the app is closed and how to fire the notification every 3 hours?
An explanation for the pop up dialog will be sweet but I really want to try and do it by myself for now, If I won't succeed I will edit this question.
Thanks a lot!

Matan

答: Take a look at the AlertController and especially the 'confirm' part.</p>

Body:
So I want my app to fire notification every 3 hours by users choice when to start this,
there is a Toggle on the HTML that if the user turn it on I want it to pop up dialog that will ask him the first time he eats on the day and then the app will notify him to eat every 3 hours from this hour.
SO I tried to start this and it looks really hard.
so far I got the notification and didn't figure how to fire the notification every 3 hours,
this is my code:

import { Component } from '@angular/core';
import { NavController, NavParams, IonicPage , AlertController , Platform } from 'ionic-angular';
import { LocalNotifications } from '@ionic-native/local-notifications';

@IonicPage()
@Component({
  selector: 'page-settings',
  templateUrl: 'settings.html'
})
export class Settings {

  mealNotifierToggle : boolean = false ;

  constructor(public navCtrl: NavController, public navParams: NavParams , private plt: Platform,
  private localNotifications: LocalNotifications) {
  }

  scheduleNotification(){
    this.localNotifications.schedule({
      id: 1,
      title: "Meal Time",
      text: "Time to eat !",
      every: 'minute'
    });
  }
}

There is any good explanations about how to save the 'Toggle' state even when the app is closed and how to fire the notification every 3 hours?
An explanation for the pop up dialog will be sweet but I really want to try and do it by myself for now, If I won't succeed I will edit this question.
Thanks a lot!

Matan


问:
I cannot install npm package error strict mode
When I install sudo npm i sharp -g

```<code>/usr/lib/node_modules/sharp/binding.js:3
const fs = require('fs');
^^^^^

SyntaxError: Use of const in strict mode.
</code>```

When I try install some packages with ES6 syntax

After upadate nodejs and npm my versions is

```<code>node -v  -----> v6.9.4
npm -v   -----> 4.1.2
node-gyp -v ----> v3.4.0
</code>```

I tried to use this command

```<code>sudo npm cache clean -f
</code>```

But it does not work...

答:
I uninstalled Node and reinstalled from the official site. It appears I had an old version of node in there causing issues. Installs worked just fine after that.

https://nodejs.org/en/download/

Body:
When I install sudo npm i sharp -g

/usr/lib/node_modules/sharp/binding.js:3
const fs = require('fs');
^^^^^

SyntaxError: Use of const in strict mode.

When I try install some packages with ES6 syntax

After upadate nodejs and npm my versions is

node -v  -----> v6.9.4
npm -v   -----> 4.1.2
node-gyp -v ----> v3.4.0

I tried to use this command

sudo npm cache clean -f

But it does not work...


问:
Angular 5 getting array issue with data from service to component to template
Trying to display data in template HTML from a component to service call which calls and returns an API, but I'm getting this error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML

```<code><li *ngFor="let item of testing">
   <a [routerLink]="[item.url]" >
    <span>{{item.name}}</span>
   </a>
</li>
</code>```

Component

```<code>testing: any;

this.arsSevice.getMenu()
     .subscribe(
         result => {
            this.testing = result;
            console.log('menu',result);
      },
      error => {
         console.log('menu error', error);
      }
      )
</code>```

Service:

```<code>getMenu()  {
    return this.http.post(this.menuUrl, JSON.stringify({
        "UserID": 61525,
        "AppID": 15,
        "NavAppID":null,
        "AppGroupID": 116,
        "SelectedCaseID": 0,
        "SelectedRoleID":0
    }), httpOptions)
        .map((response: Response)=> {
            return response;
        })
}
</code>```

Image screenshot of the data

Update

I see a data problem

"menu" has data:  and it what is HERE and NOT working.

the working one is from a different API call
Notice that is has

data: Array(16)

How can I fix my data from object to array ?

答:
That's because you're trying to iterate through data object. Try:

```<code><li *ngFor="let item of testing.Menu1Items">
</code>```

Body:
Trying to display data in template HTML from a component to service call which calls and returns an API, but I'm getting this error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML

    {{item.name}}

Component

testing: any;

this.arsSevice.getMenu()
     .subscribe(
         result => {
            this.testing = result;
            console.log('menu',result);
      },
      error => {
         console.log('menu error', error);
      }
      )

Service:

getMenu()  {
    return this.http.post(this.menuUrl, JSON.stringify({
        "UserID": 61525,
        "AppID": 15,
        "NavAppID":null,
        "AppGroupID": 116,
        "SelectedCaseID": 0,
        "SelectedRoleID":0
    }), httpOptions)
        .map((response: Response)=> {
            return response;
        })
}

Image screenshot of the data

Update

I see a data problem

"menu" has data:  and it what is HERE and NOT working.

the working one is from a different API call
Notice that is has

data: Array(16)

How can I fix my data from object to array ?

Body:
That's because you're trying to iterate through data object. Try:

<li *ngFor="let item of testing.Menu1Items">


问:
Remove NaN in Nested iif in SSRS expression
New to SQL-SSRS

How do I add functionality to the below code to change returned NaN values to 0 or blank?  What I think is happening is in situations that the sum of Agreed and Disagreed = 0 I am getting this Nan.  I think this would be easier for me if I wasnt dealing with the Agreed and Disagreed categories.  Again, new to SQL programming.  Any help would be greatly appreciated.

```<code>=(Sum(iif(Fields!Response.Value = "Agreed",Fields!Days.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Days.Value,0)))/(Sum(iif(Fields!Response.Value = "Agreed",Fields!Fq.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Fq.Value,0)))
</code>```

答:
```<code>Public Function Divider (ByVal Dividend As Double, ByVal Divisor As Double)
If IsNothing(Divisor) Or Divisor = 0
  Return 0
Else
  Return Dividend/Divisor
End If
End Function
</code>```

this function enables you to write a custom code which fixes all problems with Nan .
this can be called by below

```<code>=Code.Divider(Fields!FieldA.Value, Fields!FieldB.Value)
</code>```

your code is as below

```<code>=Code.Divider(((Sum(iif(Fields!Response.Value = "Agreed",Fields!Days.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Days.Value,0))), ((Sum(iif(Fields!Response.Value = "Agreed",Fields!Fq.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Fq.Value,0)))))
</code>```

Body:
New to SQL-SSRS

How do I add functionality to the below code to change returned NaN values to 0 or blank?  What I think is happening is in situations that the sum of Agreed and Disagreed = 0 I am getting this Nan.  I think this would be easier for me if I wasnt dealing with the Agreed and Disagreed categories.  Again, new to SQL programming.  Any help would be greatly appreciated.

=(Sum(iif(Fields!Response.Value = "Agreed",Fields!Days.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Days.Value,0)))/(Sum(iif(Fields!Response.Value = "Agreed",Fields!Fq.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Fq.Value,0)))

Body:
Public Function Divider (ByVal Dividend As Double, ByVal Divisor As Double)
If IsNothing(Divisor) Or Divisor = 0
  Return 0
Else
  Return Dividend/Divisor
End If
End Function

this function enables you to write a custom code which fixes all problems with Nan .
this can be called by below

=Code.Divider(Fields!FieldA.Value, Fields!FieldB.Value)

your code is as below

=Code.Divider(((Sum(iif(Fields!Response.Value = "Agreed",Fields!Days.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Days.Value,0))), ((Sum(iif(Fields!Response.Value = "Agreed",Fields!Fq.Value,0)) + Sum(iif(Fields!Response.Value = "Disagreed",Fields!Fq.Value,0)))))


问:
Convert Java to C# with a tool, or manually?
I have a Java project which I'd like to convert to C#, and after looking here and elsewhere found out about a tool, Sharpen.

However, in order to get it up and running (I'm new to Java) the site linked above describes grabbing the source and building it as a plugin to the Eclipse IDE, which I'd rather not do since I don't ordinarily do Java.

Does anyone know whether a standalone EXE exists which can simply utilize Sharpen to take a given Java project and run it through the wringer to convert it to C#? Or are Java and C# similar enough that it should be pretty straightforward to just port the code over to .NET manually?

答:
I would personally do it manually. You can reflect on where the Java design choices simply aren't appropriate for .NET, and end up with idiomatic C# code instead of code which looks very much like C# with a Java accent.

It also means you're more likely to understand the code at the end :)


问:
Fast way to initialize child Kotlin class with parent class' instance properties
I use Java library that defines a JSON model class named A. This class contains a lot of properties, e. g., 26 String properties named from a to z and does not have a constructor for them.

I'd like to extend this class in Kotlin with a new JSON property, lateinit var aa: String (derived class will be B), and to have a fast way to create an instance of B by copying properties of existing A instance.

I can serialize A and deserialize the resultant JSON to B. Are there any other fast solutions to do this without serializing/deserializing, e.g. by using any Kotin/Java methods or Intellij IDEA facilities?

答:
Assuming you only have 1 constructor, here you go:

```<code>inline fun <reified D> convert(c: Any) : D {
    val list = mutableListOf<Any>()
    c::class.java.declaredFields.forEach {
        it.isAccessible = true
        list.add(it.get(c) as String)
        it.isAccessible = false
    }

    val constructor = D::class.java.declaredConstructors[0]
    return constructor.newInstance(*list.toTypedArray()) as D
}
</code>```

Full use:

```<code>package com.erezbiox1

fun main(args: Array<String>){

    val A = A("Hey", "Hello")
    val B = convert<B>(A)
    B.print()

}

inline fun <reified D> convert(c: Any) : D {
    val list = mutableListOf<Any>()
    c::class.java.declaredFields.forEach {
        it.isAccessible = true
        list.add(it.get(c) as String)
        it.isAccessible = false
    }

    val constructor = D::class.java.declaredConstructors[0]
    return constructor.newInstance(*list.toTypedArray()) as D
}

class A(val a: String, val b: String){
    fun print(){
        println("Value is: $a, $b")
    }
}

class B(val a: String, val b: String) {
    fun print(){
        println("Value is: $a, $b")
    }
}
</code>```

Body:
Assuming you only have 1 constructor, here you go:

inline fun <reified D> convert(c: Any) : D {
    val list = mutableListOf<Any>()
    c::class.java.declaredFields.forEach {
        it.isAccessible = true
        list.add(it.get(c) as String)
        it.isAccessible = false
    }

    val constructor = D::class.java.declaredConstructors[0]
    return constructor.newInstance(*list.toTypedArray()) as D
}

Full use:

package com.erezbiox1

fun main(args: Array<String>){

    val A = A("Hey", "Hello")
    val B = convert<B>(A)
    B.print()

}

inline fun <reified D> convert(c: Any) : D {
    val list = mutableListOf<Any>()
    c::class.java.declaredFields.forEach {
        it.isAccessible = true
        list.add(it.get(c) as String)
        it.isAccessible = false
    }

    val constructor = D::class.java.declaredConstructors[0]
    return constructor.newInstance(*list.toTypedArray()) as D
}

class A(val a: String, val b: String){
    fun print(){
        println("Value is: $a, $b")
    }
}

class B(val a: String, val b: String) {
    fun print(){
        println("Value is: $a, $b")
    }
}


问:
Add DOCTYPE to retrofit POST xml request body
I'm using retrofit 2 and java to make API calls.  I have successfully made some POST requests but trying to add a new call has stumped me.

The body required is as follows:

```<code><!DOCTYPE ourapi SYSTEM "nameOfTheDTD.dtd">
<mainPart version="7.0">
   <some other stuff>
</mainPart>
</code>```

I can build the mainPart of the request body using the usual @Root, @Path and @Element simpleframework.xml annotations but have no idea how to add the DOCTYPE line.

Can anyone point me in the right direction please?

答:
I couldn't find any nice way to do it using annotations to build the xml object, so workaround was to create the xml as a string then parse it as text/plain to create an okhttp3 RequestBody and .execute that.</p>

```<code>String xml = "<!DOCTYPE ourapi SYSTEM \"dtdName.dtd\">\n" +
            "<otherStuff>"\n+
            "</otherStuff>";

RequestBody requestBody =
         RequestBody.create(MediaType.parse("text/plain"), xml);

return ourApi.post(requestBody).execute();
</code>```

Body:
I'm using retrofit 2 and java to make API calls.  I have successfully made some POST requests but trying to add a new call has stumped me.

The body required is as follows:

<!DOCTYPE ourapi SYSTEM "nameOfTheDTD.dtd">
<mainPart version="7.0">
   <some other stuff>
</mainPart>

I can build the mainPart of the request body using the usual @Root, @Path and @Element simpleframework.xml annotations but have no idea how to add the DOCTYPE line.

Can anyone point me in the right direction please?

Body:
I couldn't find any nice way to do it using annotations to build the xml object, so workaround was to create the xml as a string then parse it as text/plain to create an okhttp3 RequestBody and .execute that.

String xml = "<!DOCTYPE ourapi SYSTEM \"dtdName.dtd\">\n" +
            "<otherStuff>"\n+
            "</otherStuff>";

RequestBody requestBody =
         RequestBody.create(MediaType.parse("text/plain"), xml);

return ourApi.post(requestBody).execute();


问:
Show an image from storage Laravel5.5
This is how i'm storing the image

```<code>if ($request->hasFile('photo')) {
$request->file('photo')->store('public/images');
$filename = $request->file('photo')->hashName();
$authUser = Auth::user();
Auth::user()->photoUrl = $filename;
$authUser->likes=0;
$authUser->save();
}
</code>```

i already did a php artisan storage:links,file is in the storage/app/images folder also the filename stored in the database but i still cannot get the image when doing photoUrl) }}">

its telling me:

Failed to load resource: the server responded with a status of 404 (Not Found)

答:
Try this

yourPhoto_id)->photo) }}" alt="">	```

@Ayèch Hamza did you try it?

Title: Show an image from storage Laravel5.5

Body:
This is how i'm storing the image

if ($request->hasFile('photo')) {
$request->file('photo')->store('public/images');
$filename = $request->file('photo')->hashName();
$authUser = Auth::user();
Auth::user()->photoUrl = $filename;
$authUser->likes=0;
$authUser->save();
}

i already did a php artisan storage:links,file is in the storage/app/images folder also the filename stored in the database but i still cannot get the image when doing photoUrl) }}">

its telling me:

Failed to load resource: the server responded with a status of 404 (Not Found)

Body:
Try this

<td><img height='' src="{{ url('images/' . \App\Photo::find($user->yourPhoto_id)->photo) }}" alt=""></td>

@Ayèch Hamza did you try it?


问:
How to get unique values in an array
How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java's hashmap in JavaScript?

I am going to be using JavaScript and jQuery only. No additional libraries can be used.

答:
Fast, compact, no nested loops, works with any object not just strings and numbers, takes a predicate, and only 5 lines of code!!

```<code>function findUnique(arr, predicate) {
  var found = {};
  arr.forEach(d => {
    found[predicate(d)] = d;
  });
  return Object.keys(found).map(key => found[key]);
}
</code>```

Example: To find unique items by type:

```<code>var things = [
  { name: 'charm', type: 'quark'},
  { name: 'strange', type: 'quark'},
  { name: 'proton', type: 'boson'},
];

var result = findUnique(things, d => d.type);
//  [
//    { name: 'charm', type: 'quark'},
//    { name: 'proton', type: 'boson'}
//  ]
</code>```

If you want it to find the first unique item instead of the last add a found.hasOwnPropery() check in there.

Title: How to get unique values in an array

Body:
Fast, compact, no nested loops, works with any object not just strings and numbers, takes a predicate, and only 5 lines of code!!

function findUnique(arr, predicate) {
  var found = {};
  arr.forEach(d => {
    found[predicate(d)] = d;
  });
  return Object.keys(found).map(key => found[key]);
}

Example: To find unique items by type:

var things = [
  { name: 'charm', type: 'quark'},
  { name: 'strange', type: 'quark'},
  { name: 'proton', type: 'boson'},
];

var result = findUnique(things, d => d.type);
//  [
//    { name: 'charm', type: 'quark'},
//    { name: 'proton', type: 'boson'}
//  ]

If you want it to find the first unique item instead of the last add a found.hasOwnPropery() check in there.


问:
Inserting data from JSON file into HTML
I'm trying to get data about year from JSON files according to my selection from a dropdown box, by an each loop. I want my code to be like this: click on a value year in dropdown box then a table shows up with all the object's values from the file with the same year that was selected.

Here is my code :

```<code><!DOCTYPE html>
<html>
  <body>
    <form>Select a YEAR :
      <select id="Selections">
        <option value="year1">year1</option>
        <option value="year2">year2</option>
      </select>
    </form>
    <button type="button" onclick="run()">Try it</button>
    <p id="result">    </p>
    <script>
        function run () {
            var x = document.getElementById("Selections").value;
            if (x == "year1") {
                document.getElementById("result").innerHTML = "the first year";
                $.getJSON("year1.json", function(json) {
                    $.each(json, function (i,item){
                        $('#tblinfo').append('<tr> <th>'+item.year+'</th>
                            <th>'+item.eposide+'</th></tr>');
                        })
                    });
            } else if (x == "year2") {
                document.getElementById("result").innerHTML = "the second year";
                $.getJSON("year2.json", function (json) {
                    $.each(json, function (i,item){
                    $('#tblinfo').append('<tr> <th>'+item.year+'</th>
                        <th>'+item.eposide+'</th></tr>');
                    })
                });
            }
        }
    </script>
    <table id="tblinfo" border=" 1px solid black" style="width:100%"></table>
  </body>
</html>
</code>```

My JSON files:

year1.json is:

```<code>[
  {"year":"1995", "eposide":"1"},
  {"year":"1995", "eposide":"2"},
  {"year":"1995","eposide":"3"}
]
</code>```

year2.json is:

```<code>[
  {"year":"1994", "eposide":"1"},
  {"year":"1994", "eposide":"2"},
  {"year":"1994","eposide":"3"}
]
</code>```

Somehow I can't get any value in the table.

答:
```<code> <!doctype html>
<html>
<body>
    Select YEAR :
    <select id="Selections" onchange="run()">
        <option value="0">choose:</option>
        <option value="1">year1</option>
        <option value="2">year2</option>
    </select>
    <p id="result"></p>
    <template id="temp">
        <span class="year"></span>
        <span class="episode"></span><br>
    </template>

    <script>
    let url;
    function run(){
        let e=document.querySelector("#Selections");
        let year=e.options[e.selectedIndex].value;
        if(year==1)url="year1.json";
        else if (year==2)url="year2.json";
        getJson();
    }

    async function getJson() {
        let temp=document.querySelector("#temp");
        let container = document.querySelector("#result");
        let jsonObjects = await fetch(url);
        let items = await jsonObjects.json();
        container.innerHTML="";
        items.forEach(function(item) {
            let clon = temp.cloneNode(true).content;
            clon.querySelector(".year").textContent = item.year;
            clon.querySelector(".episode").textContent = item.eposide;
            container.appendChild(clon);
        });
    }
    </script>
    </body>
</html>
</code>```

Title: Inserting data from JSON file into HTML

Body:
I'm trying to get data about year from JSON files according to my selection from a dropdown box, by an each loop. I want my code to be like this: click on a value year in dropdown box then a table shows up with all the object's values from the file with the same year that was selected.

Here is my code :

<!DOCTYPE html>

    <form>Select a YEAR :
      <select id="Selections">
        <option value="year1">year1</option>
        <option value="year2">year2</option>
      </select>
    </form>
    <button type="button" onclick="run()">Try it</button>

My JSON files:

year1.json is:

[
  {"year":"1995", "eposide":"1"},
  {"year":"1995", "eposide":"2"},
  {"year":"1995","eposide":"3"}
]

year2.json is:

[
  {"year":"1994", "eposide":"1"},
  {"year":"1994", "eposide":"2"},
  {"year":"1994","eposide":"3"}
]

Somehow I can't get any value in the table.


问:
Bootstrap navbar dropdown glitch
So, I just copied a code snippet for the navbar form from bootswatch and directly imported the required JQuery, bootstrap css and js files as you can see in the snippet below. It is being responsive when the browser is resized but when I click the button to get the dropdown menu of the navbar it glitches and doesn't go down and stay there but toggles back on its own.

No tweaks or changes has been made in the code and it works fine on the bootswatch website but it doesn't here. Can anyone explain why and give a fix?

<link rel="stylesheet" href="https://bootswatch.com/4/united/bootstrap.min.css">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation" style="">

  </button>

        Home (current)

        Features

        Pricing

        About

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" placeholder="Search" type="text">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>

```

答:
The problem is in the very thing you mentioned you changed; the Bootstrap and jQuery files. You're using the jQuery from Bootstrap 3.3.7, and the CSS from Bootstrap 4, which have conflicts. Also note that Bootstrap 4 additionally needs Popper.js.

Changing both Bootstrap files to use Bootstrap 4 (and including Popper) fixes this problem:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation" style="">

  </button>

        Home (current)

        Features

        Pricing

        About

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" placeholder="Search" type="text">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>

```

Hope this helps! :)

Title: Bootstrap navbar dropdown glitch

Body:
The problem is in the very thing you mentioned you changed; the Bootstrap and jQuery files. You're using the jQuery from Bootstrap 3.3.7, and the CSS from Bootstrap 4, which have conflicts. Also note that Bootstrap 4 additionally needs Popper.js.

Changing both Bootstrap files to use Bootstrap 4 (and including Popper) fixes this problem:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation" style="">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarColor02">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">About</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" placeholder="Search" type="text">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

Hope this helps! :)


答:
That is because bootswatch is using bootstrap 4.0 beta rather than 3.and for bootstrap4 you will need popper.js

see the demo below

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">

                </button>

        Home (current)

        Features

        Pricing

        About

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>

```

EDIT

While trying to include popper.js keep in mind to use only the umd specific directory, not esm or any other. See this previous issue for details

Title: Bootstrap navbar dropdown glitch

Body:
So, I just copied a code snippet for the navbar form from bootswatch and directly imported the required JQuery, bootstrap css and js files as you can see in the snippet below. It is being responsive when the browser is resized but when I click the button to get the dropdown menu of the navbar it glitches and doesn't go down and stay there but toggles back on its own.

No tweaks or changes has been made in the code and it works fine on the bootswatch website but it doesn't here. Can anyone explain why and give a fix?

<link rel="stylesheet" href="https://bootswatch.com/4/united/bootstrap.min.css">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor02" aria-controls="navbarColor02" aria-expanded="false" aria-label="Toggle navigation" style="">

  </button>

        Home (current)

        Features

        Pricing

        About

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" placeholder="Search" type="text">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>

Body:
That is because bootswatch is using bootstrap 4.0 beta rather than 3.and for bootstrap4 you will need popper.js

see the demo below

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.13.0/umd/popper.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation" style="">
                  <span class="navbar-toggler-icon"></span>
                </button>

  <div class="collapse navbar-collapse" id="navbarColor01">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">About</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

EDIT

While trying to include popper.js keep in mind to use only the umd specific directory, not esm or any other. See this previous issue for details


问:
Python - Remove one letter in a string
I want to delete a variable (which is a string) from a list of strings. So basically:

```<code>list = ["A", "G", "T", "C"]
number = 2
newlist = ["A", "G", "T", "C"] - list[number]
</code>```

This should then give:

```<code>newlist = ["A", "G", "C"]
</code>```

But when I try this it gives me this error message:

```<code>Traceback (most recent call last):
  File "mini.py", line 3, in <module>
    newlist = ["A", "G", "T", "C"] - list[number]
TypeError: unsupported operand type(s) for -: 'list' and 'str'
</code>```

How do I fix this?

Thanks in advance!

答:
There are a several of ways to do what you want.

If you want to modify the starting list (rather than creating a new one), you could use a del statement to remove the desired index:

```<code>del oldlist[index]
</code>```

If you need a reference to the value you're removing (and don't have it already), you can call pop on the list instead:

```<code>value_removed = oldlist.pop(index)
</code>```

If you want to keep the old list as it was though, you need to copy the list's data in order to be able to remove the value without changing the original list. One way to do that is simply to copy the entire list, then use del on the index in the copy:

```<code>newlist = oldlist.copy() # or list(oldlist) or oldlist[:]
del newlist[index]
</code>```

Another option is to use slicing to get the part of the list before the index, and the part after the index, then concatenate them together. That would look like this:

```<code>newlist = oldlist[:index]
newlist.extend(oldlist[index + 1:])
</code>```

You could do this latter version in one line using the + operator to merge the two slices, but using two lines and calling extend avoids an unnecessary extra copy of the first slice of values.

Note that unless index is always close to the end of the list, all of these approaches are going to take O(len(oldlist)) time to complete, so don't do this a frequently on a very long list if you care about performance.

In all of my examples I've used oldlist as the existing list's name. I strongly encourage you to avoid using list as a variable name in your code, since it will mask the builtin list type. That's usually not going to be a problem immediately (especially if the list variable is a local variable in a function), but it might cause very confusing bugs if you later edit the code and don't remember that list is a local variable in that specific place.

Title: Python - Remove one letter in a string

Body:
I want to delete a variable (which is a string) from a list of strings. So basically:

list = ["A", "G", "T", "C"]
number = 2
newlist = ["A", "G", "T", "C"] - list[number]

This should then give:

newlist = ["A", "G", "C"]

But when I try this it gives me this error message:

Traceback (most recent call last):
  File "mini.py", line 3, in <module>
    newlist = ["A", "G", "T", "C"] - list[number]
TypeError: unsupported operand type(s) for -: 'list' and 'str'

How do I fix this?

Thanks in advance!

Body:
There are a several of ways to do what you want.

If you want to modify the starting list (rather than creating a new one), you could use a del statement to remove the desired index:

del oldlist[index]

If you need a reference to the value you're removing (and don't have it already), you can call pop on the list instead:

value_removed = oldlist.pop(index)

If you want to keep the old list as it was though, you need to copy the list's data in order to be able to remove the value without changing the original list. One way to do that is simply to copy the entire list, then use del on the index in the copy:

newlist = oldlist.copy() # or list(oldlist) or oldlist[:]
del newlist[index]

Another option is to use slicing to get the part of the list before the index, and the part after the index, then concatenate them together. That would look like this:

newlist = oldlist[:index]
newlist.extend(oldlist[index + 1:])

You could do this latter version in one line using the + operator to merge the two slices, but using two lines and calling extend avoids an unnecessary extra copy of the first slice of values.

Note that unless index is always close to the end of the list, all of these approaches are going to take O(len(oldlist)) time to complete, so don't do this a frequently on a very long list if you care about performance.

In all of my examples I've used oldlist as the existing list's name. I strongly encourage you to avoid using list as a variable name in your code, since it will mask the builtin list type. That's usually not going to be a problem immediately (especially if the list variable is a local variable in a function), but it might cause very confusing bugs if you later edit the code and don't remember that list is a local variable in that specific place.


问:
Notepad++ extented search
I search lines with (.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*) formula. (9 characters)
But search with 10 characters or more not work :(

Any know why can't search?

答:
I entered the line 1;2;3;4;5;6;7;8;9;0;q;w;e;r;t;y;u;i;o;p in Notepad++ and tried the following searches:

(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*) (9 groups): matches.

(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*);.* (10 groups without parentheses around the last): matches.

(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*);(.*) (10 groups): doesn't match.  Notepad++ tells me it can't find the text, although the text is quite clearly there.

I'd guess that this is because Notepad++ doesn't support any more than 9 backreferences (\1 to \9 in the replacement string), and so it doesn't let you have any more than 9 parenthesised groups.  (I am struggling to find any documentation to back up my claim, however.)

If you don't need the values matched (e.g. you're not replacing text), then you can always drop the parentheses, as in the second example above.

I can only guess at a possible reason why 10 or more backreferences are not allowed: what should \10 represent?  Should it be the 10th backreference, or the 1st backreference followed by 0?

Title: Notepad++ extented search


问:
How to decide number of nodes for CNN model for image classification using tensorflow ? Images are of size 178,218
How to select the following: Size of filter for convolution, strides, pooling, and densely connected layer</p>

答:
There is no single answer to this question. This Reddit and this answer have some nice discussion. To quote the second post on the Reddit, "Start simple."

Celeba has similar, maybe exactly the same, image size. When I was working with Celeba on a DCGAN project, I gently cropped and then reshaped the images to 64 x 64 x 3. My discriminator was a convolutional neural network and used 4 convolutional layers and one fully connected layer. All conv layers had 5 x 5 window size and stride size of 2 x 2. SAME padding and no pooling. The output channels per layer were 128 -> 256 -> 512 -> 1024. So, the last conv layer output a 4 x 4 x 1024 tensor. My dense layer then had a weight size of classes x 1024. (I had 1 class since its purpose was to determine whether the input image was from the dataset or made by the generator.)

That relatively simple architecture had good results, but it was intentionally built to not overpower the generator. If you're looking for pure classification, you may want a deeper architecture. You might not want to crop as aggressively as I did. Then you can include more conv layers before the fully connected layer. You may want to use a 3 x 3 window size with a stride size of 1 x 1 and use pooling - although I see  architectures abandoning pooling in favor of larger stride size. If your dataset is small, it is prone to overfitting. Having smaller weights helps combat this when dropout isn't enough. That means fewer output channels per layer.

There are a lot of possibilities when choosing an architecture, and there is no hard-and-fast rule for the best architecture. Remember to start simple.


问:
Error message when use addLayer in Leaflet
I use this code to make a join of 2 files of 2 files want to generate json files:

```<code>function join(){
    $.when(
        $.getJSON('bairro.json'),
        $.getJSON('convertJson.php')
    ).done(function(responseGeojson, responseData) {
        var data = responseData[0]
        var geojsonLayer = responseGeojson[0]

        console.log('==geojson==');
        console.log(geojsonLayer);

        var lookup = {};
        data.forEach(function(item) {
            if(item.cod) {
                lookup[item.cod] = {
                    id: item.cod,
                    nome: item.nome,
                    local: item.local
                }
            }
        })
        console.log('==lookup==');
        console.log(lookup);

        geojsonLayer.features.forEach(function(d) {
            if (lookup[d.properties.CODBAIRRO]) {
                d.properties.joined = lookup[d.properties.CODBAIRRO];
            }
        })

        console.log('==the new==');
        console.log(geojsonLayer);

        L.geoJSON(geojsonLayer).addTo(map);

    })
}
</code>```

But this error message appears:

TypeError: t.addLayer is not a function

According to the error presented, the problem is in this line of code:

L.geoJSON(geojsonLayer).addTo(map);

I do not know what to do to fix this error, for the code to work.

UPDATE

The Jsons behaving well and are valid, I checked on a validator.

Part of  the output of console.log(geojsonLayer); is:

```<code>{type: "FeatureCollection", features: Array(161)}
  features:Array(161)
    [0 … 99]

      0:
       geometry:
         coordinates:(50)
            [Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1)]
        type:"MultiPolygon"
        __proto__:Object
      properties:{OBJECTID: 325, Área: 1705684.49376977, NOME: "Paquetá", REGIAO_ADM: "PAQUETA", AREA_PLANE: "1", …}
      type:"Feature"
      __proto__:Object

      1:{type: "Feature", properties: {…}, geometry: {…}}
      2:{type: "Feature", properties: {…}, geometry: {…}}
      3:{type: "Feature", properties: {…}, geometry: {…}}
</code>```

答:
That error appears in this case if your layer is not correctly interpreted as JSON, in example because of bad file structure or your geojsonLayer variable is empty so that addTo(map) function cannot process it.

You may add some error handling to your $.getJSON functions:

```<code>$.getJSON("YOUR-FILE.JSON", function() {
  console.log("success");
})
.success(function() { console.log("success"); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete"); })
.fail(function(jqXHR, status, error){
   if(status == 'parseerror'){
    console.log("not valid json");
   } else {
    console.log("some other error?");
   }
});
</code>```

How are your JSONs behaving on this handlers?

Your code combine two files from different sources so probably the output file structure is not correct as JSON or one of your files has wrong structure to be interpreted as JSON/geoJSON. Can you post your output to some JSON validator? Is it valid?

Can you please upload output of your console.log(geojsonLayer);?

You may check adding these files separately with this script - do they separetely add properly to your map?

I would also strongly suggest you to process your files on server in PHP script which will output with one single properly structured JSON file.

Body:
I use this code to make a join of 2 files of 2 files want to generate json files:

function join(){
    $.when(
        $.getJSON('bairro.json'),
        $.getJSON('convertJson.php')
    ).done(function(responseGeojson, responseData) {
        var data = responseData[0]
        var geojsonLayer = responseGeojson[0]

        console.log('==geojson==');
        console.log(geojsonLayer);

        var lookup = {};
        data.forEach(function(item) {
            if(item.cod) {
                lookup[item.cod] = {
                    id: item.cod,
                    nome: item.nome,
                    local: item.local
                }
            }
        })
        console.log('==lookup==');
        console.log(lookup);

        geojsonLayer.features.forEach(function(d) {
            if (lookup[d.properties.CODBAIRRO]) {
                d.properties.joined = lookup[d.properties.CODBAIRRO];
            }
        })

        console.log('==the new==');
        console.log(geojsonLayer);

        L.geoJSON(geojsonLayer).addTo(map);

    })
}

But this error message appears:

TypeError: t.addLayer is not a function

According to the error presented, the problem is in this line of code:

L.geoJSON(geojsonLayer).addTo(map);

I do not know what to do to fix this error, for the code to work.

UPDATE

The Jsons behaving well and are valid, I checked on a validator.

Part of  the output of console.log(geojsonLayer); is:

{type: "FeatureCollection", features: Array(161)}
  features:Array(161)
    [0 … 99]

      0:
       geometry:
         coordinates:(50)
            [Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1), Array(1)]
        type:"MultiPolygon"
        __proto__:Object
      properties:{OBJECTID: 325, Área: 1705684.49376977, NOME: "Paquetá", REGIAO_ADM: "PAQUETA", AREA_PLANE: "1", …}
      type:"Feature"
      __proto__:Object

      1:{type: "Feature", properties: {…}, geometry: {…}}
      2:{type: "Feature", properties: {…}, geometry: {…}}
      3:{type: "Feature", properties: {…}, geometry: {…}}

Body:
That error appears in this case if your layer is not correctly interpreted as JSON, in example because of bad file structure or your geojsonLayer variable is empty so that addTo(map) function cannot process it.

You may add some error handling to your $.getJSON functions:

$.getJSON("YOUR-FILE.JSON", function() {
  console.log("success");
})
.success(function() { console.log("success"); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete"); })
.fail(function(jqXHR, status, error){
   if(status == 'parseerror'){
    console.log("not valid json");
   } else {
    console.log("some other error?");
   }
});

How are your JSONs behaving on this handlers?

Your code combine two files from different sources so probably the output file structure is not correct as JSON or one of your files has wrong structure to be interpreted as JSON/geoJSON. Can you post your output to some JSON validator? Is it valid?

Can you please upload output of your console.log(geojsonLayer);?

You may check adding these files separately with this script - do they separetely add properly to your map?

I would also strongly suggest you to process your files on server in PHP script which will output with one single properly structured JSON file.


问:
Replace NA in Column A, comparing column A and a list
I have a data.frame DF which contains two columns. Names and Score.
I than have a list (the.list) containing names. Some are equal to the names in names in DF$names.
I need to insert a number (2000) into DF$score, if the name is in the.list and the score is NA

The data:

```<code>DF.scores <- data.frame(c("steve", "anna", "albert", "john", "sarah", "lily"), c(2000, 1500, NA, NA, NA, 1750))
names(DF.scores) <- c("names", "score")
the.list <- c("anna", "steve", "john")
</code>```

I need the data frame to end up like this:

```<code>names   score
steve   2000
anna    1500
albert  NA
john    2000
sarah   NA
lily    1750
</code>```

I have tried subsetting the data, use which command but getting no results.

答:
I know it's simple, but where you have scores already in your dataframe that you might not want to change, it's hard to beat a simple ifelse statement:</p>

```<code>DF.scores$score <- with(DF.scores,ifelse(names %in% the.list & is.na(score),yes=2000,no=score))
</code>```

Body:
I have a data.frame DF which contains two columns. Names and Score.
I than have a list (the.list) containing names. Some are equal to the names in names in DF$names.
I need to insert a number (2000) into DF$score, if the name is in the.list and the score is NA

The data:

DF.scores <- data.frame(c("steve", "anna", "albert", "john", "sarah", "lily"), c(2000, 1500, NA, NA, NA, 1750))
names(DF.scores) <- c("names", "score")
the.list <- c("anna", "steve", "john")

I need the data frame to end up like this:

names   score
steve   2000
anna    1500
albert  NA
john    2000
sarah   NA
lily    1750

I have tried subsetting the data, use which command but getting no results.

Body:
I know it's simple, but where you have scores already in your dataframe that you might not want to change, it's hard to beat a simple ifelse statement:

DF.scores$score <- with(DF.scores,ifelse(names %in% the.list & is.na(score),yes=2000,no=score))


问:
Python convert image array(20,20) to array(400)
Using Python 2.7 and Numpy.

I have a B/W image stored in array(20,20) and I would like to convert it to an array(400). How can this be done in Python if I have many images, that is array(x,20,20)?

Thanks a lot!

EDIT: Thanks a lot. I got the problem wrong at the beginning, thus I was not able to figure out this simple piece of code.

答:
I think numpy.flatten() is what you are looking for

```<code>>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])
</code>```

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.flatten.html

Body:
I think numpy.flatten() is what you are looking for

>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.flatten.html


问:
Is there a non-pdb way to enter Python interpreter at a given line?
Is there a way to cause a python script to enter the interpreter at a given line? I know I can use import pdb; pdb.set_trace() to begin debugging at a certain line, but that means all the pdb commands may get in the way.

Is there a way to kick into the regular interpreter (or ipython) outside of pdb?

答:
The easiest way is code.interact:

```<code>import code
code.interact(local={**globals(), **locals()})
</code>```

Body:
The easiest way is code.interact:

import code
code.interact(local={**globals(), **locals()})


问:
How do I get the following code to work on a Safari browser?
This code works on Chrome but does not work on Safari. The circle markers on the map are supposed to open up.

html {
  background: #eaeaea;
  color: #e5e5e5;
  text-align: center;
  font-family: "Open Sans", Helvetica, sans-serif;
}

body {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 100px;
  overflow-x: hidden;
}

.description {
  max-width: 600px;
  margin: 0 auto;
  color: rgba(229, 229, 229, 0.7);
}

div, img, footer {
  position: relative;
  box-sizing: border-box;
}

h1, h2, h3, h4, h5, h6 {
  margin-bottom: 20px;
  font-family: "Raleway", Helvetica, sans-serif;
  font-weight: 300;
}

h1 {
  font-size: 36pt;
}

h2 {
  font-size: 24pt;
}

h3 {
  font-size: 18pt;
}

h4 {
  font-size: 16pt;
}

h5 {
  font-size: 14pt;
}

h6 {
  font-size: 12pt;
}

p {
  font-size: 12pt;
  margin-bottom: 12pt;
}

strong {
  font-weight: 900;
  font-family: "Raleway", Helvetica, sans-serif;
  color: #e5e5e5;
}

a {
  -webkit-transition: color 0.25s ease-in-out;
  transition: color 0.25s ease-in-out;
  font-family: "Raleway", Helvetica, sans-serif;
  text-transform: uppercase;
  text-decoration: none;
  color: #dff3fd;
}
a:visited {
  color: #dff3fd;
}
li.active a, a:hover, a:active {
  color: #e5e5e5;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.centered-y {
  position: absolute;
  width: 100%;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}

.distribution-map {
  position: relative;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  margin: 0 auto;
}
.distribution-map > img {
  width: 100%;
  position: relative;
  margin: 0;
  padding: 0;
}
.distribution-map .map-point {
  cursor: pointer;
  outline: none;
  z-index: 0;
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 20px;
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
  opacity: 0.8;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  -moz-transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  -o-transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  -webkit-transition: opacity 0.25s ease-in-out, width 0.25s ease-in-out, height 0.25s ease-in-out, z-index 0.25s ease-in-out;
  -webkit-transition-delay: 0.25s, 0.25s, 0.25s, 0.25s;
  -webkit-transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  background: #e69c53;
  border: 4px solid #fff;
}
.distribution-map .map-point .content {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0;
  -webkit-transition: opacity 0.25s ease-in-out;
  transition: opacity 0.25s ease-in-out;
  width: 100%;
  height: 100%;
  left: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: overlay;
}
.distribution-map .map-point:active, .distribution-map .map-point:focus {
  margin: 0;
  padding: 0;
  filter: progid:DXImageTransform.Microsoft.Alpha(enabled=false);
  opacity: 1;
  width: 300px;
  height: 220px;
  color: #e5e5e5;
  z-index: 1;
  -webkit-transition: opacity 0.25s ease-in-out, width 0.25s ease-in-out, height 0.25s ease-in-out;
  transition: opacity 0.25s ease-in-out, width 0.25s ease-in-out, height 0.25s ease-in-out;
}
.distribution-map .map-point:active .content, .distribution-map .map-point:focus .content {
  filter: progid:DXImageTransform.Microsoft.Alpha(enabled=false);
  opacity: 1;
  -moz-transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  -o-transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  -webkit-transition: opacity 0.25s ease-in-out, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  -webkit-transition-delay: 0.25s, 0s, 0s;
  -webkit-transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  overflow: hidden;
}
.distribution-map .map-point:active .content a:hover, .distribution-map .map-point:active .content a:active, .distribution-map .map-point:focus .content a:hover, .distribution-map .map-point:focus .content a:active {
  color: #afe1fa;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

 <link href='//fonts.googleapis.com/css?family=Raleway:300,400,700' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Open+Sans:100,300,400,700,900' rel='stylesheet' type='text/css'>
<h1>Qualität die weltweit hörbar ist</h1>
<p class="description">This doesn’t look great at small sizes — in the original, I have an alternate rule for displaying on mobile devices. <strong>Click the points to expand them.</strong></p>
<div class="distribution-map">
    <!-- This was broken for a while because imgur :( -->
    <!-- I don't trust this host. Image here if it goes down: https://i.imgur.com/M7aUkuS.png -->
    <img src="https://s24.postimg.org/jnd9wc0n9/M7a_Uku_S.png">
    <!--In the original application, these points are injected with Javascript, but ideally, they'd be injected with a haml loop. Because I'm hardcoding content, I'm presenting this as prerendered HTML-->
    <button class="map-point" style="top:15%;left:35%">
        <div class="content">
            <div class="centered-y">
                <h2>Nordamerika</h2>
                <p>You can put plenty of details in here. In the original, I listed contact information and linked phone numbers and email addresses.</p>
            </div>
        </div>
    </button>
    <button class="map-point" style="top:35%;left:50%">
        <div class="content">
            <div class="centered-y">
                <h2>Another Place</h2>
                <p>Lorem ipsum something something</p>
            </div>
        </div>
    </button>
    <button class="map-point" style="top:76%;left:82.5%">
        <div class="content">
            <div class="centered-y">
                <h2>Marauder Town</h2>
                <p>I solemnly swear that I am up to no good</p>
            </div>
        </div>
    </button>
    <button class="map-point" style="top:45%;left:16%">
        <div class="content">
            <div class="centered-y">
                <h2>Nordamerika</h2>
                <p>Englisch, Spanisch</p>
            </div>
        </div>
    </button>
    <button class="map-point" style="top:60%;left:53%">
        <div class="content">
            <div class="centered-y">
                <h2>Toto</h2>
                <p>I bless the rains</p>
            </div>
        </div>
    </button>
    <button class="map-point" style="top:45%;left:75%">
        <div class="content">
            <div class="centered-y">
                <h2>Asiatisch</h2>
                <p>Chinesische Sprecher</p>
            </div>
        </div>
    </button>
</div>
<p class="description">It’s been brought to my attention that OSX/Safari doesn’t support :active for buttons with default settings, so you guys will have to resort to JS or hold down your mouse button to keep :focus triggered.</p></code>```

I was wondering how to fix the codes so that they will work properly? I'm not sure if it needs javascript to work or not. Here is the original code I got this from if it helps:
https://codepen.io/tosa/pen/XjEOzJ?q=interactive+map&limit=all&type=type-pens

答:
Replace the .map-point elements from button to a and add a tabindex attribute to each one.

Demo at https://codepen.io/gpetrioli/full/dZrgoM/

Body:
This code works on Chrome but does not work on Safari. The circle markers on the map are supposed to open up.

html {
  background: #eaeaea;
  color: #e5e5e5;
  text-align: center;
  font-family: "Open Sans", Helvetica, sans-serif;
}

body {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 100px;
  overflow-x: hidden;
}

.description {
  max-width: 600px;
  margin: 0 auto;
  color: rgba(229, 229, 229, 0.7);
}

div, img, footer {
  position: relative;
  box-sizing: border-box;
}

h1, h2, h3, h4, h5, h6 {
  margin-bottom: 20px;
  font-family: "Raleway", Helvetica, sans-serif;
  font-weight: 300;
}

h1 {
  font-size: 36pt;
}

h2 {
  font-size: 24pt;
}

h3 {
  font-size: 18pt;
}

h4 {
  font-size: 16pt;
}

h5 {
  font-size: 14pt;
}

h6 {
  font-size: 12pt;
}

p {
  font-size: 12pt;
  margin-bottom: 12pt;
}

strong {
  font-weight: 900;
  font-family: "Raleway", Helvetica, sans-serif;
  color: #e5e5e5;
}

a {
  -webkit-transition: color 0.25s ease-in-out;
  transition: color 0.25s ease-in-out;
  font-family: "Raleway", Helvetica, sans-serif;
  text-transform: uppercase;
  text-decoration: none;
  color: #dff3fd;
}
a:visited {
  color: #dff3fd;
}
li.active a, a:hover, a:active {
  color: #e5e5e5;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.centered-y {
  position: absolute;
  width: 100%;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}

.distribution-map {
  position: relative;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  margin: 0 auto;
}
.distribution-map > img {
  width: 100%;
  position: relative;
  margin: 0;
  padding: 0;
}
.distribution-map .map-point {
  cursor: pointer;
  outline: none;
  z-index: 0;
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 20px;
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
  opacity: 0.8;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  -moz-transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  -o-transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  -webkit-transition: opacity 0.25s ease-in-out, width 0.25s ease-in-out, height 0.25s ease-in-out, z-index 0.25s ease-in-out;
  -webkit-transition-delay: 0.25s, 0.25s, 0.25s, 0.25s;
  -webkit-transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  transition: opacity 0.25s ease-in-out 0.25s, width 0.25s ease-in-out 0.25s, height 0.25s ease-in-out 0.25s, z-index 0.25s ease-in-out 0.25s;
  background: #e69c53;
  border: 4px solid #fff;
}
.distribution-map .map-point .content {
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0;
  -webkit-transition: opacity 0.25s ease-in-out;
  transition: opacity 0.25s ease-in-out;
  width: 100%;
  height: 100%;
  left: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: overlay;
}
.distribution-map .map-point:active, .distribution-map .map-point:focus {
  margin: 0;
  padding: 0;
  filter: progid:DXImageTransform.Microsoft.Alpha(enabled=false);
  opacity: 1;
  width: 300px;
  height: 220px;
  color: #e5e5e5;
  z-index: 1;
  -webkit-transition: opacity 0.25s ease-in-out, width 0.25s ease-in-out, height 0.25s ease-in-out;
  transition: opacity 0.25s ease-in-out, width 0.25s ease-in-out, height 0.25s ease-in-out;
}
.distribution-map .map-point:active .content, .distribution-map .map-point:focus .content {
  filter: progid:DXImageTransform.Microsoft.Alpha(enabled=false);
  opacity: 1;
  -moz-transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  -o-transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  -webkit-transition: opacity 0.25s ease-in-out, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  -webkit-transition-delay: 0.25s, 0s, 0s;
  -webkit-transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  transition: opacity 0.25s ease-in-out 0.25s, height 0.25s ease-in-out, overflow 0.25s ease-in-out;
  overflow: hidden;
}
.distribution-map .map-point:active .content a:hover, .distribution-map .map-point:active .content a:active, .distribution-map .map-point:focus .content a:hover, .distribution-map .map-point:focus .content a:active {
  color: #afe1fa;
}

 <link href='//fonts.googleapis.com/css?family=Raleway:300,400,700' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Open+Sans:100,300,400,700,900' rel='stylesheet' type='text/css'>

Qualität die weltweit hörbar ist

This doesn’t look great at small sizes — in the original, I have an alternate rule for displaying on mobile devices. Click the points to expand them.

    <button class="map-point" style="top:15%;left:35%">

Nordamerika

You can put plenty of details in here. In the original, I listed contact information and linked phone numbers and email addresses.

    </button>
    <button class="map-point" style="top:35%;left:50%">

Another Place

Lorem ipsum something something

    </button>
    <button class="map-point" style="top:76%;left:82.5%">

Marauder Town

I solemnly swear that I am up to no good

    </button>
    <button class="map-point" style="top:45%;left:16%">

Nordamerika

Englisch, Spanisch

    </button>
    <button class="map-point" style="top:60%;left:53%">

Toto

I bless the rains

    </button>
    <button class="map-point" style="top:45%;left:75%">

Asiatisch

Chinesische Sprecher

    </button>

It’s been brought to my attention that OSX/Safari doesn’t support :active for buttons with default settings, so you guys will have to resort to JS or hold down your mouse button to keep :focus triggered.

I was wondering how to fix the codes so that they will work properly? I'm not sure if it needs javascript to work or not. Here is the original code I got this from if it helps:
https://codepen.io/tosa/pen/XjEOzJ?q=interactive+map&limit=all&type=type-pens