问:
How to sort map or which traversal approach i need to follow?
i just want to get a Sorted map my code is like :

```<code>public class SubString {public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("string2");
list.add("STR_str2");
list.add("STR_str3");
getSequesce("STR_str1", list);
List<String> list1 = new ArrayList<>();
list1.add("STR_xyz");
list1.add("STR_ABC");
getSequesce("STR_str2", list1);
List<String> list3 = new ArrayList<>();
list3.add("Anukul");
list3.add("mittal");
getSequesce("STR_str3", list3);
List<String> list4 = new ArrayList<>();
list4.add("Test");
list4.add("STR_XYZ");
getSequesce("STR_ABC", list4);
List<String> list5 = new ArrayList<>();
list5.add("val");
list5.add("var");
getSequesce("STR_XYZ", list5);
List<String> list6 = new ArrayList<>();
list6.add("val6");
list6.add("valtest");
getSequesce("STR_free", list6);
List<String> list7 = new ArrayList<>();
list7.add("val6");
list7.add("STR_free");
getSequesce("STR_7", list7);

}private static void getSequesce(String string, List<String> list) {
Map<String, List<String>> map = new HashMap<>();
Map<String, List<String>> sortedMap = new TreeMap<>();
map.put(string, list);

for (Map.Entry<String, List<String> > itrMap : map.entrySet() ) {

}
}}
</code>```

In my fist call of getSequence method i have put a string "STR_str1" and a list.
i just want to add this into a map where key is STR_str1 and its value is list.
but my problem is  i have to  put STR_str2 ,and STR_str3 as key in map before STR_str1. similarly i have to put STR_ABC and STR_XYZ before STR_str2.
i just want a sortedMap from function getSequesce so that i get output like

STR_free,list6

"STR_7", list7

STR_XYZ,list5

STR_ABC,list4

STR_str3,list3

"STR_str2", list1

"STR_str1", list

if value of list start with STR_ then this STR_ must already avail in map.

position of "STR_free", list6  "STR_XYZ", list5   "STR_str3", list3   can be anywhere because they don't contain any dependency.

please help me to suggest what approach i can follow. i have data that will not create cyclic problem.
Thanks.

答:
Thank you for help guys code i was looking for is </p>

```<code>private static Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
private static List<String> nonDependentList = new ArrayList<String>();
private static Map<String, List<String>> dependentMap = new ConcurrentHashMap<String, List<String>>();

public static void main(String[] args) {

    List<String> list1 = new ArrayList<>();
    list1.add("string2");
    list1.add("STR_str2");
    list1.add("STR_str3");
    addRecord("STR_str1", list1);
    List<String> list2 = new ArrayList<>();
    list2.add("STR_xyz");
    list2.add("STR_ABC");
    addRecord("STR_str2", list2);
    List<String> list3 = new ArrayList<>();
    list3.add("Anukul");
    list3.add("mittal");
    addRecord("STR_str3", list3);
    List<String> list4 = new ArrayList<>();
    list4.add("Test");
    list4.add("STR_XYZ");
    addRecord("STR_ABC", list4);
    List<String> list5 = new ArrayList<>();
    list5.add("val");
    list5.add("var");
    addRecord("STR_XYZ", list5);
    List<String> list6 = new ArrayList<>();
    list6.add("val6");
    list6.add("valtest");
    addRecord("STR_free", list6);
    List<String> list7 = new ArrayList<>();
    list7.add("val6");
    list7.add("STR_free");
    addRecord("STR_7", list7);

    Map<String, List<String>> processedMap = proceedAndFetchRecords();
    System.out.println("Final result");
    for (Entry<String, List<String>> entry : processedMap.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " || Values : " + entry.getValue());
    }
}

private static Map<String, List<String>> proceedAndFetchRecords() {
    for (Entry<String, List<String>> entry : map.entrySet()) {
        boolean flag = isNotDependent(entry.getValue());
        // System.out.println("Key : " + entry.getKey() + " isNotDependent :
        // " + flag);
        if (flag) {
            nonDependentList.add(entry.getKey());
        } else {
            List<String> list = getOnlyDependentList(entry.getValue());
            dependentMap.put(entry.getKey(), list);
        }
    }
    // showDependentMap();
    refreshDependentMap();

    // Final result
    Map<String, List<String>> processedMap = addResultsInMap();
    return processedMap;
}

private static void refreshDependentMap() {
    for (Entry<String, List<String>> entry : dependentMap.entrySet()) {
        List<String> list = entry.getValue();
        list.removeAll(nonDependentList);

        boolean flag = isNotDependent(list);

        if (flag) {
            nonDependentList.add(entry.getKey());
            dependentMap.remove(entry.getKey());
            refreshDependentMap();
        } else {
            continue;
        }
    }

}

private static Map<String, List<String>> addResultsInMap() {
    Map<String, List<String>> processedMap = new LinkedHashMap<String, List<String>>();

    for (String key : nonDependentList) {
        processedMap.put(key, map.get(key));
    }

    for (Entry<String, List<String>> entry : dependentMap.entrySet()) {
        processedMap.put(entry.getKey(), map.get(entry.getKey()));
    }
    return processedMap;
}

private static boolean isNotDependent(List<String> list) {
    int count = 0;
    for (String string : list) {
        if (!string.startsWith("STR_")) {
            ++count;
        }
    }
    if (list.size() == count) {
        return true;
    }
    return false;
}

private static void addRecord(String structureName, List<String> list) {
    map.put(structureName, list);
}

private static List<String> getOnlyDependentList(List<String> list) {
    List<String> list1 = new ArrayList<>();
    for (String string : list) {
        if (string.startsWith("STR_")) {
            list1.add(string);
        }
    }
    return list1;
}}
</code>```

Body:
i just want to get a Sorted map my code is like :

public class SubString {public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("string2");
list.add("STR_str2");
list.add("STR_str3");
getSequesce("STR_str1", list);
List<String> list1 = new ArrayList<>();
list1.add("STR_xyz");
list1.add("STR_ABC");
getSequesce("STR_str2", list1);
List<String> list3 = new ArrayList<>();
list3.add("Anukul");
list3.add("mittal");
getSequesce("STR_str3", list3);
List<String> list4 = new ArrayList<>();
list4.add("Test");
list4.add("STR_XYZ");
getSequesce("STR_ABC", list4);
List<String> list5 = new ArrayList<>();
list5.add("val");
list5.add("var");
getSequesce("STR_XYZ", list5);
List<String> list6 = new ArrayList<>();
list6.add("val6");
list6.add("valtest");
getSequesce("STR_free", list6);
List<String> list7 = new ArrayList<>();
list7.add("val6");
list7.add("STR_free");
getSequesce("STR_7", list7);

}private static void getSequesce(String string, List<String> list) {
Map<String, List<String>> map = new HashMap<>();
Map<String, List<String>> sortedMap = new TreeMap<>();
map.put(string, list);

for (Map.Entry<String, List<String> > itrMap : map.entrySet() ) {

}
}}

In my fist call of getSequence method i have put a string "STR_str1" and a list.
i just want to add this into a map where key is STR_str1 and its value is list.
but my problem is  i have to  put STR_str2 ,and STR_str3 as key in map before STR_str1. similarly i have to put STR_ABC and STR_XYZ before STR_str2.
i just want a sortedMap from function getSequesce so that i get output like

STR_free,list6

"STR_7", list7

STR_XYZ,list5

STR_ABC,list4

STR_str3,list3

"STR_str2", list1

"STR_str1", list

if value of list start with STR_ then this STR_ must already avail in map.

position of "STR_free", list6  "STR_XYZ", list5   "STR_str3", list3   can be anywhere because they don't contain any dependency.

please help me to suggest what approach i can follow. i have data that will not create cyclic problem.
Thanks.

Body:
Thank you for help guys code i was looking for is

private static Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
private static List<String> nonDependentList = new ArrayList<String>();
private static Map<String, List<String>> dependentMap = new ConcurrentHashMap<String, List<String>>();

public static void main(String[] args) {

    List<String> list1 = new ArrayList<>();
    list1.add("string2");
    list1.add("STR_str2");
    list1.add("STR_str3");
    addRecord("STR_str1", list1);
    List<String> list2 = new ArrayList<>();
    list2.add("STR_xyz");
    list2.add("STR_ABC");
    addRecord("STR_str2", list2);
    List<String> list3 = new ArrayList<>();
    list3.add("Anukul");
    list3.add("mittal");
    addRecord("STR_str3", list3);
    List<String> list4 = new ArrayList<>();
    list4.add("Test");
    list4.add("STR_XYZ");
    addRecord("STR_ABC", list4);
    List<String> list5 = new ArrayList<>();
    list5.add("val");
    list5.add("var");
    addRecord("STR_XYZ", list5);
    List<String> list6 = new ArrayList<>();
    list6.add("val6");
    list6.add("valtest");
    addRecord("STR_free", list6);
    List<String> list7 = new ArrayList<>();
    list7.add("val6");
    list7.add("STR_free");
    addRecord("STR_7", list7);

    Map<String, List<String>> processedMap = proceedAndFetchRecords();
    System.out.println("Final result");
    for (Entry<String, List<String>> entry : processedMap.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " || Values : " + entry.getValue());
    }
}

private static Map<String, List<String>> proceedAndFetchRecords() {
    for (Entry<String, List<String>> entry : map.entrySet()) {
        boolean flag = isNotDependent(entry.getValue());
        // System.out.println("Key : " + entry.getKey() + " isNotDependent :
        // " + flag);
        if (flag) {
            nonDependentList.add(entry.getKey());
        } else {
            List<String> list = getOnlyDependentList(entry.getValue());
            dependentMap.put(entry.getKey(), list);
        }
    }
    // showDependentMap();
    refreshDependentMap();

    // Final result
    Map<String, List<String>> processedMap = addResultsInMap();
    return processedMap;
}

private static void refreshDependentMap() {
    for (Entry<String, List<String>> entry : dependentMap.entrySet()) {
        List<String> list = entry.getValue();
        list.removeAll(nonDependentList);

        boolean flag = isNotDependent(list);

        if (flag) {
            nonDependentList.add(entry.getKey());
            dependentMap.remove(entry.getKey());
            refreshDependentMap();
        } else {
            continue;
        }
    }

}

private static Map<String, List<String>> addResultsInMap() {
    Map<String, List<String>> processedMap = new LinkedHashMap<String, List<String>>();

    for (String key : nonDependentList) {
        processedMap.put(key, map.get(key));
    }

    for (Entry<String, List<String>> entry : dependentMap.entrySet()) {
        processedMap.put(entry.getKey(), map.get(entry.getKey()));
    }
    return processedMap;
}

private static boolean isNotDependent(List<String> list) {
    int count = 0;
    for (String string : list) {
        if (!string.startsWith("STR_")) {
            ++count;
        }
    }
    if (list.size() == count) {
        return true;
    }
    return false;
}

private static void addRecord(String structureName, List<String> list) {
    map.put(structureName, list);
}

private static List<String> getOnlyDependentList(List<String> list) {
    List<String> list1 = new ArrayList<>();
    for (String string : list) {
        if (string.startsWith("STR_")) {
            list1.add(string);
        }
    }
    return list1;
}}


来源: stackexchange

问:
How to install pyperclip to Anaconda?
I want to install pyperclip from GitHub using pip install but unfortunately it's only installed to pip and not Anaconda. I'm using PyCharm and my interpreter is Anaconda. (Linux)

I want Anaconda to install the package 'pyperclip' as well so I can use it in PyCharm. I've try Googling but can't find any result.

答:
To install pyperclip from conda run following command.</p>

```<code>conda install -c bryanwweber pyperclip
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to install pyperclip to Anaconda?

Body:
To install pyperclip from conda run following command.

conda install -c bryanwweber pyperclip

ContentLicense: CC BY-SA 3.0


问:
How to get all in and out time of an particular employee?
Given Table:

```<code>    id       time_stamp                  Access Type
    1001    2017-09-05 09:35:00         IN
    1002    2017-09-05 11:00:00         IN
    1001    2017-09-05 12:00:00         OUT
    1002    2017-09-05 12:25:00          OUT
    1001    2017-09-05 13:00:00          IN
    1002    2017-09-05 14:00:00         IN
    1001    2017-09-05 17:00:00          OUT
    1002   2017-09-05 18:00:00         OUT
</code>```

I tried this query below:

```<code>    select  *,       datediff(minute, first_in, last_out) as durationfrom    (
        select  id
        ,       min(case when [Access Type] = 'IN' then time_stamp end) as first_in
        ,       max(case when [Access Type] = 'OUT' then time_stamp end) as last_out
        ,       cast(min(time_stamp) as date) as date
        from    Table1
        group by
                id
        ,       cast(time_stamp as date)
        ) as SubQueriesMustBeNamed
</code>```

when i try this query it shows only first in last out.

Desired Result:

```<code>    id      check_in    check_out  totalhrs  check_in check_out totalhrs  date
    1001     09:35       12:00      2:25       13:00    17:00     2:00    2013-09-05
    1002     11:00       12:25      1:25       14:00    18:00     4:00    2013-09-05
</code>```

The result will be above like this .  Anyone help me.. Thanks in advance

答:
SQL Fiddle

MS SQL Server 2014 Schema Setup:

```<code>CREATE TABLE Table1
    ([id] int, [time_stamp] datetime, [AccessType] varchar(3))
;

INSERT INTO Table1
    ([id], [time_stamp], [AccessType])
VALUES
    (1001, '2017-09-05 09:35:00', 'IN'),
    (1002, '2017-09-05 11:00:00', 'IN'),
    (1001, '2017-09-05 12:00:00', 'OUT'),
    (1002, '2017-09-05 12:25:00', 'OUT'),
    (1001, '2017-09-05 13:00:00', 'IN'),
    (1002, '2017-09-05 14:00:00', 'IN'),
    (1001, '2017-09-05 17:00:00', 'OUT'),
    (1002, '2017-09-05 18:00:00', 'OUT')
;
</code>```

Query 1:

```<code>select
       id, cast(time_stamp as date) [date]
     , format(max(case when in_rank = 1 then time_stamp end),'HH:mm')         check_in_1
     , format(max(case when in_rank = 1 then next_timestamp end),'HH:mm')     check_out_1
     , format(max(case when in_rank = 1 then
           dateadd(ss,datediff(ss,time_stamp,next_timestamp),0) end),'HH:mm') total_hrs_1
     , format(max(case when in_rank = 2 then time_stamp end),'HH:mm')         check_in_2
     , format(max(case when in_rank = 2 then next_timestamp end),'HH:mm')     check_out_2
     , format(max(case when in_rank = 2 then
           dateadd(ss,datediff(ss,time_stamp,next_timestamp),0) end),'HH:mm') total_hrs_2
from (
      select
            id, time_stamp, AccessType, next_timestamp, next_accesstype
          , dense_rank() over(partition by id, cast(time_stamp as date) order by time_stamp) in_rank
      from table1 t1
      outer apply (
          select top(1) t2.time_stamp, t2.AccessType
          from table1 t2
          where t1.id = t2.id and t1.AccessType <> t2.AccessType
          and cast(t1.time_stamp as date) = cast(t2.time_stamp as date)
          and t1.time_stamp < t2.time_stamp
          order by t2.time_stamp
          ) oa (next_timestamp, next_accesstype)
      where AccessType = 'IN'
     ) d
group by id, cast(time_stamp as date)
</code>```

Results:

```<code>|   id |       date | check_in_1 | check_out_1 | total_hrs_1 | check_in_2 | check_out_2 | total_hrs_2 |
|------|------------|------------|-------------|-------------|------------|-------------|-------------|
| 1001 | 2017-09-05 |      09:35 |       12:00 |       02:25 |      13:00 |       17:00 |       04:00 |
| 1002 | 2017-09-05 |      11:00 |       12:25 |       01:25 |      14:00 |       18:00 |       04:00 |
</code>```

Body:
Given Table:

    id       time_stamp                  Access Type
    1001    2017-09-05 09:35:00         IN
    1002    2017-09-05 11:00:00         IN
    1001    2017-09-05 12:00:00         OUT
    1002    2017-09-05 12:25:00          OUT
    1001    2017-09-05 13:00:00          IN
    1002    2017-09-05 14:00:00         IN
    1001    2017-09-05 17:00:00          OUT
    1002   2017-09-05 18:00:00         OUT

I tried this query below:

    select  *,       datediff(minute, first_in, last_out) as durationfrom    (
        select  id
        ,       min(case when [Access Type] = 'IN' then time_stamp end) as first_in
        ,       max(case when [Access Type] = 'OUT' then time_stamp end) as last_out
        ,       cast(min(time_stamp) as date) as date
        from    Table1
        group by
                id
        ,       cast(time_stamp as date)
        ) as SubQueriesMustBeNamed

when i try this query it shows only first in last out.

Desired Result:

    id      check_in    check_out  totalhrs  check_in check_out totalhrs  date
    1001     09:35       12:00      2:25       13:00    17:00     2:00    2013-09-05
    1002     11:00       12:25      1:25       14:00    18:00     4:00    2013-09-05

The result will be above like this .  Anyone help me.. Thanks in advance

Body:
SQL Fiddle

MS SQL Server 2014 Schema Setup:

CREATE TABLE Table1
    ([id] int, [time_stamp] datetime, [AccessType] varchar(3))
;

INSERT INTO Table1
    ([id], [time_stamp], [AccessType])
VALUES
    (1001, '2017-09-05 09:35:00', 'IN'),
    (1002, '2017-09-05 11:00:00', 'IN'),
    (1001, '2017-09-05 12:00:00', 'OUT'),
    (1002, '2017-09-05 12:25:00', 'OUT'),
    (1001, '2017-09-05 13:00:00', 'IN'),
    (1002, '2017-09-05 14:00:00', 'IN'),
    (1001, '2017-09-05 17:00:00', 'OUT'),
    (1002, '2017-09-05 18:00:00', 'OUT')
;

Query 1:

select
       id, cast(time_stamp as date) [date]
     , format(max(case when in_rank = 1 then time_stamp end),'HH:mm')         check_in_1
     , format(max(case when in_rank = 1 then next_timestamp end),'HH:mm')     check_out_1
     , format(max(case when in_rank = 1 then
           dateadd(ss,datediff(ss,time_stamp,next_timestamp),0) end),'HH:mm') total_hrs_1
     , format(max(case when in_rank = 2 then time_stamp end),'HH:mm')         check_in_2
     , format(max(case when in_rank = 2 then next_timestamp end),'HH:mm')     check_out_2
     , format(max(case when in_rank = 2 then
           dateadd(ss,datediff(ss,time_stamp,next_timestamp),0) end),'HH:mm') total_hrs_2
from (
      select
            id, time_stamp, AccessType, next_timestamp, next_accesstype
          , dense_rank() over(partition by id, cast(time_stamp as date) order by time_stamp) in_rank
      from table1 t1
      outer apply (
          select top(1) t2.time_stamp, t2.AccessType
          from table1 t2
          where t1.id = t2.id and t1.AccessType <> t2.AccessType
          and cast(t1.time_stamp as date) = cast(t2.time_stamp as date)
          and t1.time_stamp < t2.time_stamp
          order by t2.time_stamp
          ) oa (next_timestamp, next_accesstype)
      where AccessType = 'IN'
     ) d
group by id, cast(time_stamp as date)

Results:

|   id |       date | check_in_1 | check_out_1 | total_hrs_1 | check_in_2 | check_out_2 | total_hrs_2 |
|------|------------|------------|-------------|-------------|------------|-------------|-------------|
| 1001 | 2017-09-05 |      09:35 |       12:00 |       02:25 |      13:00 |       17:00 |       04:00 |
| 1002 | 2017-09-05 |      11:00 |       12:25 |       01:25 |      14:00 |       18:00 |       04:00 |


问:
Conditional Select - Part 2
I have the following situation within a PL/SLQ function. Depending of existing table field value I might run a different select. Specifically: I can have multiple rows for a particular BILL CODE (PINGPONG) where I would only need to get the SYS_FIELD value. This field has to be fetched only once according to following condition: If fields prep_seq_num=0 and primary_ind=0 then just get this row sys_field value straightaway and do not take care of other possible prep_seq_num and primary_ind values different from 0. If that rows is not existing, fetch the sys_field value from prep_seq_num!=0 and primary_ind=1. For both case only one instance/row must be possible So in the first case I should run:

```<code>SELECT SYS_FIELD
      INTO v_start_of_invoice
      FROM BILL
     WHERE TRACKING_ID = v_previous_trackingID
       AND BSCO_CODE_ID = 'PINGPONG'
       AND CHRG_ACCT_ID = v_ACCT_ID
       AND PREP_SEQ_NUM = 0 -- maybe not needed here
       AND ITEM_CAT_CODE_ID=1
       AND PARTITION_KEY = v_prev_partition
       AND SUBPARTITION_KEY = v_prev_subpartition
       AND PRIMARY_IND=0;
In the second case

SELECT SYS_FIELD
      INTO v_start_of_invoice
      FROM BILL
     WHERE TRACKING_ID = v_previous_trackingID
       AND BILL_CODE_ID = 'PINGPONG'
       AND ITEM_CAT_CODE_ID in ('5' , '-100')
       AND PARTITION_KEY = v_prev_partition
       AND SUBPARTITION_KEY = v_prev_subpartition
       AND PRIMARY_IND=1;
</code>```

Not sure I'm making it very complicated, but still I 'd need to know whether IF THEN ELSE or CASE or whatever should be used and how.

答:
You can utilize an implicit cursor for loop.</p>

```<code>for rec IN ( <your query that gives all records)
LOOP

--compare the value of this variable and decide in the IF condition.

    IF rec.prep_seq_num=0 and rec.primary_ind=0
      THEN
    -- write the query to get the sys_field

     ELSE
    -- write alternative query.

    END IF;

END LOOP;
</code>```

Title: Conditional Select - Part 2

Body:
I have the following situation within a PL/SLQ function. Depending of existing table field value I might run a different select. Specifically: I can have multiple rows for a particular BILL CODE (PINGPONG) where I would only need to get the SYS_FIELD value. This field has to be fetched only once according to following condition: If fields prep_seq_num=0 and primary_ind=0 then just get this row sys_field value straightaway and do not take care of other possible prep_seq_num and primary_ind values different from 0. If that rows is not existing, fetch the sys_field value from prep_seq_num!=0 and primary_ind=1. For both case only one instance/row must be possible So in the first case I should run:

SELECT SYS_FIELD
      INTO v_start_of_invoice
      FROM BILL
     WHERE TRACKING_ID = v_previous_trackingID
       AND BSCO_CODE_ID = 'PINGPONG'
       AND CHRG_ACCT_ID = v_ACCT_ID
       AND PREP_SEQ_NUM = 0 -- maybe not needed here
       AND ITEM_CAT_CODE_ID=1
       AND PARTITION_KEY = v_prev_partition
       AND SUBPARTITION_KEY = v_prev_subpartition
       AND PRIMARY_IND=0;
In the second case

SELECT SYS_FIELD
      INTO v_start_of_invoice
      FROM BILL
     WHERE TRACKING_ID = v_previous_trackingID
       AND BILL_CODE_ID = 'PINGPONG'
       AND ITEM_CAT_CODE_ID in ('5' , '-100')
       AND PARTITION_KEY = v_prev_partition
       AND SUBPARTITION_KEY = v_prev_subpartition
       AND PRIMARY_IND=1;

Not sure I'm making it very complicated, but still I 'd need to know whether IF THEN ELSE or CASE or whatever should be used and how.

Body:
You can utilize an implicit cursor for loop.

for rec IN ( <your query that gives all records)
LOOP

--compare the value of this variable and decide in the IF condition.

    IF rec.prep_seq_num=0 and rec.primary_ind=0
      THEN
    -- write the query to get the sys_field

     ELSE
    -- write alternative query.

    END IF;

END LOOP;


问:
Phalcon, Send mail in background process
I using phalcon framework,
I need send email (in background process) after submit contact form
Everyone help me with the demo code.
thanks all.</p>

答:
No can't help you with demo code. But can help you with the steps:

Prepare mail message

Put into into queue

In cli task(which will be fired by cron) get messages from queue and send it


问:
R - gsub() for to remove dates from data set
I am using the gsub() function to remove the unwanted text from the data. I just want to have the age in the brackets, not the dates of birth. However, this is in a large data set with differing birth days. </p>

<p>Example of the data: </p>

```<code>Test1$Age

Sep 10, 1990(27)
Mar 26, 1987(30
Feb 24, 1997(20)
</code>```

答:
You can do this using str_extract() from the stringr package:

```<code>s <- "Sep 10, 1990(27)"

# get the age in parentheses
stringr::str_extract(s, "\\([0-9]+\\)")

# just the age, with parentheses removed
stringr::str_extract(s, "(?<=\\()[0-9]+")
</code>```

And the output is:

```<code>> s <- "Sep 10, 1990(27)"
>
> # get the age in parentheses
> stringr::str_extract(s, "\\([0-9]+\\)")
[1] "(27)"
>
> # just the age, with parentheses removed
> stringr::str_extract(s, "(?<=\\()[0-9]+")
[1] "27"
</code>```

The first regular expression matches paired parentheses containing one or more digits. The second regular expression uses positive lookbehind to match one or more digits following an opening parenthesis.

If your data is in a data.frame df with the column named age, then you could do the following:

```<code>df$age <- stringr::str_extract(df$age, "\\([0-9]+\\)")
</code>```

Or, in tidyverse notation:

```<code>df <- df %>% mutate(age = stringr::str_extract(age, "\\([0-9]+\\)"))
</code>```

Body:
I am using the gsub() function to remove the unwanted text from the data. I just want to have the age in the brackets, not the dates of birth. However, this is in a large data set with differing birth days.

Example of the data:

Test1$Age

Sep 10, 1990(27)
Mar 26, 1987(30
Feb 24, 1997(20)

Body:
You can do this using str_extract() from the stringr package:

s <- "Sep 10, 1990(27)"

# get the age in parentheses
stringr::str_extract(s, "\\([0-9]+\\)")

# just the age, with parentheses removed
stringr::str_extract(s, "(?<=\\()[0-9]+")

And the output is:

> s <- "Sep 10, 1990(27)"
>
> # get the age in parentheses
> stringr::str_extract(s, "\\([0-9]+\\)")
[1] "(27)"
>
> # just the age, with parentheses removed
> stringr::str_extract(s, "(?<=\\()[0-9]+")
[1] "27"

The first regular expression matches paired parentheses containing one or more digits. The second regular expression uses positive lookbehind to match one or more digits following an opening parenthesis.

If your data is in a data.frame df with the column named age, then you could do the following:

df$age <- stringr::str_extract(df$age, "\\([0-9]+\\)")

Or, in tidyverse notation:

df <- df %>% mutate(age = stringr::str_extract(age, "\\([0-9]+\\)"))


问:
Angular 2/4 pushing in array inside an object
I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

```<code>export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}
</code>```

Each time some one types a comment I want to add it to the comment array something like this

```<code>  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})
</code>```

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved.
Please let me know how can I push comment values

答:
Be sure to initialize always yours objects and array... you can do it in different ways so for example ...

```<code>export class test{
         recordname: string;
         comments: any[] = []; //set it as empty array ...intilized
    }

addcomment: test = new test(); //<-- INITIALIZE IT
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'});
}
</code>```

Or if you don't like this approch ...

```<code>addcomment: test = new test(); //<-- INITIALIZE IT
    addRow(){

//check if nested array is undefined ..or other
 if(!this.addcomment.comment || this.addcomment.comment.length<=0)
     {
       this.addcomment.comment =[]; //<-- INITIALIZE AS EMPTY ARRAY
     }
        this.addcomment.comment.push({
            comment : 'first comment'});
    }
</code>```

Hope it helps you!!

Body:
I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}

Each time some one types a comment I want to add it to the comment array something like this

  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved.
Please let me know how can I push comment values

Body:
Be sure to initialize always yours objects and array... you can do it in different ways so for example ...

export class test{
         recordname: string;
         comments: any[] = []; //set it as empty array ...intilized
    }

addcomment: test = new test(); //<-- INITIALIZE IT
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'});
}

Or if you don't like this approch ...

addcomment: test = new test(); //<-- INITIALIZE IT
    addRow(){

//check if nested array is undefined ..or other
 if(!this.addcomment.comment || this.addcomment.comment.length<=0)
     {
       this.addcomment.comment =[]; //<-- INITIALIZE AS EMPTY ARRAY
     }
        this.addcomment.comment.push({
            comment : 'first comment'});
    }

Hope it helps you!!


问:
Can only concatenate tuple (not "int") to tuple
It doesn't move like it should be and it says:

x += x_change
  TypeError: can only concatenate tuple (not "int") to tuple

Code is here:

```<code>import pygame

pygame.init()

display_width = 800
display_height = 600

green = (30,255,50)

gameDisplay = pygame.display.set_mode((display_width,display_height))

pygame.display.set_caption("testV1.0")

clock = pygame.time.Clock()

CharacterImg = pygame.image.load("Character.png")
def Character(x,y):
    gameDisplay.blit(CharacterImg,(x,y))

x = (display_width * 0,45)
y = (display_height * 0,8)

x_change = 0

hit = False

while not hit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            hit = True

            if event.type == pygame.KEYDOWN:
                if pygame.key == K_LEFT:
                    x_change += -50
                if pygame.key == K_RIGHT:
                    x_change += 50

            if event.type == pygame.KEYUP:
                if pygame.key == K_LEFT:
                    x_change += 50
                if pygame.key == K_RIGHT:
                    x_change += -50

            x += x_change

        print(event)

    gameDisplay.fill(green)
    Character(x,y)
    pygame.display.update()
    clock.tick(30)

pygame.quit()
quit()
</code>```

答:
For python, you are using the wrong decimal separator , in your code, should be .

Bad

```<code>x = (display_width * 0,45)
y = (display_height * 0,8)
</code>```

Good

```<code>x = (display_width * 0.45)
y = (display_height * 0.8)
</code>```

Body:
It doesn't move like it should be and it says:

x += x_change
  TypeError: can only concatenate tuple (not "int") to tuple

Code is here:

import pygame

pygame.init()

display_width = 800
display_height = 600

green = (30,255,50)

gameDisplay = pygame.display.set_mode((display_width,display_height))

pygame.display.set_caption("testV1.0")

clock = pygame.time.Clock()

CharacterImg = pygame.image.load("Character.png")
def Character(x,y):
    gameDisplay.blit(CharacterImg,(x,y))

x = (display_width * 0,45)
y = (display_height * 0,8)

x_change = 0

hit = False

while not hit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            hit = True

            if event.type == pygame.KEYDOWN:
                if pygame.key == K_LEFT:
                    x_change += -50
                if pygame.key == K_RIGHT:
                    x_change += 50

            if event.type == pygame.KEYUP:
                if pygame.key == K_LEFT:
                    x_change += 50
                if pygame.key == K_RIGHT:
                    x_change += -50

            x += x_change

        print(event)

    gameDisplay.fill(green)
    Character(x,y)
    pygame.display.update()
    clock.tick(30)

pygame.quit()
quit()

Body:
For python, you are using the wrong decimal separator , in your code, should be .

Bad

x = (display_width * 0,45)
y = (display_height * 0,8)

Good

x = (display_width * 0.45)
y = (display_height * 0.8)


问:
Using time() inside a while loop
For a school assignment we need to write a PHP script that counts for 1 second.

The following code I wrote should do exactly that was my thought:

```<code>$startTijd = time();
$teller = 0;
while($startTijd == time()){
    echo 'Iteratie: ' . $teller . '<br>';
    $teller++;
}
</code>```

However, every time I run this or any PHP script similar to it that uses the time() function inside a while loop I get a 502 bad request from the server when I try to visit the page.

答:
Your code makes no sense... your while statment is only true if you computer is fast enough.

```<code>$startTijd = 100; # you set here the time represented by a number

while(100 == time() #101) { # here time is some milliseconds or seconds in the future
</code>```

so after a second your while stops so that make not so much sense. Then use

```<code>while(true) {
</code>```

and stop the while with a condition insight the while loop.

Title: Using time() inside a while loop

Body:
For a school assignment we need to write a PHP script that counts for 1 second.

The following code I wrote should do exactly that was my thought:

$startTijd = time();
$teller = 0;
while($startTijd == time()){
    echo 'Iteratie: ' . $teller . '
';
    $teller++;
}

However, every time I run this or any PHP script similar to it that uses the time() function inside a while loop I get a 502 bad request from the server when I try to visit the page.

Body:
Your code makes no sense... your while statment is only true if you computer is fast enough.

$startTijd = 100; # you set here the time represented by a number

while(100 == time() #101) { # here time is some milliseconds or seconds in the future

so after a second your while stops so that make not so much sense. Then use

while(true) {

and stop the while with a condition insight the while loop.


问:
Displaying Buffered percentage of Audio
Why I am not able to display the buffered percentage of Audio using Javascript?

var audio = document.getElementById("aone1");
var percentages = document.getElementById("aone1l");

function loop() {
  var buffered = audio.buffered;
  var loaded;
  var played;

  if (buffered.length) {
    loaded = 100 * buffered.end(0) / audio.duration;
    played = 100 * audio.currentTime / audio.duration;
    percentages[0].innerHTML = loaded.toFixed(2);
    percentages[1].innerHTML = played.toFixed(2);
  }

  setTimeout(loop, 50);
}

loop();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio id="aone1" controls="controls">
   <source src="http://jainvidhya.epizy.com/Audio/Part1/ऑडियो नंबर 1 नमस्कार महामंत्र.mp4">
</audio>
<p>Loaded: <span id="aone1l"></span>%</p>
<p>Played: <span id="aone1l"></span>%</p></code>```

Also why the audio takes much time to load?

答:
Use unique id or use classes instead here, which will give you an array and then set the innerHTML:

var audio = document.getElementById("aone1");
var percentages = document.getElementsByClassName("aone1l")

function loop() {
  var buffered = audio.buffered;
  var loaded;
  var played;

  if (buffered.length) {
    loaded = 100 * buffered.end(0) / audio.duration;
    played = 100 * audio.currentTime / audio.duration;
    percentages[0].innerHTML = loaded.toFixed(2);
    percentages[1].innerHTML = played.toFixed(2);
  }

  setTimeout(loop, 50);
}

loop();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio id="aone1" controls="controls">
   <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3">
</audio>
<p>Loaded: <span class="aone1l"></span>%</p>
<p>Played: <span class="aone1l"></span>%</p></code>```

Title: Displaying Buffered percentage of Audio

Body:
Why I am not able to display the buffered percentage of Audio using Javascript?

var audio = document.getElementById("aone1");
var percentages = document.getElementById("aone1l");

function loop() {
  var buffered = audio.buffered;
  var loaded;
  var played;

  if (buffered.length) {
    loaded = 100 * buffered.end(0) / audio.duration;
    played = 100 * audio.currentTime / audio.duration;
    percentages[0].innerHTML = loaded.toFixed(2);
    percentages[1].innerHTML = played.toFixed(2);
  }

  setTimeout(loop, 50);
}

loop();

<audio id="aone1" controls="controls">
   <source src="http://jainvidhya.epizy.com/Audio/Part1/ऑडियो नंबर 1 नमस्कार महामंत्र.mp4">
</audio>

Loaded: %

Played: %

Also why the audio takes much time to load?

Body:
Use unique id or use classes instead here, which will give you an array and then set the innerHTML:

var audio = document.getElementById("aone1");
var percentages = document.getElementsByClassName("aone1l")

function loop() {
  var buffered = audio.buffered;
  var loaded;
  var played;

  if (buffered.length) {
    loaded = 100 * buffered.end(0) / audio.duration;
    played = 100 * audio.currentTime / audio.duration;
    percentages[0].innerHTML = loaded.toFixed(2);
    percentages[1].innerHTML = played.toFixed(2);
  }

  setTimeout(loop, 50);
}

loop();

<audio id="aone1" controls="controls">
   <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3">
</audio>
<p>Loaded: <span class="aone1l"></span>%</p>
<p>Played: <span class="aone1l"></span>%</p>


问:
PostgreSQL SELECT, UPDATE and INSERT together
I'm currently trying to SELECT columns from a table, do some arithmetic with the selected values and then INSERT the updated values back into the same table. So far, I'm thinking of SELECT all columns, copy to another table, UPDATE that table and copy it back but this seems kinda redundant.

```<code>INSERT INTO tableB (x, y) SELECT x, y FROM tableA;

UPDATE tableB SET y = y + 1;

INSERT INTO tableA (x, y) SELECT x, y FROM tableB;
</code>```

where x and y are declared UNIQUE(x, y)

EDIT: Is there a way to avoid creating another table for this transaction?

答:
If you want to copy the changed data, you can do that with a single insert:</p>

```<code>insert into tablea (x,y)
select x, y + 1
from tablea;
</code>```

Body:
I'm currently trying to SELECT columns from a table, do some arithmetic with the selected values and then INSERT the updated values back into the same table. So far, I'm thinking of SELECT all columns, copy to another table, UPDATE that table and copy it back but this seems kinda redundant.

INSERT INTO tableB (x, y) SELECT x, y FROM tableA;

UPDATE tableB SET y = y + 1;

INSERT INTO tableA (x, y) SELECT x, y FROM tableB;

where x and y are declared UNIQUE(x, y)

EDIT: Is there a way to avoid creating another table for this transaction?

Body:
If you want to copy the changed data, you can do that with a single insert:

insert into tablea (x,y)
select x, y + 1
from tablea;


问:
Ruby on Rails: Destroy action displays an error
If you execute the destroy action, you will get such an error.
URL:http://localhost:3000/listings/test

View

```<code><% @alllistings.all.order(created_at: :desc).each do |listing| %>
        <tbody>
          <tr>
            <th scope="row">
              <%= link_to listing_path(listing) do %>
                <span class="listing-title"><%= listing.listing_title %></span>
              <% end %>
            </th>
            <td>
              <%= link_to "delete",[listing],method: :delete, data: {confirm: "Are you sure?"} if current_user = listing.user %>
            </td>
          </tr>
        </tbody>
  <% end %>
</code>```

Controller

```<code>class ListingsController < ApplicationController
before_action :set_listing, only: [:destroy]
  def index
    @alllistings = current_user.listings
  end
  def destroy
    @listing.destroy

    return reedirect_to listings_path, notice: "削除しました", :status => :moved_permanently
  end

private
  def set_listing
    @listing = Listing.friendly.find(params[:id])
  end
end
</code>```

Model

```<code>class Listing < ApplicationRecord
 validates :listing_title, presence: true

  include FriendlyId
  friendly_id :listing_title

  def should_generate_new_friendly_id?
     listing_title_changed?
  end
end
</code>```

rails 5
We are using gem 'friendly_id'.
We also introduced slug.

Please answer me my question.

答:
Please try to use in your view.

```<code><%= link_to "delete",listing_path(listing), method: :delete, data: {confirm: "Are you sure?"} if current_user = listing.user %>
</code>```

Body:
If you execute the destroy action, you will get such an error.
URL:http://localhost:3000/listings/test

View

<% @alllistings.all.order(created_at: :desc).each do |listing| %>

              <%= link_to listing_path(listing) do %>
                <%= listing.listing_title %>
              <% end %>

              <%= link_to "delete",[listing],method: :delete, data: {confirm: "Are you sure?"} if current_user = listing.user %>

  <% end %>

Controller

class ListingsController < ApplicationController
before_action :set_listing, only: [:destroy]
  def index
    @alllistings = current_user.listings
  end
  def destroy
    @listing.destroy

    return reedirect_to listings_path, notice: "削除しました", :status => :moved_permanently
  end

private
  def set_listing
    @listing = Listing.friendly.find(params[:id])
  end
end

Model

class Listing < ApplicationRecord
 validates :listing_title, presence: true

  include FriendlyId
  friendly_id :listing_title

  def should_generate_new_friendly_id?
     listing_title_changed?
  end
end

rails 5
We are using gem 'friendly_id'.
We also introduced slug.

Please answer me my question.

Body:
Please try to use in your view.

<%= link_to "delete",listing_path(listing), method: :delete, data: {confirm: "Are you sure?"} if current_user = listing.user %>


问:
Build xamarin android project unsucessfully,error XA4212
At visual Studio 2017 15.4,everything goes fine.But after I upgrated to 15.5,my xamarin android project can not be built successfully,showing:</p>

```<code>error XA4212: Type `Android.Support.V4.App.JobIntentService/JobServiceEngineImpl` implements `Android.Runtime.IJavaObject` but does not inherit `Java.Lang.Object` or `Java.Lang.Throwable`. This is not supported.
</code>```

答:
AndroidErrorOnCustomJavaObject :

A boolean property that determines whether types may implement
  Android.Runtime.IJavaObject without also inheriting from
  Java.Lang.Object or Java.Lang.Throwable:

```<code>class BadType : IJavaObject {
    public IntPtr Handle {
        get {return IntPtr.Zero;}
    }

    public void Dispose()
    {
    }
}
</code>```

When True, such types will generate an XA4212 error, otherwise a XA4212 warning will be generated.

Support for this property was added in Xamarin.Android 8.1.

This property is True by default.

Body:
At visual Studio 2017 15.4,everything goes fine.But after I upgrated to 15.5,my xamarin android project can not be built successfully,showing:

error XA4212: Type `Android.Support.V4.App.JobIntentService/JobServiceEngineImpl` implements `Android.Runtime.IJavaObject` but does not inherit `Java.Lang.Object` or `Java.Lang.Throwable`. This is not supported.

Body:
AndroidErrorOnCustomJavaObject :

A boolean property that determines whether types may implement
  Android.Runtime.IJavaObject without also inheriting from
  Java.Lang.Object or Java.Lang.Throwable:

class BadType : IJavaObject {
    public IntPtr Handle {
        get {return IntPtr.Zero;}
    }

    public void Dispose()
    {
    }
}

When True, such types will generate an XA4212 error, otherwise a XA4212 warning will be generated.

Support for this property was added in Xamarin.Android 8.1.

This property is True by default.


问:
d3.layout.histogram() and attributes don't work in v4
I would like to "convert" a D3.js v3 based code to D3.js v4.

I don't know what I have to change in the following code that it doesnt display any error:

```<code>var data = d3.layout.histogram()
                        .bins(resolution)
                        .frequency(0)
                        (results);
</code>```

I know that in d3.js v4 there isn't something like d3.layout.histogram() - I only found d3.histogram() in the API. But how do I change the "syntax" of line 2-4 in order to make it working with v4? Thanks in Advance.

答:
According to this article we have the following list of differences between histogram layout in d3v3 and d3v4:

d3.layout.histogram becomes d3.histogram

.bins becomes .thresholds

d3.scale.linear becomes d3.scaleLinear

d.x+d.dx becomes d.x1

d.y becomes d.length

d.dx becomes d.x1-d.x0

More detailed explanations from d3v4 changelog:

The new d3.histogram API replaces d3.layout.histogram. Rather than
  exposing bin.x and bin.dx on each returned bin, the histogram exposes
  bin.x0 and bin.x1, guaranteeing that bin.x0 is exactly equal to bin.x1
  on the preceeding bin. The “frequency” and “probability” modes are no
  longer supported; each bin is simply an array of elements from the
  input data, so bin.length is equal to D3 3.x’s bin.y in frequency
  mode. To compute a probability distribution, divide the number of
  elements in each bin by the total number of elements.

The histogram.range method has been renamed histogram.domain for
  consistency with scales. The histogram.bins method has been renamed
  histogram.thresholds, and no longer accepts an upper value: n
  thresholds will produce n + 1 bins. If you specify a desired number of
  bins rather than thresholds, d3.histogram now uses d3.ticks to compute
  nice bin thresholds. In addition to the default Sturges’ formula, D3
  now implements the Freedman-Diaconis rule and Scott’s normal reference rule.

So you should rewrite mentioned code snippet this way:

```<code>var data = d3.histogram()
  .thresholds(resolution)
  (results);
</code>```

But you also need to rewrite other parts of your code and replace: d.x+d.dx to d.x1, d.y to d.length and d.dx to d.x1-d.x0.

Example how to create histogram layout with d3v4 see in the hidden snippet below:

var data = [
  79, 54, 74, 62, 85, 55, 88, 85, 51, 85, 54, 84, 78, 47, 83, 52, 62, 84, 52, 79, 51, 47, 78, 69, 74, 83, 55, 76, 78, 79, 73, 77, 66, 80, 74, 52, 48, 80, 59, 90, 80, 58, 84, 58, 73, 83, 64, 53,
  82, 59, 75, 90, 54, 80, 54, 83, 71, 64, 77, 81, 59, 84, 48, 82, 60, 92, 78, 78, 65, 73, 82, 56, 79, 71, 62, 76, 60, 78, 76, 83, 75, 82, 70, 65, 73, 88, 76, 80, 48, 86, 60, 90, 50, 78, 63, 72,
  84, 75, 51, 82, 62, 88, 49, 83, 81, 47, 84, 52, 86, 81, 75, 59, 89, 79, 59, 81, 50, 85, 59, 87, 53, 69, 77, 56, 88, 81, 45, 82, 55, 90, 45, 83, 56, 89, 46, 82, 51, 86, 53, 79, 81, 60, 82, 77,
  76, 59, 80, 49, 96, 53, 77, 77, 65, 81, 71, 70, 81, 93, 53, 89, 45, 86, 58, 78, 66, 76, 63, 88, 52, 93, 49, 57, 77, 68, 81, 81, 73, 50, 85, 74, 55, 77, 83, 83, 51, 78, 84, 46, 83, 55, 81, 57,
  76, 84, 77, 81, 87, 77, 51, 78, 60, 82, 91, 53, 78, 46, 77, 84, 49, 83, 71, 80, 49, 75, 64, 76, 53, 94, 55, 76, 50, 82, 54, 75, 78, 79, 78, 78, 70, 79, 70, 54, 86, 50, 90, 54, 54, 77, 79, 64,
  75, 47, 86, 63, 85, 82, 57, 82, 67, 74, 54, 83, 73, 73, 88, 80, 71, 83, 56, 79, 78, 84, 58, 83, 43, 60, 75, 81, 46, 90, 46, 74
];

var width = 952;
var height = 476;
var x = d3.scaleLinear().domain([30, 110]).range([0, width]);

var bins = d3.histogram().domain(x.domain()).thresholds(x.ticks(30))(data);

var max = d3.max(bins, function(d) {
  return d.y;
});

var y = d3.scaleLinear().domain([0, .1]).range([0, height]);

var yForHistogram = d3.scaleLinear()
  .domain([0, d3.max(bins, function(d) {
    return d.length;
  })])
  .range([height, 0]);

var vis = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var bars = vis.selectAll("g.bar")
  .data(bins)
  .enter().append("g")
  .attr("class", "bar")
  .attr("transform", function(d) {
    return "translate(" + x(d.x0) + "," + yForHistogram(d.length) + ")";
  });

bars.append("rect")
  .attr("fill", "steelblue")
  .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
  .attr("height", function(d) {
    return height - yForHistogram(d.length);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js"></script></code>```

Body:
I would like to "convert" a D3.js v3 based code to D3.js v4.

I don't know what I have to change in the following code that it doesnt display any error:

var data = d3.layout.histogram()
                        .bins(resolution)
                        .frequency(0)
                        (results);

I know that in d3.js v4 there isn't something like d3.layout.histogram() - I only found d3.histogram() in the API. But how do I change the "syntax" of line 2-4 in order to make it working with v4? Thanks in Advance.

Body:
According to this article we have the following list of differences between histogram layout in d3v3 and d3v4:

d3.layout.histogram becomes d3.histogram

.bins becomes .thresholds

d3.scale.linear becomes d3.scaleLinear

d.x+d.dx becomes d.x1

d.y becomes d.length

d.dx becomes d.x1-d.x0

More detailed explanations from d3v4 changelog:

The new d3.histogram API replaces d3.layout.histogram. Rather than
  exposing bin.x and bin.dx on each returned bin, the histogram exposes
  bin.x0 and bin.x1, guaranteeing that bin.x0 is exactly equal to bin.x1
  on the preceeding bin. The “frequency” and “probability” modes are no
  longer supported; each bin is simply an array of elements from the
  input data, so bin.length is equal to D3 3.x’s bin.y in frequency
  mode. To compute a probability distribution, divide the number of
  elements in each bin by the total number of elements.

The histogram.range method has been renamed histogram.domain for
  consistency with scales. The histogram.bins method has been renamed
  histogram.thresholds, and no longer accepts an upper value: n
  thresholds will produce n + 1 bins. If you specify a desired number of
  bins rather than thresholds, d3.histogram now uses d3.ticks to compute
  nice bin thresholds. In addition to the default Sturges’ formula, D3
  now implements the Freedman-Diaconis rule and Scott’s normal reference rule.

So you should rewrite mentioned code snippet this way:

var data = d3.histogram()
  .thresholds(resolution)
  (results);

But you also need to rewrite other parts of your code and replace: d.x+d.dx to d.x1, d.y to d.length and d.dx to d.x1-d.x0.

Example how to create histogram layout with d3v4 see in the hidden snippet below:

var data = [
  79, 54, 74, 62, 85, 55, 88, 85, 51, 85, 54, 84, 78, 47, 83, 52, 62, 84, 52, 79, 51, 47, 78, 69, 74, 83, 55, 76, 78, 79, 73, 77, 66, 80, 74, 52, 48, 80, 59, 90, 80, 58, 84, 58, 73, 83, 64, 53,
  82, 59, 75, 90, 54, 80, 54, 83, 71, 64, 77, 81, 59, 84, 48, 82, 60, 92, 78, 78, 65, 73, 82, 56, 79, 71, 62, 76, 60, 78, 76, 83, 75, 82, 70, 65, 73, 88, 76, 80, 48, 86, 60, 90, 50, 78, 63, 72,
  84, 75, 51, 82, 62, 88, 49, 83, 81, 47, 84, 52, 86, 81, 75, 59, 89, 79, 59, 81, 50, 85, 59, 87, 53, 69, 77, 56, 88, 81, 45, 82, 55, 90, 45, 83, 56, 89, 46, 82, 51, 86, 53, 79, 81, 60, 82, 77,
  76, 59, 80, 49, 96, 53, 77, 77, 65, 81, 71, 70, 81, 93, 53, 89, 45, 86, 58, 78, 66, 76, 63, 88, 52, 93, 49, 57, 77, 68, 81, 81, 73, 50, 85, 74, 55, 77, 83, 83, 51, 78, 84, 46, 83, 55, 81, 57,
  76, 84, 77, 81, 87, 77, 51, 78, 60, 82, 91, 53, 78, 46, 77, 84, 49, 83, 71, 80, 49, 75, 64, 76, 53, 94, 55, 76, 50, 82, 54, 75, 78, 79, 78, 78, 70, 79, 70, 54, 86, 50, 90, 54, 54, 77, 79, 64,
  75, 47, 86, 63, 85, 82, 57, 82, 67, 74, 54, 83, 73, 73, 88, 80, 71, 83, 56, 79, 78, 84, 58, 83, 43, 60, 75, 81, 46, 90, 46, 74
];

var width = 952;
var height = 476;
var x = d3.scaleLinear().domain([30, 110]).range([0, width]);

var bins = d3.histogram().domain(x.domain()).thresholds(x.ticks(30))(data);

var max = d3.max(bins, function(d) {
  return d.y;
});

var y = d3.scaleLinear().domain([0, .1]).range([0, height]);

var yForHistogram = d3.scaleLinear()
  .domain([0, d3.max(bins, function(d) {
    return d.length;
  })])
  .range([height, 0]);

var vis = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var bars = vis.selectAll("g.bar")
  .data(bins)
  .enter().append("g")
  .attr("class", "bar")
  .attr("transform", function(d) {
    return "translate(" + x(d.x0) + "," + yForHistogram(d.length) + ")";
  });

bars.append("rect")
  .attr("fill", "steelblue")
  .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
  .attr("height", function(d) {
    return height - yForHistogram(d.length);
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js"></script>


问:
API call failed: Error executing API call (request): Unauthorized request
I am trying to integrate Mollie payment gateway by using these detail

```<code>$mollie = new Mollie_API_Client;
$mollie->setApiKey('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM');

$order_id = time();
$protocol = isset($_SERVER['HTTPS']) && strcasecmp('off', $_SERVER['HTTPS']) !== 0 ? "https" : "http";
$hostname = $_SERVER['HTTP_HOST'];
$path     = dirname(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']);

$payment = $mollie->payments->create(array(
        "amount"       => 10.00,
        "description"  => "My first API payment",
        "redirectUrl"  => "{$protocol}://{$hostname}{$path}/3-return-page.php?order_id={$order_id}",
        "metadata"     => array(
            "order_id" => $order_id,
        ),
    ));
</code>```

after run the code it through error

API call failed: Error executing API call (request): Unauthorized
  request.

please tell me where i do mistake

THANKS!

答:
You are receiving this error from the Mollie server. The Mollie API has made a HTTP POST request from your server to Mollie server. The response was: Unauthorized request

The most likely reason is that you are using the wrong API key. Visit the Mollie dashboard and copy-paste the appropriate key (either test or live)...

Body:
I am trying to integrate Mollie payment gateway by using these detail

$mollie = new Mollie_API_Client;
$mollie->setApiKey('test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM');

$order_id = time();
$protocol = isset($_SERVER['HTTPS']) && strcasecmp('off', $_SERVER['HTTPS']) !== 0 ? "https" : "http";
$hostname = $_SERVER['HTTP_HOST'];
$path     = dirname(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']);

$payment = $mollie->payments->create(array(
        "amount"       => 10.00,
        "description"  => "My first API payment",
        "redirectUrl"  => "{$protocol}://{$hostname}{$path}/3-return-page.php?order_id={$order_id}",
        "metadata"     => array(
            "order_id" => $order_id,
        ),
    ));

after run the code it through error

API call failed: Error executing API call (request): Unauthorized
  request.

please tell me where i do mistake

THANKS!


问:
How Make a 2d cube via css
i want have an animation like this:
i want one Square fade in a place holder like code below

```<code>#item1_placeholder{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 7%;
    content: "";
    display: block;
    padding-bottom: 7%;
                                    border: 3px solid #F4DC03;
</code>```

}

and i want this placeholder and cube resize with resizing display window,

then this Square rotate like a 2d cube in some direction like first show the front, then turn to left, then turn to top

can anyone help me!!!

答:
first i must Apology for my bad English, i made it like this below code:

CSS:

```<code>@charset "utf-8";
@media screen and (min-width: 320px) {
    body {
                font-family:'BebasRegular';
                text-align:center;
                background-color: #d0d2d0;
                background-image:url(../Image/Back_pattern.png);
                width: 95%;
                height: 95%;
                margin:auto;
                }

    div#main {
                font-size: 3vw;
                }

    #content {
                        margin:auto;
                        height:100vh;
                        width:100vw;
                    }
}

@font-face {
    font-family: 'BebasRegular';
    src: url('../Fonts/BEBAS___-webfont.eot');
    src: url('../Fonts/BEBAS___-webfont.eot?#iefix') format('embedded-opentype'),
         url('../Fonts/BEBAS___-webfont.woff') format('woff'),
         url('../Fonts/BEBAS___-webfont.ttf') format('truetype'),
         url('../Fonts/BEBAS___-webfont.svg#BebasRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@media only screen and (orientation: landscape) {
#item1_placeholder{
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 7%;
        content: "";
        display: block;
        padding-bottom: 7%;
}

  #AHCube div {
    position: absolute;
    width: 7vw;
    height: 7vw;
    border: 1px solid rgba(0,0,0,0.3);
    background: rgba(255,255,255,1);
    box-shadow: inset 0 0 20px rgba(0,0,0,0.3);
    text-align: center;
    line-height: 120px;
  }

  #AHCube .Front {
  -webkit-transform: translateZ(3.5vw);
  transform: translateZ(3.5vw);
  -moz-transform: translateZ(3.5vw);
  -o-transform: translateZ(3.5vw);
  }
  #AHCube .Right {
  -webkit-transform: rotateY(90deg) translateZ(3.5vw);
  transform: rotateY(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(90deg) translateZ(3.5vw);
  -o-transform: rotateY(90deg) translateZ(3.5vw);
  }
  #AHCube .Top {
  -webkit-transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  -o-transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  }
  #AHCube .Back {
  -webkit-transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  -o-transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  }
  #AHCube .Left {
  -webkit-transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  -o-transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  }
  #AHCube .Below {
  -webkit-transform: rotateX(-90deg) translateZ(3.5vw);
  transform: rotateX(-90deg) translateZ(3.5vw);
  -moz-transform: rotateX(-90deg) translateZ(3.5vw);
  -o-transform: rotateX(-90deg) translateZ(3.5vw);
  background:rgba(3,76,244,1.00);
}

  .AH_Ani1 {
    -webkit-animation-name: spin1;
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-duration: 5s;
    -webkit-animation-fill-mode: forwards;
    -webkit-transform-style: preserve-3d;
    -webkit-transform-origin: 3.5vw 3.5vw 0;

    animation-name: spin1;
    animation-timing-function: ease-in-out;
    animation-iteration-count: 1;
    animation-duration: 5s;
    animation-fill-mode: forwards;
    transform-style: preserve-3d;
    transform-origin: 3.5vw 3.5vw 0;

    -moz-animation-name: spin1;
    -moz-animation-timing-function: ease-in-out;
    -moz-animation-iteration-count: 1;
    -moz-animation-duration: 5s;
    -moz-animation-fill-mode: forwards;
    -moz-transform-style: preserve-3d;
    -moz-transform-origin: 3.5vw 3.5vw 0;

    -o-animation-name: spin1;
    -o-animation-timing-function: ease-in-out;
    -o-animation-iteration-count: 1;
    -o-animation-duration: 5s;
    -o-animation-fill-mode: forwards;
    -o-transform-style: preserve-3d;
    -o-transform-origin: 3.5vw 3.5vw 0;
    }
    .ICO_Hold1 {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        filter: drop-shadow(5% 5% 5% #222);
        width: 80%;
        height: auto;
        display:block;
  }

  @-webkit-keyframes spin1 {
    from,to  { -webkit-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { -webkit-transform:scale(0,0);      }
    10% { -webkit-transform:scale(1,1);     }
    28%      { -webkit-transform: rotateY(-90deg);                           }
    46%      { -webkit-transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { -webkit-transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { -webkit-transform: rotateY(90deg) rotateX(90deg);             }
    100%      { -webkit-transform: rotateX(90deg);                            }
  }
  @keyframes spin1 {
    from,to  { transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { transform:scale(0,0);      }
    10% { transform:scale(1,1);     }
    28%      { transform: rotateY(-90deg);                           }
    46%      { transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { transform: rotateY(90deg) rotateX(90deg);             }
    100%      { transform: rotateX(90deg);                            }
  }
  @-moz-keyframes spin1 {
    from,to  { -moz-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { -moz-transform:scale(0,0);     }
    10% { -moz-transform:scale(1,1);        }
    28%      { -moz-transform: rotateY(-90deg);                           }
    46%      { -moz-transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { -moz-transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { -moz-transform: rotateY(90deg) rotateX(90deg);             }
    100%      { -moz-transform: rotateX(90deg);                            }
  }
  @-o-keyframes spin1 {
    from,to  { -o-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { -o-transform:scale(0,0);       }
    10% { -o-transform:scale(1,1);      }
    28%      { -o-transform: rotateY(-90deg);                           }
    46%      { -o-transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { -o-transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { -o-transform: rotateY(90deg) rotateX(90deg);             }
    100%      { -o-transform: rotateX(90deg);                            }
  }

}

@media only screen and (orientation: portrait) {

#item1_placeholder{
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 0%;
        content: "";
        display: block;
        padding-bottom: 0%;
}
  #AHCube div {
    position: absolute;
    width: 0vw;
    height: 0vw;
    border: 1px solid rgba(0,0,0,0.3);
    background: rgba(255,255,255,1);
    box-shadow: inset 0 0 20px rgba(0,0,0,0.3);
    text-align: center;
    line-height: 120px;
  }
    .ICO_Hold1 {
        position: fixed;
        top: 0%;
        left: 0%;
        transform: translate(-50%, -50%);
         -webkit-filter: drop-shadow(50% 50% 50% #222 );
        filter: drop-shadow(5% 5% 5% #222);
        width: 0%;
        height: auto;
        display:none;
  }
  }
</code>```

HTML:

```<code><div id="item1_placeholder" >

<div id="AHCube" class="AH_Ani1">
<div class="Front"><img class="ICO_Hold1" src="Image/1-1.png" /></div>
<div class="Right"><img class="ICO_Hold1" src="Image/1-2.png" /></div>
<div class="Top"><img class="ICO_Hold1" src="Image/1-3.png" /></div>
<div class="Back"><img class="ICO_Hold1" src="Image/1-4.png"  /></div>
<div class="Left"><img class="ICO_Hold1" src="Image/1-5.png" /></div>
<div class="Below"><img class="ICO_Hold1" src="Image/1-6.png" /></div>

</div>

</div>
</code>```

it work fine in chrome and Mozilla but it is not fine IE or Microsoft Edge, and i didn't check it in portable device

can any one check this and hint me to correct this?

Title: How Make a 2d cube via css

Body:
i want have an animation like this:
i want one Square fade in a place holder like code below

#item1_placeholder{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 7%;
    content: "";
    display: block;
    padding-bottom: 7%;
                                    border: 3px solid #F4DC03;

}

and i want this placeholder and cube resize with resizing display window,

then this Square rotate like a 2d cube in some direction like first show the front, then turn to left, then turn to top

can anyone help me!!!

Body:
first i must Apology for my bad English, i made it like this below code:

CSS:

@charset "utf-8";
@media screen and (min-width: 320px) {
    body {
                font-family:'BebasRegular';
                text-align:center;
                background-color: #d0d2d0;
                background-image:url(../Image/Back_pattern.png);
                width: 95%;
                height: 95%;
                margin:auto;
                }

    div#main {
                font-size: 3vw;
                }

    #content {
                        margin:auto;
                        height:100vh;
                        width:100vw;
                    }
}

@font-face {
    font-family: 'BebasRegular';
    src: url('../Fonts/BEBAS___-webfont.eot');
    src: url('../Fonts/BEBAS___-webfont.eot?#iefix') format('embedded-opentype'),
         url('../Fonts/BEBAS___-webfont.woff') format('woff'),
         url('../Fonts/BEBAS___-webfont.ttf') format('truetype'),
         url('../Fonts/BEBAS___-webfont.svg#BebasRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@media only screen and (orientation: landscape) {
#item1_placeholder{
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 7%;
        content: "";
        display: block;
        padding-bottom: 7%;
}

  #AHCube div {
    position: absolute;
    width: 7vw;
    height: 7vw;
    border: 1px solid rgba(0,0,0,0.3);
    background: rgba(255,255,255,1);
    box-shadow: inset 0 0 20px rgba(0,0,0,0.3);
    text-align: center;
    line-height: 120px;
  }

  #AHCube .Front {
  -webkit-transform: translateZ(3.5vw);
  transform: translateZ(3.5vw);
  -moz-transform: translateZ(3.5vw);
  -o-transform: translateZ(3.5vw);
  }
  #AHCube .Right {
  -webkit-transform: rotateY(90deg) translateZ(3.5vw);
  transform: rotateY(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(90deg) translateZ(3.5vw);
  -o-transform: rotateY(90deg) translateZ(3.5vw);
  }
  #AHCube .Top {
  -webkit-transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  -o-transform: rotateY(90deg) rotateX(90deg) translateZ(3.5vw);
  }
  #AHCube .Back {
  -webkit-transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  -o-transform: rotateY(180deg) rotateZ(90deg) translateZ(3.5vw);
  }
  #AHCube .Left {
  -webkit-transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  -moz-transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  -o-transform: rotateY(-90deg) rotateZ(90deg) translateZ(3.5vw);
  }
  #AHCube .Below {
  -webkit-transform: rotateX(-90deg) translateZ(3.5vw);
  transform: rotateX(-90deg) translateZ(3.5vw);
  -moz-transform: rotateX(-90deg) translateZ(3.5vw);
  -o-transform: rotateX(-90deg) translateZ(3.5vw);
  background:rgba(3,76,244,1.00);
}

  .AH_Ani1 {
    -webkit-animation-name: spin1;
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-duration: 5s;
    -webkit-animation-fill-mode: forwards;
    -webkit-transform-style: preserve-3d;
    -webkit-transform-origin: 3.5vw 3.5vw 0;

    animation-name: spin1;
    animation-timing-function: ease-in-out;
    animation-iteration-count: 1;
    animation-duration: 5s;
    animation-fill-mode: forwards;
    transform-style: preserve-3d;
    transform-origin: 3.5vw 3.5vw 0;

    -moz-animation-name: spin1;
    -moz-animation-timing-function: ease-in-out;
    -moz-animation-iteration-count: 1;
    -moz-animation-duration: 5s;
    -moz-animation-fill-mode: forwards;
    -moz-transform-style: preserve-3d;
    -moz-transform-origin: 3.5vw 3.5vw 0;

    -o-animation-name: spin1;
    -o-animation-timing-function: ease-in-out;
    -o-animation-iteration-count: 1;
    -o-animation-duration: 5s;
    -o-animation-fill-mode: forwards;
    -o-transform-style: preserve-3d;
    -o-transform-origin: 3.5vw 3.5vw 0;
    }
    .ICO_Hold1 {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        filter: drop-shadow(5% 5% 5% #222);
        width: 80%;
        height: auto;
        display:block;
  }

  @-webkit-keyframes spin1 {
    from,to  { -webkit-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { -webkit-transform:scale(0,0);      }
    10% { -webkit-transform:scale(1,1);     }
    28%      { -webkit-transform: rotateY(-90deg);                           }
    46%      { -webkit-transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { -webkit-transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { -webkit-transform: rotateY(90deg) rotateX(90deg);             }
    100%      { -webkit-transform: rotateX(90deg);                            }
  }
  @keyframes spin1 {
    from,to  { transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { transform:scale(0,0);      }
    10% { transform:scale(1,1);     }
    28%      { transform: rotateY(-90deg);                           }
    46%      { transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { transform: rotateY(90deg) rotateX(90deg);             }
    100%      { transform: rotateX(90deg);                            }
  }
  @-moz-keyframes spin1 {
    from,to  { -moz-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { -moz-transform:scale(0,0);     }
    10% { -moz-transform:scale(1,1);        }
    28%      { -moz-transform: rotateY(-90deg);                           }
    46%      { -moz-transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { -moz-transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { -moz-transform: rotateY(90deg) rotateX(90deg);             }
    100%      { -moz-transform: rotateX(90deg);                            }
  }
  @-o-keyframes spin1 {
    from,to  { -o-transform: rotateX(0deg) rotateY(0deg) rotateZ(0deg); }
    0% { -o-transform:scale(0,0);       }
    10% { -o-transform:scale(1,1);      }
    28%      { -o-transform: rotateY(-90deg);                           }
    46%      { -o-transform: rotateY(-90deg) rotateZ(90deg);            }
    64%      { -o-transform: rotateY(-180deg) rotateZ(90deg);           }
    82%      { -o-transform: rotateY(90deg) rotateX(90deg);             }
    100%      { -o-transform: rotateX(90deg);                            }
  }

}

@media only screen and (orientation: portrait) {

#item1_placeholder{
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 0%;
        content: "";
        display: block;
        padding-bottom: 0%;
}
  #AHCube div {
    position: absolute;
    width: 0vw;
    height: 0vw;
    border: 1px solid rgba(0,0,0,0.3);
    background: rgba(255,255,255,1);
    box-shadow: inset 0 0 20px rgba(0,0,0,0.3);
    text-align: center;
    line-height: 120px;
  }
    .ICO_Hold1 {
        position: fixed;
        top: 0%;
        left: 0%;
        transform: translate(-50%, -50%);
         -webkit-filter: drop-shadow(50% 50% 50% #222 );
        filter: drop-shadow(5% 5% 5% #222);
        width: 0%;
        height: auto;
        display:none;
  }
  }

HTML:

<div id="item1_placeholder" >

<div id="AHCube" class="AH_Ani1">
<div class="Front"><img class="ICO_Hold1" src="Image/1-1.png" /></div>
<div class="Right"><img class="ICO_Hold1" src="Image/1-2.png" /></div>
<div class="Top"><img class="ICO_Hold1" src="Image/1-3.png" /></div>
<div class="Back"><img class="ICO_Hold1" src="Image/1-4.png"  /></div>
<div class="Left"><img class="ICO_Hold1" src="Image/1-5.png" /></div>
<div class="Below"><img class="ICO_Hold1" src="Image/1-6.png" /></div>

</div>

</div>

it work fine in chrome and Mozilla but it is not fine IE or Microsoft Edge, and i didn't check it in portable device

can any one check this and hint me to correct this?


问:
Prolog Sudoku Solver, Solve any quadratic Sudoku, elements not distinct
Solving any quadratic Sudoku, so Sudoku of sizes 4,9,16,25... without the need of hard-coding those "blocks", the sub-units of your normal Sudoku field.

Using SWI-Prolog and the clp(FD) library.

Sudokus given in a format like this (list of lists):

```<code>[[_,1,3,_],
 [2,_,_,_],
 [_,_,_,3],
 [_,2,1,_]]
</code>```

Program called using:

```<code>solve_sudoku([[_,1,3,_],[2,_,_,_],[_,_,_,3],[_,2,1,_]],L).
L = [[4, 1, 3, 2], [2, 3, 4, 1], [1, 4, 2, 3], [3, 2, 1, 4]]
</code>```

答:
Top-level from this link.

```<code>sudoku(Rows) :-
  length(Rows,N),
  D is integer(sqrt(N)),
  append(Rows,Vs),Vs ins 1..N,
  maplist(all_distinct,Rows),
  transpose(Rows,Columns),
  maplist(all_distinct,Columns),
  check_blocks(Rows,D),
  maplist(label,Rows).
</code>```

After checking that the rows and columns have no repetitions, we need to check the blocks, which are D by D squares.

The procedure check_blocks/2 takes D rows at a time and passes them to block_columns/4.

```<code>check_blocks(Rows,D) :-
  length(BlockRows,D), append(BlockRows,Rest,Rows),
  block_columns(BlockRows,D,[],[]),
  check_blocks(Rest,D).
check_blocks([],_).
</code>```

Now we have D rows, which are assumed to each contain some number (ie D) of D columns. But we need to get hold of the first D columns of all the rows in order to check the block.

So the first clause in block_columns/4 loops over all the rows and splits them into the prefix (D columns) and the rest. When Rows is empty, Bs is the current block, and Rs the rest of the columns in each row.

```<code>block_columns([Row|Rows],D,Bs,Rs) :-
  length(Cols,D), append(Cols,Rest,Row),
  block_columns(Rows,D,[Cols|Bs],[Rest|Rs]).
block_columns([],D,Bs,Rs) :-
  flatten(Bs,Ns), all_distinct(Ns),
  flatten(Rs,Xs),
  ( Xs = [] ->
    true
  ; block_columns(Rs,D,[],[]) ).
</code>```

The second clause checks the block, and then starts over again. When we have reached the end of the columns, Rs will not be empty but contain D empty lists, so we have to flatten it before checking for termination.

Body:
Solving any quadratic Sudoku, so Sudoku of sizes 4,9,16,25... without the need of hard-coding those "blocks", the sub-units of your normal Sudoku field.

Using SWI-Prolog and the clp(FD) library.

Sudokus given in a format like this (list of lists):

[[_,1,3,_],
 [2,_,_,_],
 [_,_,_,3],
 [_,2,1,_]]

Program called using:

solve_sudoku([[_,1,3,_],[2,_,_,_],[_,_,_,3],[_,2,1,_]],L).
L = [[4, 1, 3, 2], [2, 3, 4, 1], [1, 4, 2, 3], [3, 2, 1, 4]]

Body:
Top-level from this link.

sudoku(Rows) :-
  length(Rows,N),
  D is integer(sqrt(N)),
  append(Rows,Vs),Vs ins 1..N,
  maplist(all_distinct,Rows),
  transpose(Rows,Columns),
  maplist(all_distinct,Columns),
  check_blocks(Rows,D),
  maplist(label,Rows).

After checking that the rows and columns have no repetitions, we need to check the blocks, which are D by D squares.

The procedure check_blocks/2 takes D rows at a time and passes them to block_columns/4.

check_blocks(Rows,D) :-
  length(BlockRows,D), append(BlockRows,Rest,Rows),
  block_columns(BlockRows,D,[],[]),
  check_blocks(Rest,D).
check_blocks([],_).

Now we have D rows, which are assumed to each contain some number (ie D) of D columns. But we need to get hold of the first D columns of all the rows in order to check the block.

So the first clause in block_columns/4 loops over all the rows and splits them into the prefix (D columns) and the rest. When Rows is empty, Bs is the current block, and Rs the rest of the columns in each row.

block_columns([Row|Rows],D,Bs,Rs) :-
  length(Cols,D), append(Cols,Rest,Row),
  block_columns(Rows,D,[Cols|Bs],[Rest|Rs]).
block_columns([],D,Bs,Rs) :-
  flatten(Bs,Ns), all_distinct(Ns),
  flatten(Rs,Xs),
  ( Xs = [] ->
    true
  ; block_columns(Rs,D,[],[]) ).

The second clause checks the block, and then starts over again. When we have reached the end of the columns, Rs will not be empty but contain D empty lists, so we have to flatten it before checking for termination.


问:
In Java, will empty collections of the same type, but different type parameters always be equal?
Consider the following snippet:

```<code>    List<String> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    assertThat(list1.equals(list2), is(true));
</code>```

The assertion succeeds.

Indeed, as far as I understand, there is no way in Java, for the equals method to differentiate between the two, due to run-time type-erasure (i.e. the fact the type arguments String and Integer are only accessible at compile-time, but not at run-time).
And since there are no elements, which could be compared, equals has to return true. And by this line of thought, this must be true, for all collections.

So the question is the following: is my thought process correct, or am I missing something?

EDIT

@qqilihq gave an excellent answer, which prompts the next question:
Is this possible to achieve without passing the type explicitly (I'm fine if the type is stored explicitly somehow, just the user does should not have to pass it.)

I attempted the following, but it did not work (I guess due to type erasure):

```<code>    public TypedList(List<T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = (Class<T>) delegate.getClass();
    }
</code>```

But maybe you can do something similar to this? this.type = T. (This does not compile, but maybe something similar would be possible.)

答:
Generics are used for Type Checking at compile time.

If you create ArrayList like this:

```<code>List<String> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
System.out.println(list1.equals(list2)); // result:true
</code>```

list1 and list2 will be equal because they are empty.ArrayList internally uses Object[] to store ArrayList entry.

If you add some entry to your array list:

```<code>List<String> list1 = new ArrayList<>();
list1.add("A");

List<Integer> list2 = new ArrayList<>();
list2.add(1);

System.out.println(list1.equals(list2)); // result: false
</code>```

This will return false because ArrayList entry are different

Body:
Consider the following snippet:

    List<String> list1 = new ArrayList<>();
    List<Integer> list2 = new ArrayList<>();
    assertThat(list1.equals(list2), is(true));

The assertion succeeds.

Indeed, as far as I understand, there is no way in Java, for the equals method to differentiate between the two, due to run-time type-erasure (i.e. the fact the type arguments String and Integer are only accessible at compile-time, but not at run-time).
And since there are no elements, which could be compared, equals has to return true. And by this line of thought, this must be true, for all collections.

So the question is the following: is my thought process correct, or am I missing something?

EDIT

@qqilihq gave an excellent answer, which prompts the next question:
Is this possible to achieve without passing the type explicitly (I'm fine if the type is stored explicitly somehow, just the user does should not have to pass it.)

I attempted the following, but it did not work (I guess due to type erasure):

    public TypedList(List<T> delegate) {
        this.delegate = Objects.requireNonNull(delegate);
        this.type = (Class<T>) delegate.getClass();
    }

But maybe you can do something similar to this? this.type = T. (This does not compile, but maybe something similar would be possible.)

Body:
Generics are used for Type Checking at compile time.

If you create ArrayList like this:

List<String> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
System.out.println(list1.equals(list2)); // result:true

list1 and list2 will be equal because they are empty.ArrayList internally uses Object[] to store ArrayList entry.

If you add some entry to your array list:

List<String> list1 = new ArrayList<>();
list1.add("A");

List<Integer> list2 = new ArrayList<>();
list2.add(1);

System.out.println(list1.equals(list2)); // result: false

This will return false because ArrayList entry are different


问:
Passing a hash as an initial value when creating an object
I am making a Temperature class with instance methods that convert the temperature from f to c, and vice-versa. A test case is:

```<code>Temperature.new(:f => 32).in_celsius #=> 0
</code>```

I thought that passing :f => 32 would give the conversion. I don't know how to extract the value 32 from the hash :f => 32. I want to extract that so that I can convert that number either into f or c.

Below is my answer code.

```<code>class Temperature
  def initialize(f = 0, c = 0)
    @f = f
    @c = c
  end

  def in_fahrenheit
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    @f
  end

  def celsius
    @c
  end
end
</code>```

I am not familiar with hashes passed as initial values when creating objects. I would appreciate any advice.

答:
You're incorrectly mixing different argument styles.

Positional Arguments

Judging by your call Temperature.new(:f => 32) you seem to think that def initialize(f = 0, c = 0) offers hash or keyword arguments. It doesn't. That's just two positional arguments (with defaults, so they're optional). Let's print out what we get to see what happens:

```<code>  def initialize(f = 0, c = 0)
    puts "f is #{f.inspect}"
    puts "c is #{c.inspect}"
  end
</code>```

Your call:

```<code>Temperature.new(:f => 32)
f is {:f=>32}
c is 0
</code>```

Clearly that's not what you want, and why you get an error later on. Here's how you'd have to call it:

```<code>Temperature.new(32)
f is 32
c is 0

Temperature.new(0, 32)
f is 0
c is 32
</code>```

I'd by the way say that nil would be a better default than 0, because 0 is a perfectly valid temperature. And it's bad having to provide some f value in order to provide a c value.

Hash Argument

Above we saw that Ruby created a hash for you which then became the argument the method got. So you could change the method signature to reflect that, i.e., take a hash, and then extract the values from it:

```<code>  def initialize(options)
    f = options[:f]
    c = options[:c]
    puts "f is #{f.inspect}"
    puts "c is #{c.inspect}"
  end
</code>```

Now you can use it like you did:

```<code>Temperature.new(:f => 32)
f is 32
c is nil

Temperature.new(:c => 32)
f is nil
c is 32
</code>```

Note that this way you do get nil as default. You can also use this nicer syntax:

```<code>Temperature.new(f: 32)
f is 32
c is nil

Temperature.new(c: 32)
f is nil
c is 32
</code>```

Keyword Arguments

Almost five years ago already, Ruby 2 came out and brought us keyword arguments. Now instead of only creating a hash for you, Ruby can also be told to take it apart for you. Like this:

```<code>  def initialize(f: nil, c: nil)
    puts "f is #{f.inspect}"
    puts "c is #{c.inspect}"
  end
</code>```

You can still call it as before:

```<code>Temperature.new(f: 32)
f is 32
c is nil

Temperature.new(c: 32)
f is nil
c is 32
</code>```

Doesn't initialize(f: nil, c: nil) look much more meaningful than initialize(options)? It even looks very much like the calls now. And you don't need extra code to extract the values from the hash. Also, if you mistype an argument name, you now get an error:

```<code>Temperature.new(x: 32)
ArgumentError: unknown keyword: x
</code>```

The single hash parameter solution would just set f and c to nil and happily move on as if there were no problem.

You can btw still call it even with an explicit hash and the rocket notation, though I'm just showing that for additional understanding:

```<code>Temperature.new({:f => 32})
f is 32
c is nil
</code>```

Body:
I am making a Temperature class with instance methods that convert the temperature from f to c, and vice-versa. A test case is:

Temperature.new(:f => 32).in_celsius #=> 0

I thought that passing :f => 32 would give the conversion. I don't know how to extract the value 32 from the hash :f => 32. I want to extract that so that I can convert that number either into f or c.

Below is my answer code.

class Temperature
  def initialize(f = 0, c = 0)
    @f = f
    @c = c
  end

  def in_fahrenheit
    c = @c * 1.8
    c += 32
    @f = c.floor
    @f
  end

  def in_celsius
    f = @f - 32
    f /= 1.8
    @c = f.floor
    @c
  end

  def fahrenheit
    @f
  end

  def celsius
    @c
  end
end

I am not familiar with hashes passed as initial values when creating objects. I would appreciate any advice.

Body:
You're incorrectly mixing different argument styles.

Positional Arguments

Judging by your call Temperature.new(:f => 32) you seem to think that def initialize(f = 0, c = 0) offers hash or keyword arguments. It doesn't. That's just two positional arguments (with defaults, so they're optional). Let's print out what we get to see what happens:

  def initialize(f = 0, c = 0)
    puts "f is #{f.inspect}"
    puts "c is #{c.inspect}"
  end

Your call:

Temperature.new(:f => 32)
f is {:f=>32}
c is 0

Clearly that's not what you want, and why you get an error later on. Here's how you'd have to call it:

Temperature.new(32)
f is 32
c is 0

Temperature.new(0, 32)
f is 0
c is 32

I'd by the way say that nil would be a better default than 0, because 0 is a perfectly valid temperature. And it's bad having to provide some f value in order to provide a c value.

Hash Argument

Above we saw that Ruby created a hash for you which then became the argument the method got. So you could change the method signature to reflect that, i.e., take a hash, and then extract the values from it:

  def initialize(options)
    f = options[:f]
    c = options[:c]
    puts "f is #{f.inspect}"
    puts "c is #{c.inspect}"
  end

Now you can use it like you did:

Temperature.new(:f => 32)
f is 32
c is nil

Temperature.new(:c => 32)
f is nil
c is 32

Note that this way you do get nil as default. You can also use this nicer syntax:

Temperature.new(f: 32)
f is 32
c is nil

Temperature.new(c: 32)
f is nil
c is 32

Keyword Arguments

Almost five years ago already, Ruby 2 came out and brought us keyword arguments. Now instead of only creating a hash for you, Ruby can also be told to take it apart for you. Like this:

  def initialize(f: nil, c: nil)
    puts "f is #{f.inspect}"
    puts "c is #{c.inspect}"
  end

You can still call it as before:

Temperature.new(f: 32)
f is 32
c is nil

Temperature.new(c: 32)
f is nil
c is 32

Doesn't initialize(f: nil, c: nil) look much more meaningful than initialize(options)? It even looks very much like the calls now. And you don't need extra code to extract the values from the hash. Also, if you mistype an argument name, you now get an error:

Temperature.new(x: 32)
ArgumentError: unknown keyword: x

The single hash parameter solution would just set f and c to nil and happily move on as if there were no problem.

You can btw still call it even with an explicit hash and the rocket notation, though I'm just showing that for additional understanding:

Temperature.new({:f => 32})
f is 32
c is nil


问:
Why does adding Microsoft.Extensions.Logging cause could not load file or assembly System.Net.Http version=4.2.0?
I started getting from a new .Net 4.6.2 Unit Test project. It was really strange so I set out to reproduce with a simplified project which I've put on Github and attached. Unzip and run Nuget restore in VS. There are 2 commits. The first has it failing and the 2nd has it fixed after removing the "Microsoft.Extensions.Logging.Abstractions" and Microsoft.Extensions.Logging NuGet packages. Adding that package back in will cause the tests to fail.

Please help me understand this strange issue. Does it have something to do this package being from .Net Standard? System.Net.Http is coming from .NET Core + Platform Extensions, according to apisofnet, but I'm not using .Net Core.

What can I do continue using System.Net.Http version 4.0.0.0?
Build output has: Unified primary reference "System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

Update  Note: I ran through this same exercise of removing Nuget packages from my first commit and the tests didn't pass, so all of this may be a red herring. The screenshots below show that I was successful one time anyways.

Update 2: I reproduced it with commits step by step: https://github.com/aligneddev/UseSystemNetHttpReferencing/commits/reproduce. I removed all packages, then after removing the last one Microsoft.Extensions.DependencyInjection.Abstractions - system.Net.http is missing build error. I then added in the reference with ReSharper and the unit test passes!

Last Update: downgrading to .Net 4.5.2 solves the problem as well. I don't really want to do that :-).

答:
Adding binding redirection in app.config of UseSystemNetHttp.Test project fixes your issue:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

Body:
Adding binding redirection in app.config of UseSystemNetHttp.Test project fixes your issue:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>


问:
How to update google play services m2repository?
My playServices m2repository version is 58 (11.0.4).
The location is:

```<code>my_android_sdk/extras/google/m2repository/com/google/android/gms
</code>```

Android sdkmanager GUI shows version 58, no update available.

This command

```<code>./tools/bin/sdkmanager --list
</code>```

doesn't show any updates for m2repository either.

Is there any way to get the latest aar-files for playservices?

Solution:

I found the packages here:

play-services-ads-11.6.0

play-services-location-11.6.0

答:
You should not rely on what's inside the m2repository folder of your SDK but on the libraries version you set on your application. AARs are automatically downloaded when you add a dependency like those ones:

```<code>dependencies {
    ....
    implementation "com.google.android.gms:play-services-auth:$LAST_LIB_VERSION"
    implementation "com.google.android.gms:play-services-drive:$LAST_LIB_VERSION"
    //read below to know $LAST_LIB_VERSION values
    ....
}
//the google play services plugin, applied at the end of the build.gradle file
apply plugin: 'com.google.gms.google-services'
</code>```

First of all you should have a project build.gradle similar to this

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$LATEST_AGP_VERSION"
        //as the time of writing $LATEST_AGP_VERSION is 3.0.1

        classpath "com.google.gms:google-services:$GPS_VERSION"
        //read below for $GPS_VERSION values
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

$GPS_VERSION valid values are inside this page

$LAST_LIB_VERSION valid values:

If you are NOT using Firebase functionalities, follow the dependencies version of this
  page, and the dependencies available are listed here

If you are using Firebase functionalities, follow the dependencies version of this
  page, and the dependencies available are listed here

That's all.

Body:
My playServices m2repository version is 58 (11.0.4).
The location is:

my_android_sdk/extras/google/m2repository/com/google/android/gms

Android sdkmanager GUI shows version 58, no update available.

This command

./tools/bin/sdkmanager --list

doesn't show any updates for m2repository either.

Is there any way to get the latest aar-files for playservices?

Solution:

I found the packages here:

play-services-ads-11.6.0

play-services-location-11.6.0

Body:
You should not rely on what's inside the m2repository folder of your SDK but on the libraries version you set on your application. AARs are automatically downloaded when you add a dependency like those ones:

dependencies {
    ....
    implementation "com.google.android.gms:play-services-auth:$LAST_LIB_VERSION"
    implementation "com.google.android.gms:play-services-drive:$LAST_LIB_VERSION"
    //read below to know $LAST_LIB_VERSION values
    ....
}
//the google play services plugin, applied at the end of the build.gradle file
apply plugin: 'com.google.gms.google-services'

First of all you should have a project build.gradle similar to this

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$LATEST_AGP_VERSION"
        //as the time of writing $LATEST_AGP_VERSION is 3.0.1

        classpath "com.google.gms:google-services:$GPS_VERSION"
        //read below for $GPS_VERSION values
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

$GPS_VERSION valid values are inside this page

$LAST_LIB_VERSION valid values:

If you are NOT using Firebase functionalities, follow the dependencies version of this
  page, and the dependencies available are listed here

If you are using Firebase functionalities, follow the dependencies version of this
  page, and the dependencies available are listed here

That's all.


问:
Passing extra properties to maven archetype:generate
I've created a Maven archetype for a custom project setup, which is working wonderfully, but I was wondering if it's possible to pass extra parameters so that I can do some more interesting templating. I tried something like

```<code>mvn archetype:generate -DarchetypeCatalog=local -DdbHost=localhost
</code>```

and put

```<code>...
<option name="db.host.config.option" value="${dbHost}" />
...
</code>```

in my template, but that doesn't seem to work. Is there a way to do this with an archetype?

答:
we need to pass property values in command prompt as well by maintaining it in archetype-metadat.xml but here name should not contain "." symbol as it does't allow you to update the values.

It is restriction in Maven to do not use name like prod.ex.version
you can use prod-ex-version

ContentLicense: CC BY-SA 2.5

Body:
I've created a Maven archetype for a custom project setup, which is working wonderfully, but I was wondering if it's possible to pass extra parameters so that I can do some more interesting templating. I tried something like

mvn archetype:generate -DarchetypeCatalog=local -DdbHost=localhost

and put

...
<option name="db.host.config.option" value="${dbHost}" />
...

in my template, but that doesn't seem to work. Is there a way to do this with an archetype?