问:
Checkboxes don't stay checked after pagination
Whenever I check a checkbox on a listing page, save it then go to page eg 2 (using pagination) and check something there and save it the checkbox on my first page is unchecked. I thought about using AJAX to save checked checkboxes to grails session but don't know how to do that - I'm beginner with JS and using views. Could someone help me out?
Here is the part with listing all companies and checkboxes in my gsp:

```<code> <g:form name="company-list-form" action="listCompany">

    <div>
        <g:textField id="search-field" name="query" value="${params.query}"/>

        <span>
            <g:checkBox id="only-blockades-box" name="onlyBlockades" class="submit-on-change" value="${params.onlyBlockades}" title="Pokaż tylko blokady"/>
            <label for="only-blockades-box">Tylko blokady</label>
        </span>

        <g:actionSubmit value="${message(code: 'default.buttons.search', default: 'Szukaj')}" action="listCompany" class="button_orange"/>
        <g:link action="listCompany" class="button_gray"><g:message code="default.buttons.clean" default="Wyczyść"/></g:link>
    </div>

    <div class="padding-top">
        <table class="table_td company-list-table">
            <tbody>
            <tr class="gray2">
                <th class="first">Id</th>
                <th style="max-width: 100px;">Nazwa</th>
                <th>Id Kontrahenta</th>
                <th title="Dostęp do TPO">TPO</th>
                <th style="width: 20px;" title="Dostawa bezpośrednio do magazynu">Dostawa bezpośrednio</th>
                <th style="width: 20px;" title="Możliwość potwierdzania zamówień">Potwierdzanie zamówień</th>
                <th style="width: 20px;" title="Możliwość importowania awizacji z XLS">Import z Excel</th>
                <th style="width: 20px;" title="Możliwość awizowania zamówionych indeksów">Awizacja zam. indeksów</th>
                <th style="width: 20px;" title="Możliwość awizowania tygodniowego">Awizacja tyg.</th>
                <th style="width: 20px;" title="Dostęp jedynie do awizowania tygodniowego">Tylko awizacja tyg.</th>
                <th title="Limit AGD przypadający na każdą kratkę okna prywatnego">AGD</th>
                <th title="Limit rowerów przypadający na każdą kratkę okna prywatnego">Rowery</th>
                <th>Blokady</th>
                <th class="is-blocked-th">Zablokowany?</th>
            </tr>
            <g:each in="${companyInstanceList}" var="company" status="i">
                <tr class="${(i % 2) == 0 ? 'even' : 'odd'} table_td_gray2 ${i + 1 == companyInstanceList?.size() ? 'last' : ''}">
                    <td class="first" style="text-decoration: underline;">
                        <g:link action="editCompany" id="${company?.id}">${company?.id}</g:link>
                    </td>
                    <td>
                        ${company?.name}
                    </td>
                    <td>
                        ${company?.idKontrahenta}
                    </td>
                    <td>
                        <g:checkBox name="tpoAccess.${company?.id}" id="tpo-access-${company?.id}"
                                    checked="${company?.tpoAccess}"/>
                    </td>
                    <td>
                        <g:checkBox name="directDeliveryAvailable.${company?.id}"
                                    id="direct-delivery-available-${company?.id}"
                                    checked="${company?.directDeliveryAvailable}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToOrderConfirmation.${company?.id}"
                                    id="access-to-order-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderConfirmation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToXlsImport.${company?.id}"
                                    id="access-to-xls-import-${company?.id}"
                                    checked="${company?.accessToXlsImport}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToOrderedProductsAvisation.${company?.id}"
                                    id="access-to-ordered-products-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderedProductsAvisation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessToLimitedAvisation.${company?.id}"
                                    id="access-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessToLimitedAvisation}"/>
                    </td>
                    <td>
                        <g:checkBox name="accessOnlyToLimitedAvisation.${company?.id}"
                                    id="access-only-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessOnlyToLimitedAvisation}"/>
                    </td>
                    <td>
                        <input type="text" name="agdPrivateWindowLimit.${company?.id}"
                               value="${company?.agdPrivateWindowLimit}"
                               class="shortText" id="agd-private-window-limit-${company?.id}"
                               onchange="validateLimits('agdPrivateWindowLimit.${company?.id}')">
                    </td>
                    <td>
                        <input type="text" name="bicyclePrivateWindowLimit.${company?.id}"
                               value="${company?.bicyclePrivateWindowLimit}"
                               class="shortText" id="bicycle-private-window-limit-${company?.id}"
                               onchange="validateLimits('bicyclePrivateWindowLimit.${company.id}')">
                    </td>
                    <td>
                        <g:link class="button_gray" controller="productGroup" action="list" params="[companyId: company?.id, query: params.query ?: '']">
                            Blokady
                        </g:link>
                    </td>
                    <td>
                        <g:if test="${company?.findBlockades()}">
                            <span title="Dostawca ma aktywne blokady grup towarowych." class="bold large">
                                ✓
                            </span>
                        </g:if>
                    </td>
                </tr>
            </g:each>
            </tbody>
        </table>
    </div>

    <div class="paginateButtons">
        <g:paginate controller="company" action="listCompany" total="${companyInstanceTotal}"
                    params="[query: params.query ?: '']"/>
    </div>

    <div style="float:right;">
        <g:link action="createCompany" class="button_orange">
            <g:message code="default.button.create.label" default="Utwórz"/>
        </g:link>
        <g:actionSubmit action="updateCompanies" name="companyListSubmit" class="button_orange" value="Zapisz"/>
    </div>

</g:form>
</code>```

Here is my javascript file associated with that view:

```<code>    function validateLimits(name) {
    document.getElementsByName(name)[0].value = document.getElementsByName(name)[0].value.replace(/[A-Za-z!@#$%^&*" "]/g, "");
    var quantity = document.getElementsByName(name)[0].value;
    var toBeAvised = 9999;
    if (quantity.indexOf(',') > -1 || quantity.indexOf('.') > -1 || /*quantity == "" ||*/ isNaN(quantity)) {
        alert("Limit musi być liczbą całkowitą");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) > toBeAvised) {
        alert("Podana liczba jest większa niż maksymalny limit równy " +toBeAvised + ".");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) < 0) {
        alert("Limit musi być liczbą dodatnią!");
        document.getElementsByName(name)[0].value = '';
    }
}
</code>```

And here is controller method (listCompany):

```<code> def listCompany(Integer max) {
        Person person = Person.read(springSecurityService.principal.id)
        Company comp = person?.company

        params.max = Math.min(max ?: 25, 100)
        params.offset = params.offset ?: 0
        params.readOnly = true

        String q = (params.query as String)?.toLowerCase() ?: ""

        def query = Company.where {
            id != comp?.id
            name =~ "%$q%" || idKontrahenta as String =~ "%$q%"
            if (params.onlyBlockades == "on") {
                id in ProductGroupBlockade.findAllByCompanyIsNotNullAndEnabled(true)*.companyId
            }
        }
        List<Company> companyInstanceList = query.list([max: params.int("max"), offset: params.int("offset"), sort: "name"])
        Integer count = query.count()
        if (flash.message) {
            params.errors = flash.message
        }
        [companyInstanceList: companyInstanceList, companyInstanceTotal: count, companySaved: params.companySaved, errors: params.errors]
    }
</code>```

How I could fix that so my checkboxes stay checked after saving? Right now they become unchecked whenever I go to next page and save some checkboxes there.

答:
The reason is that you need to build your own search parameters to be sent with pagination:

```<code><g:paginate total="${instanceTotal}" params="${search}" />
</code>```

a similar post can be found here with more details of how you build this search params included as links as a form of comment within it.

Edited to add if you wantd to actually ammend pagination yourself by checking additional stuff through jquery i.e.

```<code>var something = $('#somFIeld').val()
</code>```

and adding something through javascript to current pagination instead then take a read of this answer

Body:
Whenever I check a checkbox on a listing page, save it then go to page eg 2 (using pagination) and check something there and save it the checkbox on my first page is unchecked. I thought about using AJAX to save checked checkboxes to grails session but don't know how to do that - I'm beginner with JS and using views. Could someone help me out?
Here is the part with listing all companies and checkboxes in my gsp:

 <g:form name="company-list-form" action="listCompany">

        <g:textField id="search-field" name="query" value="${params.query}"/>

            <g:checkBox id="only-blockades-box" name="onlyBlockades" class="submit-on-change" value="${params.onlyBlockades}" title="Pokaż tylko blokady"/>
            Tylko blokady

        <g:actionSubmit value="${message(code: 'default.buttons.search', default: 'Szukaj')}" action="listCompany" class="button_orange"/>
        <g:link action="listCompany" class="button_gray"><g:message code="default.buttons.clean" default="Wyczyść"/></g:link>

                Id
                Nazwa
                Id Kontrahenta
                TPO
                Dostawa bezpośrednio
                Potwierdzanie zamówień
                Import z Excel
                Awizacja zam. indeksów
                Awizacja tyg.
                Tylko awizacja tyg.
                AGD
                Rowery
                Blokady
                Zablokowany?

            <g:each in="${companyInstanceList}" var="company" status="i">

                        <g:link action="editCompany" id="${company?.id}">${company?.id}</g:link>

                        ${company?.name}

                        ${company?.idKontrahenta}

                        <g:checkBox name="tpoAccess.${company?.id}" id="tpo-access-${company?.id}"
                                    checked="${company?.tpoAccess}"/>

                        <g:checkBox name="directDeliveryAvailable.${company?.id}"
                                    id="direct-delivery-available-${company?.id}"
                                    checked="${company?.directDeliveryAvailable}"/>

                        <g:checkBox name="accessToOrderConfirmation.${company?.id}"
                                    id="access-to-order-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderConfirmation}"/>

                        <g:checkBox name="accessToXlsImport.${company?.id}"
                                    id="access-to-xls-import-${company?.id}"
                                    checked="${company?.accessToXlsImport}"/>

                        <g:checkBox name="accessToOrderedProductsAvisation.${company?.id}"
                                    id="access-to-ordered-products-confirmation-${company?.id}"
                                    checked="${company?.accessToOrderedProductsAvisation}"/>

                        <g:checkBox name="accessToLimitedAvisation.${company?.id}"
                                    id="access-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessToLimitedAvisation}"/>

                        <g:checkBox name="accessOnlyToLimitedAvisation.${company?.id}"
                                    id="access-only-to-limited-avisation-${company?.id}"
                                    checked="${company?.accessOnlyToLimitedAvisation}"/>

                        <input type="text" name="agdPrivateWindowLimit.${company?.id}"
                               value="${company?.agdPrivateWindowLimit}"
                               class="shortText" id="agd-private-window-limit-${company?.id}"
                               onchange="validateLimits('agdPrivateWindowLimit.${company?.id}')">

                        <input type="text" name="bicyclePrivateWindowLimit.${company?.id}"
                               value="${company?.bicyclePrivateWindowLimit}"
                               class="shortText" id="bicycle-private-window-limit-${company?.id}"
                               onchange="validateLimits('bicyclePrivateWindowLimit.${company.id}')">

                        <g:link class="button_gray" controller="productGroup" action="list" params="[companyId: company?.id, query: params.query ?: '']">
                            Blokady
                        </g:link>

                        <g:if test="${company?.findBlockades()}">

                                ✓

                        </g:if>

            </g:each>

        <g:paginate controller="company" action="listCompany" total="${companyInstanceTotal}"
                    params="[query: params.query ?: '']"/>

        <g:link action="createCompany" class="button_orange">
            <g:message code="default.button.create.label" default="Utwórz"/>
        </g:link>
        <g:actionSubmit action="updateCompanies" name="companyListSubmit" class="button_orange" value="Zapisz"/>

</g:form>

Here is my javascript file associated with that view:

    function validateLimits(name) {
    document.getElementsByName(name)[0].value = document.getElementsByName(name)[0].value.replace(/[A-Za-z!@#$%^&*" "]/g, "");
    var quantity = document.getElementsByName(name)[0].value;
    var toBeAvised = 9999;
    if (quantity.indexOf(',') > -1 || quantity.indexOf('.') > -1 || /*quantity == "" ||*/ isNaN(quantity)) {
        alert("Limit musi być liczbą całkowitą");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) > toBeAvised) {
        alert("Podana liczba jest większa niż maksymalny limit równy " +toBeAvised + ".");
        document.getElementsByName(name)[0].value = '';
    } else if (parseInt(quantity) < 0) {
        alert("Limit musi być liczbą dodatnią!");
        document.getElementsByName(name)[0].value = '';
    }
}

And here is controller method (listCompany):

 def listCompany(Integer max) {
        Person person = Person.read(springSecurityService.principal.id)
        Company comp = person?.company

        params.max = Math.min(max ?: 25, 100)
        params.offset = params.offset ?: 0
        params.readOnly = true

        String q = (params.query as String)?.toLowerCase() ?: ""

        def query = Company.where {
            id != comp?.id
            name =~ "%$q%" || idKontrahenta as String =~ "%$q%"
            if (params.onlyBlockades == "on") {
                id in ProductGroupBlockade.findAllByCompanyIsNotNullAndEnabled(true)*.companyId
            }
        }
        List<Company> companyInstanceList = query.list([max: params.int("max"), offset: params.int("offset"), sort: "name"])
        Integer count = query.count()
        if (flash.message) {
            params.errors = flash.message
        }
        [companyInstanceList: companyInstanceList, companyInstanceTotal: count, companySaved: params.companySaved, errors: params.errors]
    }

How I could fix that so my checkboxes stay checked after saving? Right now they become unchecked whenever I go to next page and save some checkboxes there.

Body:
The reason is that you need to build your own search parameters to be sent with pagination:

<g:paginate total="${instanceTotal}" params="${search}" />

a similar post can be found here with more details of how you build this search params included as links as a form of comment within it.

Edited to add if you wantd to actually ammend pagination yourself by checking additional stuff through jquery i.e.

var something = $('#somFIeld').val()

and adding something through javascript to current pagination instead then take a read of this answer


来源: stackexchange

问:
Illegal string offset Warning PHP
I get a strange PHP error after updating my php version to 5.4.0-3.

I have this array:

```<code>Array
(
    [host] => 127.0.0.1
    [port] => 11211
)
</code>```

When I try to access it like this I get strange warnings

```<code> print $memcachedConfig['host'];
 print $memcachedConfig['port'];

 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...
</code>```

I really don't want to just edit my php.ini and re-set the error level.

答:
It's an old one but in case someone can benefit from this.
You will also get this error if your array is empty.

In my case I had:

```<code>$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
</code>```

which I changed to:

```<code>$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
if(is_array($buyers_array)) {
   echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
} else {
   echo 'Buyers id ' . $this_buyer_id . ' not found';
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Illegal string offset Warning PHP

Body:
I get a strange PHP error after updating my php version to 5.4.0-3.

I have this array:

Array
(
    [host] => 127.0.0.1
    [port] => 11211
)

When I try to access it like this I get strange warnings

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];

 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...

I really don't want to just edit my php.ini and re-set the error level.

Body:
It's an old one but in case someone can benefit from this.
You will also get this error if your array is empty.

In my case I had:

$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];

which I changed to:

$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
if(is_array($buyers_array)) {
   echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname'];
} else {
   echo 'Buyers id ' . $this_buyer_id . ' not found';
}

ContentLicense: CC BY-SA 3.0


问:
MySQL Query error using UNION/UNION ALL and Group By
Generate the following two result sets:

1). Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

2). Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

There are total [occupation_count] [occupation]s.

Table Name: Occupations

Total Columns: Two = 'Name' and 'Occupation', demo table is shown below:

Sample Output:

```<code>Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are total 2 doctors.
There are total 2 singers.
There are total 3 actors.
There are total 3 professors.
</code>```

My Approach:

```<code>(SELECT NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')'
    FROM OCCUPATIONS ORDER BY NAME)
UNION ALL
(SELECT COUNT(*) FROM OCCUPATIONS GROUP BY OCCUPATION ORDER BY ASEC);
</code>```

Error:

```<code>ERROR 1222 (21000) at line 1:
    The used SELECT statements have a different number of columns
</code>```

Thank You!

答:
```<code>(
  SELECT CONCAT(NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')') as THETEXT
    FROM OCCUPATIONS
)
UNION ALL
(
  SELECT CONCAT('There are total ', COUNT(*),' ', LOWER(OCCUPATION) ,(IF (COUNT(*) > 1, 's','')), '.') as THETEXT
   FROM OCCUPATIONS  group by  OCCUPATION
)
ORDER by THETEXT ASC;
</code>```

Body:
Generate the following two result sets:

1). Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

2). Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

There are total [occupation_count] [occupation]s.

Table Name: Occupations

Total Columns: Two = 'Name' and 'Occupation', demo table is shown below:

Sample Output:

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are total 2 doctors.
There are total 2 singers.
There are total 3 actors.
There are total 3 professors.

My Approach:

(SELECT NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')'
    FROM OCCUPATIONS ORDER BY NAME)
UNION ALL
(SELECT COUNT(*) FROM OCCUPATIONS GROUP BY OCCUPATION ORDER BY ASEC);

Error:

ERROR 1222 (21000) at line 1:
    The used SELECT statements have a different number of columns

Thank You!


问:
Wildfly Security Manager : Permission failed for javax.management.MBeanPermission
I have My JBOSS Wildfly10 set up. I am enabling SECMGR flag in standlone.conf.bat file to true for enabling java security manager and as my war is deployed in wildfy 10 ,I am giving following permission set in standalone.xml as below and getting following error:

14:49:56,804 INFO  [stdout] (ServerService Thread Pool -- 58)
  2017-03-28 14:49:56,804 ServerService Thread Pool -- 58 ERROR Could
  not unregister MBeans for org.apac
  he.logging.log4j2:type=2483b420,component=Loggers,name=*,subtype=RingBuffer
  java.security.AccessControlException: WFSM000001: Permission check
  failed (permission "( "javax.management.MBeanPermission" "-#-[-]"
  "queryNames")" in code source
  "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySample.war/WEB-INF/lib/log4j-core-2.5.
  jar )" of "null")

My Standalone.xml configuration is as below so please can anyone help me out here where I am doing wrong ?

```<code> <subsystem xmlns="urn:jboss:domain:security-manager:1.0">
                <deployment-permissions>
                    <minimum-set>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="java.util.PropertyPermission" name="*" actions="read"/>
                        <permission class="java.lang.RuntimePermission" name="createClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="getClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="javax.management.MBeanServerPermission" name="createMBeanServer"/>
                        <permission class="java.lang.reflect.ReflectPermission" name="suppressAccessChecks"/>
                        <permission class="javax.management.MBeanPermission" name="registerMBean"/>
                        <permission class="javax.management.MBeanPermission" name="queryNames"/>
                    </minimum-set>
                </deployment-permissions>
            </subsystem>
</code>```

答: Hi James thanks for reply, I am little new to java security management as you said I have corrected the permission and referred the MBeanPermission link , It was helpful for me and that issue got fixed.</p>

Body:
I have My JBOSS Wildfly10 set up. I am enabling SECMGR flag in standlone.conf.bat file to true for enabling java security manager and as my war is deployed in wildfy 10 ,I am giving following permission set in standalone.xml as below and getting following error:

14:49:56,804 INFO  [stdout] (ServerService Thread Pool -- 58)
  2017-03-28 14:49:56,804 ServerService Thread Pool -- 58 ERROR Could
  not unregister MBeans for org.apac
  he.logging.log4j2:type=2483b420,component=Loggers,name=*,subtype=RingBuffer
  java.security.AccessControlException: WFSM000001: Permission check
  failed (permission "( "javax.management.MBeanPermission" "-#-[-]"
  "queryNames")" in code source
  "(vfs:/C:/wildfly-10.0.0.Final/standalone/deployments/mySample.war/WEB-INF/lib/log4j-core-2.5.
  jar )" of "null")

My Standalone.xml configuration is as below so please can anyone help me out here where I am doing wrong ?

 <subsystem xmlns="urn:jboss:domain:security-manager:1.0">
                <deployment-permissions>
                    <minimum-set>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="java.util.PropertyPermission" name="*" actions="read"/>
                        <permission class="java.lang.RuntimePermission" name="createClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="getClassLoader"/>
                        <permission class="java.lang.RuntimePermission" name="shutdownHooks"/>
                        <permission class="javax.management.MBeanServerPermission" name="createMBeanServer"/>
                        <permission class="java.lang.reflect.ReflectPermission" name="suppressAccessChecks"/>
                        <permission class="javax.management.MBeanPermission" name="registerMBean"/>
                        <permission class="javax.management.MBeanPermission" name="queryNames"/>
                    </minimum-set>
                </deployment-permissions>
            </subsystem>


问:
Alternative to Year function in Oracle
I have been using the SQL query below in Access, which previosuly worked until I moved my data to Oracle :-

```<code>SELECT Count(*) AS xCount
FROM tblQuotesNew AS t1
WHERE (((t1.sales_route)='Sales Mailbox') AND ((t1.DATE_SENT_TO_REGISTRATIONS)=Year(Date())));
</code>```

This now produces an inconsistent datatypes error is Access.

How should I adjust my query so that it will execute in Access?

答:
You can use a normal query (not a pass-through) in Access:</p>

```<code>SELECT
    Count(*) AS xCount
FROM
    tblQuotesNew AS t1
WHERE
    t1.sales_route='Sales Mailbox'
    AND
    (t1.DATE_SENT_TO_REGISTRATIONS Between
        DateSerial(Year(Date()), 1, 1) And
        DateSerial(Year(Date()), 12, 31));
</code>```

Title: Alternative to Year function in Oracle

Body:
I have been using the SQL query below in Access, which previosuly worked until I moved my data to Oracle :-

SELECT Count(*) AS xCount
FROM tblQuotesNew AS t1
WHERE (((t1.sales_route)='Sales Mailbox') AND ((t1.DATE_SENT_TO_REGISTRATIONS)=Year(Date())));

This now produces an inconsistent datatypes error is Access.

How should I adjust my query so that it will execute in Access?

Body:
You can use a normal query (not a pass-through) in Access:

SELECT
    Count(*) AS xCount
FROM
    tblQuotesNew AS t1
WHERE
    t1.sales_route='Sales Mailbox'
    AND
    (t1.DATE_SENT_TO_REGISTRATIONS Between
        DateSerial(Year(Date()), 1, 1) And
        DateSerial(Year(Date()), 12, 31));


问:
Cannot set facebook profile picture to an Imageview
I have a problem when I am trying to retrieve the Facebook profile picture of a person through his/her user ID.

The user ID that i get I then try to set it up using a FacebookProfilePictureView which sets up until I put it into a table which then becomes null and shows me a blank space.

The same is the case with ImageView. When I try to set the ImageView using a Bitmap it just doesnt return anything, shows me a blank space whatever I do. I have tried around 3-4 links of SO that have implemented different functions to solve this problem but this just doesnt work for me.

What is really happening in my code ...

First, when I login through facebook, it saves my name, my userID and some other data and stores it into a PHP database. This happens in the HomePage of my app. Then when I move to another page where it retrieves the same link from the same PHP database and tries to set up the ImageView using this ID.

For some reason, this method always returns null no matter what I do. Also, if it helps, the URL which I recieve is of this format:

```<code>https:\/\/fb-s-d-a.akamaihd.net\/h-ak-xpt1\/v\/t1.0-1\/p50x50\/
</code>```

Any help would be appreciated ... :)

答:
The link has some weirdly placed forward brackets, did you try changing them to a backslash?

```<code>https://fb-s-d-a.akamaihd.net/h-ak-xpt1/v/t1.0-1/p50x50/
</code>```

The forward brackets are removed in the above link. What our browser does is that it auromatically detects this forward slash thing and it converts it to the type I have shown above.

Try it out it might work

Body:
I have a problem when I am trying to retrieve the Facebook profile picture of a person through his/her user ID.

The user ID that i get I then try to set it up using a FacebookProfilePictureView which sets up until I put it into a table which then becomes null and shows me a blank space.

The same is the case with ImageView. When I try to set the ImageView using a Bitmap it just doesnt return anything, shows me a blank space whatever I do. I have tried around 3-4 links of SO that have implemented different functions to solve this problem but this just doesnt work for me.

What is really happening in my code ...

First, when I login through facebook, it saves my name, my userID and some other data and stores it into a PHP database. This happens in the HomePage of my app. Then when I move to another page where it retrieves the same link from the same PHP database and tries to set up the ImageView using this ID.

For some reason, this method always returns null no matter what I do. Also, if it helps, the URL which I recieve is of this format:

https:\/\/fb-s-d-a.akamaihd.net\/h-ak-xpt1\/v\/t1.0-1\/p50x50\/

Any help would be appreciated ... :)

Body:
The link has some weirdly placed forward brackets, did you try changing them to a backslash?

https://fb-s-d-a.akamaihd.net/h-ak-xpt1/v/t1.0-1/p50x50/

The forward brackets are removed in the above link. What our browser does is that it auromatically detects this forward slash thing and it converts it to the type I have shown above.

Try it out it might work


问:
Cannot login with Facebook with play framework, silhouette, and satellizer
I was doing just fine this morning when I realized that the facebook login wasn't working anymore in my app. As I mentioned I'm using play framework with silhouette version 2.0-RC1.

This is the problem:

```<code>[Silhouette][facebook] Cannot build OAuth2Info because of invalid response format  : {"access_token":"EAAE2YyQkAUUBANAfoUfhdG8jrRfJnhrgZCaZB5FsZAO1G5Jq0ITTfZA6coj4g0HuUC48JToHCnZCFx8r9Q3JZCulzt6SaEcRqKrxNealsBldH4dpzJpK4oeblZAmxjq9Rjzl2rO3IKPUwllWAv5vEz33cGc4XeqLSgZD","token_type":"bearer","expires_in":5183717}
</code>```

The problem is that the Json response for the authentication doesn't have the correct format as OAuth2Info expects, which is weird because we never touch the authentication mecanism and I'm woried because it could be a library version problem and update silhouette is not an option right now... Is somebody having this problem and found the solution? Please help me with this guys... Thanks a lot.

答:
We have to create a custom implementation of the FacebookProvider in order to process the new facebook's answer. Here it is</p>

```<code>    import com.mohiva.play.silhouette.api.LoginInfo
    import com.mohiva.play.silhouette.api.exceptions.AuthenticationException
    import com.mohiva.play.silhouette.api.util.HTTPLayer
    import com.mohiva.play.silhouette.impl.exceptions.ProfileRetrievalException
    import com.mohiva.play.silhouette.impl.providers.OAuth2Provider._
    import com.mohiva.play.silhouette.impl.providers._
    import com.mohiva.play.silhouette.impl.providers.oauth2.{FacebookProfileBuilder, FacebookProvider}
    import com.mohiva.play.silhouette.impl.providers.oauth2.FacebookProvider._
    import play.api.libs.concurrent.Execution.Implicits._
    import play.api.libs.json.{ JsObject, JsValue }
    import play.api.libs.ws.WSResponse
    import play.api.libs.json._

    import scala.concurrent.Future
    import scala.util.{ Failure, Success, Try }

    /**
     * A Facebook OAuth2 Provider.
     *
     * @param httpLayer The HTTP layer implementation.
     * @param stateProvider The state provider implementation.
     * @param settings The provider settings.
     *
     * @see https://developers.facebook.com/tools/explorer
     * @see https://developers.facebook.com/docs/graph-api/reference/user
     * @see https://developers.facebook.com/docs/facebook-login/access-tokens
     */
    abstract class FacebookProvider(httpLayer: HTTPLayer, stateProvider: OAuth2StateProvider, settings: OAuth2Settings)
      extends OAuth2Provider(httpLayer, stateProvider, settings) {

      /**
       * The content type to parse a profile from.
       */
      type Content = JsValue

      /**
       * Gets the provider ID.
       *
       * @return The provider ID.
       */
      val id = ID

      /**
       * Defines the URLs that are needed to retrieve the profile data.
       */
      protected val urls = Map("api" -> API)

      /**
       * Builds the social profile.
       *
       * @param authInfo The auth info received from the provider.
       * @return On success the build social profile, otherwise a failure.
       */
      protected def buildProfile(authInfo: OAuth2Info): Future[Profile] = {
        httpLayer.url(urls("api").format(authInfo.accessToken)).get().flatMap { response =>
          val json = response.json
          (json \ "error").asOpt[JsObject] match {
            case Some(error) =>
              val errorMsg = (error \ "message").as[String]
              val errorType = (error \ "type").as[String]
              val errorCode = (error \ "code").as[Int]

              throw new ProfileRetrievalException(SpecifiedProfileError.format(id, errorMsg, errorType, errorCode))
            case _ => profileParser.parse(json)
          }
        }
      }

      /**
       * Builds the OAuth2 info from response.
       *
       * @param response The response from the provider.
       * @return The OAuth2 info on success, otherwise a failure.
       */
      override def buildInfo(response: WSResponse): Try[OAuth2Info] = {
        val responseJson = Json.parse(response.body)
        responseJson.validate[OAuth2Info].asEither.fold(
          error => Failure(new AuthenticationException(InvalidInfoFormat.format(id, error))),
          info => Success(info)
        )
      }
    }

    /**
     * The profile parser for the common social profile.
     */
    class FacebookProfileParser extends SocialProfileParser[JsValue, CommonSocialProfile] {

      /**
       * Parses the social profile.
       *
       * @param json The content returned from the provider.
       * @return The social profile from given result.
       */
      def parse(json: JsValue) = Future.successful {
        val userID = (json \ "id").as[String]
        val firstName = (json \ "first_name").asOpt[String]
        val lastName = (json \ "last_name").asOpt[String]
        val fullName = (json \ "name").asOpt[String]
        val avatarURL = (json \ "picture" \ "data" \ "url").asOpt[String]
        val email = (json \ "email").asOpt[String]

        CommonSocialProfile(
          loginInfo = LoginInfo(ID, userID),
          firstName = firstName,
          lastName = lastName,
          fullName = fullName,
          avatarURL = avatarURL,
          email = email)
      }
    }

    /**
     * The profile builder for the common social profile.
     */
    trait FacebookProfileBuilder extends CommonSocialProfileBuilder {
      self: FacebookProvider =>

      /**
       * The profile parser implementation.
       */
      val profileParser = new FacebookProfileParser
    }

    /**
     * The companion object.
     */
    object FacebookWesuraProvider {

      /**
       * The error messages.
       */
      val SpecifiedProfileError = "[Silhouette][%s] Error retrieving profile information. Error message: %s, type: %s, code: %s"

      /**
       * The Facebook constants.
       */
      val ID = "facebook"
      val API = "https://graph.facebook.com/me?fields=name,first_name,last_name,picture,email&return_ssl_resources=1&access_token=%s"

      /**
       * Creates an instance of the provider.
       *
       * @param httpLayer The HTTP layer implementation.
       * @param stateProvider The state provider implementation.
       * @param settings The provider settings.
       * @return An instance of this provider.
       */
      def apply(httpLayer: HTTPL

ayer, stateProvider: OAuth2StateProvider, settings: OAuth2Settings) = {
    new FacebookProvider(httpLayer, stateProvider, settings) with FacebookProfileBuilder
  }
}
</code>```

Body:
I was doing just fine this morning when I realized that the facebook login wasn't working anymore in my app. As I mentioned I'm using play framework with silhouette version 2.0-RC1.

This is the problem:

[Silhouette][facebook] Cannot build OAuth2Info because of invalid response format  : {"access_token":"EAAE2YyQkAUUBANAfoUfhdG8jrRfJnhrgZCaZB5FsZAO1G5Jq0ITTfZA6coj4g0HuUC48JToHCnZCFx8r9Q3JZCulzt6SaEcRqKrxNealsBldH4dpzJpK4oeblZAmxjq9Rjzl2rO3IKPUwllWAv5vEz33cGc4XeqLSgZD","token_type":"bearer","expires_in":5183717}

The problem is that the Json response for the authentication doesn't have the correct format as OAuth2Info expects, which is weird because we never touch the authentication mecanism and I'm woried because it could be a library version problem and update silhouette is not an option right now... Is somebody having this problem and found the solution? Please help me with this guys... Thanks a lot.

Body:
We have to create a custom implementation of the FacebookProvider in order to process the new facebook's answer. Here it is

    import com.mohiva.play.silhouette.api.LoginInfo
    import com.mohiva.play.silhouette.api.exceptions.AuthenticationException
    import com.mohiva.play.silhouette.api.util.HTTPLayer
    import com.mohiva.play.silhouette.impl.exceptions.ProfileRetrievalException
    import com.mohiva.play.silhouette.impl.providers.OAuth2Provider._
    import com.mohiva.play.silhouette.impl.providers._
    import com.mohiva.play.silhouette.impl.providers.oauth2.{FacebookProfileBuilder, FacebookProvider}
    import com.mohiva.play.silhouette.impl.providers.oauth2.FacebookProvider._
    import play.api.libs.concurrent.Execution.Implicits._
    import play.api.libs.json.{ JsObject, JsValue }
    import play.api.libs.ws.WSResponse
    import play.api.libs.json._

    import scala.concurrent.Future
    import scala.util.{ Failure, Success, Try }

    /**
     * A Facebook OAuth2 Provider.
     *
     * @param httpLayer The HTTP layer implementation.
     * @param stateProvider The state provider implementation.
     * @param settings The provider settings.
     *
     * @see https://developers.facebook.com/tools/explorer
     * @see https://developers.facebook.com/docs/graph-api/reference/user
     * @see https://developers.facebook.com/docs/facebook-login/access-tokens
     */
    abstract class FacebookProvider(httpLayer: HTTPLayer, stateProvider: OAuth2StateProvider, settings: OAuth2Settings)
      extends OAuth2Provider(httpLayer, stateProvider, settings) {

      /**
       * The content type to parse a profile from.
       */
      type Content = JsValue

      /**
       * Gets the provider ID.
       *
       * @return The provider ID.
       */
      val id = ID

      /**
       * Defines the URLs that are needed to retrieve the profile data.
       */
      protected val urls = Map("api" -> API)

      /**
       * Builds the social profile.
       *
       * @param authInfo The auth info received from the provider.
       * @return On success the build social profile, otherwise a failure.
       */
      protected def buildProfile(authInfo: OAuth2Info): Future[Profile] = {
        httpLayer.url(urls("api").format(authInfo.accessToken)).get().flatMap { response =>
          val json = response.json
          (json \ "error").asOpt[JsObject] match {
            case Some(error) =>
              val errorMsg = (error \ "message").as[String]
              val errorType = (error \ "type").as[String]
              val errorCode = (error \ "code").as[Int]

              throw new ProfileRetrievalException(SpecifiedProfileError.format(id, errorMsg, errorType, errorCode))
            case _ => profileParser.parse(json)
          }
        }
      }

      /**
       * Builds the OAuth2 info from response.
       *
       * @param response The response from the provider.
       * @return The OAuth2 info on success, otherwise a failure.
       */
      override def buildInfo(response: WSResponse): Try[OAuth2Info] = {
        val responseJson = Json.parse(response.body)
        responseJson.validate[OAuth2Info].asEither.fold(
          error => Failure(new AuthenticationException(InvalidInfoFormat.format(id, error))),
          info => Success(info)
        )
      }
    }

    /**
     * The profile parser for the common social profile.
     */
    class FacebookProfileParser extends SocialProfileParser[JsValue, CommonSocialProfile] {

      /**
       * Parses the social profile.
       *
       * @param json The content returned from the provider.
       * @return The social profile from given result.
       */
      def parse(json: JsValue) = Future.successful {
        val userID = (json \ "id").as[String]
        val firstName = (json \ "first_name").asOpt[String]
        val lastName = (json \ "last_name").asOpt[String]
        val fullName = (json \ "name").asOpt[String]
        val avatarURL = (json \ "picture" \ "data" \ "url").asOpt[String]
        val email = (json \ "email").asOpt[String]

        CommonSocialProfile(
          loginInfo = LoginInfo(ID, userID),
          firstName = firstName,
          lastName = lastName,
          fullName = fullName,
          avatarURL = avatarURL,
          email = email)
      }
    }

    /**
     * The profile builder for the common social profile.
     */
    trait FacebookProfileBuilder extends CommonSocialProfileBuilder {
      self: FacebookProvider =>

      /**
       * The profile parser implementation.
       */
      val profileParser = new FacebookProfileParser
    }

    /**
     * The companion object.
     */
    object FacebookWesuraProvider {

      /**
       * The error messages.
       */
      val SpecifiedProfileError = "[Silhouette][%s] Error retrieving profile information. Error message: %s, type: %s, code: %s"

      /**
       * The Facebook constants.
       */
      val ID = "facebook"
      val API = "https://graph.facebook.com/me?fields=name,first_name,last_name,picture,email&return_ssl_resources=1&access_token=%s"

      /**
       * Creates an instance of the provider.
       *
       * @param httpLayer The HTTP layer implementation.
       * @param stateProvider The state provider implementation.
       * @param settings The provider settings.
       * @return An instance of this provider.
       */
      def apply(httpLayer: HTTPL

ayer, stateProvider: OAuth2StateProvider, settings: OAuth2Settings) = {
    new FacebookProvider(httpLayer, stateProvider, settings) with FacebookProfileBuilder
  }
}


问:
How to query records in multiple time zones using their own time zones with Rails or raw SQL
Here's my issue: I have records stored in my DB with UTC time zones but! I need to query those records and return everything within a day according the record's own time zone, regardless of its UTC date.

Example?

Let's say I have a record uploaded at 00:30 on a Tuesday in America/Denver and I have a bunch of records uploaded at 00:30 on a Monday in America/Los_Angeles.

Alright, now, when I query for records made on Monday, the whole day, I'm getting that Tuesday record because 00:30 in America/Denver is technically on Monday in America/Los_Angeles. I'm running raw SQL to try and solve this in my Rails project, but... no dice.

Any help on this?

```<code>SELECT
DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone) as uploaded_at,
count(DISTINCT photos.id)
FROM photos, areas
WHERE photos.category IN ('landscape', 'family', 'animal', 'saucy', 'feet', 'portrait')
AND photos.uploaded_at
BETWEEN '2017-03-27 00:00:00 UTC' AND '2017-04-02 23:59:59 UTC'
GROUP BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone)
ORDER BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone);
</code>```

答:
Use the in_time_zone method.  Docs here: http://apidock.com/rails/DateTime/in_time_zone

Ex. usage:

```<code>t = foo.start_time
=> 2000-01-01 14:20:00 UTC
t.zone
=> "UTC"
t.in_time_zone("America/New_York")
=> Sat, 01 Jan 2000 09:20:00 EST -05:00
</code>```

You can use this to convert the times based on their corresponding timezone thus giving you the proper range to query the UTC records.

Body:
Here's my issue: I have records stored in my DB with UTC time zones but! I need to query those records and return everything within a day according the record's own time zone, regardless of its UTC date.

Example?

Let's say I have a record uploaded at 00:30 on a Tuesday in America/Denver and I have a bunch of records uploaded at 00:30 on a Monday in America/Los_Angeles.

Alright, now, when I query for records made on Monday, the whole day, I'm getting that Tuesday record because 00:30 in America/Denver is technically on Monday in America/Los_Angeles. I'm running raw SQL to try and solve this in my Rails project, but... no dice.

Any help on this?

SELECT
DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone) as uploaded_at,
count(DISTINCT photos.id)
FROM photos, areas
WHERE photos.category IN ('landscape', 'family', 'animal', 'saucy', 'feet', 'portrait')
AND photos.uploaded_at
BETWEEN '2017-03-27 00:00:00 UTC' AND '2017-04-02 23:59:59 UTC'
GROUP BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone)
ORDER BY DATE(uploaded_at AT TIME ZONE 'UTC' AT TIME ZONE areas.iso_time_zone);

Body:
Use the in_time_zone method.  Docs here: http://apidock.com/rails/DateTime/in_time_zone

Ex. usage:

t = foo.start_time
=> 2000-01-01 14:20:00 UTC
t.zone
=> "UTC"
t.in_time_zone("America/New_York")
=> Sat, 01 Jan 2000 09:20:00 EST -05:00

You can use this to convert the times based on their corresponding timezone thus giving you the proper range to query the UTC records.


问:
Jupyter Notebook with Apache Spark (Kernel Error)
My objectif is to use Jupyter Notebook (IPython) with Apache Spark. I'm using Apache Toree to do this. I was setting environment variable for SPARK_HOME and configuring Apache Toree installation with Jupyter. Everything seems fine.

When I run the below command, a juypter browser is opened ipython notebook --profile=pyspark

When I choose Apache Toree - PySpark in the drop-down menu, I can't code in my notebook and I have this view (Python 2 is OK):

The red button gives :

What's wrong ? Help please ?

答:
Not really an answer, but if you're not hooked on toree and just need a local spark for learning and experimenting, you could download a copy of spark, unzip it and use this in the beginning of your notebook:</p>

```<code>import os
import sys

os.environ['SPARK_HOME']="<path where you have extracted the spark file>"
sys.path.append( os.path.join(os.environ['SPARK_HOME'], 'python') )
sys.path.append( os.path.join(os.environ['SPARK_HOME'], 'bin') )
sys.path.append( os.path.join(os.environ['SPARK_HOME'], 'python/lib/py4j-0.10.4-src.zip') )

from pyspark import SparkContext,SparkConf
from pyspark.sql import SQLContext, Row
import pyspark.sql.functions as sql

sc = SparkContext()
sqlContext = SQLContext(sc)
print sc.version
</code>```

Body:
Not really an answer, but if you're not hooked on toree and just need a local spark for learning and experimenting, you could download a copy of spark, unzip it and use this in the beginning of your notebook:

import os
import sys

os.environ['SPARK_HOME']="<path where you have extracted the spark file>"
sys.path.append( os.path.join(os.environ['SPARK_HOME'], 'python') )
sys.path.append( os.path.join(os.environ['SPARK_HOME'], 'bin') )
sys.path.append( os.path.join(os.environ['SPARK_HOME'], 'python/lib/py4j-0.10.4-src.zip') )

from pyspark import SparkContext,SparkConf
from pyspark.sql import SQLContext, Row
import pyspark.sql.functions as sql

sc = SparkContext()
sqlContext = SQLContext(sc)
print sc.version


问:
Android instrumented test infinitely running
I've written up some instrumented tests, and the assertions are passing - however regardless of what configuration they are run in, the run never terminates/ends - I have to manually terminate the run - which is not optimal for a CI setup.

I have tried running the below code in the following run configurations:

Run all tests in the test class - in this instance the run does not progress onto the second test after running the first

Run all tests in test package - in this instance the run does not progress onto the second test after running the first, but all other instrumented tests in other classes succeed.

Run both tests in the test class separately

Even if I take out my test code and put in incredibly simple tests (as I have done below) the code execution does not complete.

```<code>public class TestClass {

    private MainActivity mainActivity;
    private MyScreen myScreenInstance;

    @Rule
    public ActivityTestRule mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Before
    public void setUp() throws FileNotFoundException {
        mainActivity = (MainActivity) mActivityRule.getActivity();
    }

    @Test
    public void test_1() throws FileNotFoundException {
        assertEquals(1,2);
    }

    @Test
    public void test_2() throws FileNotFoundException {
        assertEquals(2,2);
    }

}
</code>```

For context I'm trying to test that a touch behaviour in a class I have written on top of a simple game engine written by a lecturer, the test code and assertions I have written all work - but the problem is that the run does not complete.

Do I have to have some sort of 'teardown' method to destroy the ActivityTestRule? What can I do to ensure this run completes correctly?

Interestingly these very simple assertions successfully run on API 25 on a Nexus 7 emulator, however when run in a Nexus 5 emulator running API 23 the tests do not complete as described above.

Further information:

running the tests slowly through with the debugger, stepping through steps - they all pass as they should

adding a Thread.sleep(1000) to the @After (tearDown) method, the described issue stops occurring. However this does not resolve this issue as it our run still times out in firebase test lab (CI)

Below is a picture of a run I started, and then 5 minutes later it's hung. It should have completed 2 tests in < 2 seconds.

答:
I have now resolved this issue, ordinarily a developer would be adding a onView call, however due to the nature of the framework i am working in I was not doing so. I have added

```<code>onView(withId(R.id.activity_fragment_id)).perform(click());
</code>```

to the setup, to just click the main area that the game runs within and now tests pass.

Body:
I've written up some instrumented tests, and the assertions are passing - however regardless of what configuration they are run in, the run never terminates/ends - I have to manually terminate the run - which is not optimal for a CI setup.

I have tried running the below code in the following run configurations:

Run all tests in the test class - in this instance the run does not progress onto the second test after running the first

Run all tests in test package - in this instance the run does not progress onto the second test after running the first, but all other instrumented tests in other classes succeed.

Run both tests in the test class separately

Even if I take out my test code and put in incredibly simple tests (as I have done below) the code execution does not complete.

public class TestClass {

    private MainActivity mainActivity;
    private MyScreen myScreenInstance;

    @Rule
    public ActivityTestRule mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Before
    public void setUp() throws FileNotFoundException {
        mainActivity = (MainActivity) mActivityRule.getActivity();
    }

    @Test
    public void test_1() throws FileNotFoundException {
        assertEquals(1,2);
    }

    @Test
    public void test_2() throws FileNotFoundException {
        assertEquals(2,2);
    }

}

For context I'm trying to test that a touch behaviour in a class I have written on top of a simple game engine written by a lecturer, the test code and assertions I have written all work - but the problem is that the run does not complete.

Do I have to have some sort of 'teardown' method to destroy the ActivityTestRule? What can I do to ensure this run completes correctly?

Interestingly these very simple assertions successfully run on API 25 on a Nexus 7 emulator, however when run in a Nexus 5 emulator running API 23 the tests do not complete as described above.

Further information:

running the tests slowly through with the debugger, stepping through steps - they all pass as they should

adding a Thread.sleep(1000) to the @After (tearDown) method, the described issue stops occurring. However this does not resolve this issue as it our run still times out in firebase test lab (CI)

Below is a picture of a run I started, and then 5 minutes later it's hung. It should have completed 2 tests in < 2 seconds.

Body:
I have now resolved this issue, ordinarily a developer would be adding a onView call, however due to the nature of the framework i am working in I was not doing so. I have added

onView(withId(R.id.activity_fragment_id)).perform(click());

to the setup, to just click the main area that the game runs within and now tests pass.


问:
JointJS - handle links (join, delete)

When connecting the ports two ports, I want to get the ID of port1, and ID of port2. For instance, I connect Yes from left side, to No on other side, and I want to get ID of Yes Port, and ID of No Port. So far I have tried this:

```<code>this.graph.on('add', function(cell, collection, opt) {
 if (cell.isLink()) {
    console.log(cell.id);
 }
});
</code>```

How ever, I only get the ID of first line (not port) I clicked on. I would also like to get the same output upon removing the line.

```<code>    this.graph.on('remove', function(cell, collection, opt) {
        if (cell.isLink()) {
            alert('link removed;');
        }
    });
</code>```

答:
Using graph's "add" event won't help you because if the link is draggable, when you add it you'll only have the source id and port but not the target's id and port.

The events "change:source" and "change:target" won't be called when you remove a link either and they also have the disadvantage of being called several times when dragging the link around.

I'd suggest you use the paper "link:connect" event and graph's "remove" event as follows:

```<code>this.paper.on("link:connect", function(linkView, evt, cellView, magnet, arrowhead) {
    logSourceTargetPorts(linkView.model);
}

this.graph.on("remove", function(cell, collection, opt) {
    if (cell.isLink()) {
        logSourceTargetPorts(cell);
    }
}

function logSourceTargetPorts(link) {
    var source = link.get('source');
    var target = link.get('target');
    if(source.port && target.port) {
        console.log("source and target ports: ", source.port, target.port);
    }
}
</code>```

There's also the paper "link:disconnect" event that has the same signature as "link:connect" in case you also want to do something when the link is disconnected, not only removed.

Title: JointJS - handle links (join, delete)

Body:
When connecting the ports two ports, I want to get the ID of port1, and ID of port2. For instance, I connect Yes from left side, to No on other side, and I want to get ID of Yes Port, and ID of No Port. So far I have tried this:

this.graph.on('add', function(cell, collection, opt) {
 if (cell.isLink()) {
    console.log(cell.id);
 }
});

How ever, I only get the ID of first line (not port) I clicked on. I would also like to get the same output upon removing the line.

    this.graph.on('remove', function(cell, collection, opt) {
        if (cell.isLink()) {
            alert('link removed;');
        }
    });

Body:
Using graph's "add" event won't help you because if the link is draggable, when you add it you'll only have the source id and port but not the target's id and port.

The events "change:source" and "change:target" won't be called when you remove a link either and they also have the disadvantage of being called several times when dragging the link around.

I'd suggest you use the paper "link:connect" event and graph's "remove" event as follows:

this.paper.on("link:connect", function(linkView, evt, cellView, magnet, arrowhead) {
    logSourceTargetPorts(linkView.model);
}

this.graph.on("remove", function(cell, collection, opt) {
    if (cell.isLink()) {
        logSourceTargetPorts(cell);
    }
}

function logSourceTargetPorts(link) {
    var source = link.get('source');
    var target = link.get('target');
    if(source.port && target.port) {
        console.log("source and target ports: ", source.port, target.port);
    }
}

There's also the paper "link:disconnect" event that has the same signature as "link:connect" in case you also want to do something when the link is disconnected, not only removed.


问:
Windows could not start the Apache2 on Local Computer - problem
During the installation of Apache2 I got the following message into cmd window:

Installing the Apache2.2 service The
  Apache2.2 service is successfully
  installed. Testing httpd.conf....

Errors reported here must be corrected
  before the service can be started.
  httpd.exe: Could not reliably
  determine the server's fully qualified
  domain name , using 192.168.1.3 for
  ServerName (OS 10048)Only one usage of
  each socket address (protocol/network
  address/port) is normally permitted.
  : make_sock: could not bind to address
  0.0.0.0:80 no listening sockets available, shutting down Unable to
  open logs Note the errors or messages
  above, and press the  key to
  exit.  24...

and after installing everything look fine, but it isn't. If I try to start service I got the following message:

Windows could not start the Apache2 on
  Local Computer.  For more information,
  review the System Event Log.  If this
  is a non-Micorsoft service, contact
  the service vendor, and refer to
  service-specific error code 1.

Apach2 version is 2.2.9

Does anyone have the same problem, or could help me.

答:
I had the same problem. I checked netstat, other processes running, firewall and changed httpd.conf, stopped antivirus, But all my efforts were in vain. :(

So finally the solution was to stop the IIS. And it worked :)

I guess IIS and apache cant work together. If anybody know any work around let us know.

OwnerDisplayName: vaske

ContentLicense: CC BY-SA 2.5


问:
Social networking site: anonymous first, claim later
One of the great features of StackOverflow is that you can ask a question or answer a question without signing up, then claim your activity later. It's perfect because you engage people right away without any barriers to entry.

Are there any Social Networking frameworks out there in any language with any data backend (relational or non-relational) that support this behavior along with OpenID?

答:
OSQA.net - Python & Django

Shapado - Ruby on Rails

Question2Answer - PHP


问:
Bootstrap panels - same outer height and same panel-body height
I need to have three Bootsrap panels (.panel) within a row (.row) all the same height, regardless of how much content is in each of them. I was able to set the outer height of each .panel using the jquery.matchHeight.js library (https://github.com/liabru/jquery-match-height). However, I've been unable to get the inner height the same (height of the .panel-body divs). I tried setting the height of .panel and .panel-body to 100% but this caused the background-color of the .panel-body divs to extend past the height of the containing .row.

Please take a look at the jsfiddle I created to see the problem in action: https://jsfiddle.net/vpdq2ugb/21/

```<code><div class="row">

  <div class="col-md-3 site-component" style="background-color: pink;">

    <div class="panel panel-default">
      <div class="panel-heading" style="background-color: rgba(240,90,40,0.8);">Panel 1</div>
      <div class="panel-body" style="background-color: rgba(240,90,40,0.2);">
        sdf sjdf jsdj g egjjweg
      </div>
    </div>

  </div>

  <div class="col-md-3 site-component" style="background-color: pink;">

    <div class="panel panel-default">
      <div class="panel-heading" style="background-color: rgba(247,147,29,0.8);">Panel 2</div>
      <div class="panel-body" style="background-color: rgba(247,147,29,0.2);">
        sdf sjdf jsdj g egjjweg sjdgjsg ie wengieg jskdkg e gjwe jg wefmwegjw eg wjegjwegjwjg kd
        fdsljg e rgi re vmeb,enb eb ejrke gmer mgeirg s gneirg er gmwefi3 igr mgierg mw egiewrg
      </div>
    </div>

  </div>

  <div class="col-md-3 site-component" style="background-color: pink;">

    <div class="panel panel-default">
      <div class="panel-heading" style="background-color: rgba(55,208,0,0.8);">Panel 3</div>
      <div class="panel-body" style="background-color: rgba(55,208,0,0.2);">
        sdf sjdf jsdj g egjjweg sjdgjsg ie wengirgeg wrey yu yubrb  zdxc xev
      </div>
    </div>

  </div>

</div>
</code>```

Please note: I need this to be responsive. I only want the .panels to be vertical when the screen size is wide enough.

Also, I know there are many questions already posted that are very similar; however, none of the previous posts address the problem of the inner height (height of the .panel-body divs).

Thank you in advance!

答:
Try using the pink background div as a wrapper around all three panels, not separate backgrounds. Then do overflow:auto. This wrapper must have a defined height. Style the panel-body, panel and div with 100% height.

Here is a bootply: http://www.bootply.com/svJMjYtLso

Body:
I need to have three Bootsrap panels (.panel) within a row (.row) all the same height, regardless of how much content is in each of them. I was able to set the outer height of each .panel using the jquery.matchHeight.js library (https://github.com/liabru/jquery-match-height). However, I've been unable to get the inner height the same (height of the .panel-body divs). I tried setting the height of .panel and .panel-body to 100% but this caused the background-color of the .panel-body divs to extend past the height of the containing .row.

Please take a look at the jsfiddle I created to see the problem in action: https://jsfiddle.net/vpdq2ugb/21/

Panel 1

        sdf sjdf jsdj g egjjweg

Panel 2

        sdf sjdf jsdj g egjjweg sjdgjsg ie wengieg jskdkg e gjwe jg wefmwegjw eg wjegjwegjwjg kd
        fdsljg e rgi re vmeb,enb eb ejrke gmer mgeirg s gneirg er gmwefi3 igr mgierg mw egiewrg

Panel 3

        sdf sjdf jsdj g egjjweg sjdgjsg ie wengirgeg wrey yu yubrb  zdxc xev

Please note: I need this to be responsive. I only want the .panels to be vertical when the screen size is wide enough.

Also, I know there are many questions already posted that are very similar; however, none of the previous posts address the problem of the inner height (height of the .panel-body divs).

Thank you in advance!


问:
Wordpress - Facebook SDK - Comments Plugin Loads in Staging but not in Production
We are trying to use the Facebook SDK to engage users. We have a simple Facebook App on our blog that allows users to "sign in" with Facebook as well as "Comment" on articles etc. On our staging site, loading the Facebook SDK asynchronously, we have this functionality working normally, users can sign in with Facebook and Comment on posts. However, on the production site which is using the exact same Wordpress theme files and Wordpress App ID, the Comments only load SOMETIMES (1/10 times). Here is the code in "Header.php" that I am using to access the Facebook SDK in both the staging and production. Much of my code was taken from the Facebook SDK "Sign in with Facebook" Instructions. As you can see, I have already tried using FB.XFBML.parse(); to reload the XFBML but it doesn't make any differnce. Any help anyone can give me as to why the Comments plugin loads in Staging and Production would be much appreciated.

```<code><script>window.isSigned = 0;
    ////////////FB LOGIN STUFF////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response.status);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // You are logged into your app and Facebook.
      document.getElementById('fbinfoz').innerHTML = '1'
      testAPI();

  } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('fbinfoz').innerHTML = '0'
      /*document.getElementById('status').innerHTML = 'Please log ' +
      'into this app.';*/

  } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('fbinfoz').innerHTML = '0'
      /*document.getElementById('status').innerHTML = 'Please log ' +
      'into Facebook.';*/

  }
}

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
        appId      : 'XXXXXXXXXXXXXX',
    cookie     : true,  // enable cookies to allow the server to access
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.8' // use graph api version 2.8
});

  // Now that we've initialized the JavaScript SDK, we call
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  //
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  //
  // These three cases are handled in the callback function.

  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
};

  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    jQuery(document).ready(function(){
        console.log('Welcome!  Fetching your information.... ');
        FB.api('/me?fields=id,name,first_name,last_name,email,age_range,birthday,gender,locale,timezone,picture', function(response) {
            console.log('Successful login for: ' + response.name);
            var fbname = response.name;
            console.log('First Name: ' + response.first_name);
            var fbfname = response.first_name;
            console.log('Last Name: ' + response.last_name);
            var fblname = response.last_name;
            console.log('Email: ' + response.email);
            var fbemail = response.email;
            console.log('FB ID: ' + response.id);
            var fbid = response.id;
            console.log('Age Range Min: ' + response.age_range.min);
            var fbagerange = response.age_range.min;
            console.log('Birthday: ' + response.birthday);
            console.log('Gender: ' + response.gender);
            var fbgender = response.gender;
            console.log('Locale: ' + response.locale);
            var fblocale = response.locale;
            console.log('Timezone: ' + response.timezone);
            var fbtimezone = response.timezone;
            console.log('Picture: http://graph.facebook.com/' + response.id +'/picture?type=large');
            var fbpicture = 'Picture: http://graph.facebook.com/' + response.id +'/picture?type=large';

        /* document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';*/
    });
});
}
</script>
</code>```

And the Comments Section:

```<code><script>
  FB.XFBML.parse();
</script>
    <div id="facebookCommentz" style="" class="fb-comments" data-width="100%" data-href="<?php echo get_permalink(); ?>" data-numposts="5"></div>
</code>```

Thanks for your help!

答:
I thought I would share what ultimately fixed this problem. Our Staging site and Production site were both using the same Facebook App ID. The Staging site was set up with a .htaccess redirect that forwards all other IPs except ours to the Production site.  We were testing the Facebook Comments plugin on the Staging site by adding Comments to staging pages, but those same live pages on the Production site would not gain the comments. I simply created a new Facebook App with a new App ID and everything works normally.

So, I guess the answer is: It's best to have two different Facebook App ID's for Staging and Production.

Body:
We are trying to use the Facebook SDK to engage users. We have a simple Facebook App on our blog that allows users to "sign in" with Facebook as well as "Comment" on articles etc. On our staging site, loading the Facebook SDK asynchronously, we have this functionality working normally, users can sign in with Facebook and Comment on posts. However, on the production site which is using the exact same Wordpress theme files and Wordpress App ID, the Comments only load SOMETIMES (1/10 times). Here is the code in "Header.php" that I am using to access the Facebook SDK in both the staging and production. Much of my code was taken from the Facebook SDK "Sign in with Facebook" Instructions. As you can see, I have already tried using FB.XFBML.parse(); to reload the XFBML but it doesn't make any differnce. Any help anyone can give me as to why the Comments plugin loads in Staging and Production would be much appreciated.

And the Comments Section:

    <div id="facebookCommentz" style="" class="fb-comments" data-width="100%" data-href="<?php echo get_permalink(); ?>" data-numposts="5">

Thanks for your help!


问:
Create a WebLogic development domain with custom memory
I've been trying to automate the creation of our development environment by combining batch files and WLST, but I am struggling to change the memory WebLogic server will start with.

Currently we are manually changing the memory settings in the <DOMAIN_HOME>/bin/setDomainEnv.cmd script, but this is a workaround. It should be possible to to do it automatically without much effort.

Setting the Domain

The script that sets the Domain in pretty simple:

```<code>set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_45
set MW_HOME=C:\dev\wls1036_dev
set DOMAIN_HOME=C:\dev\domain
cd %MW_HOME%
call configure.cmd
mkdir %DOMAIN_HOME%
cd %DOMAIN_HOME%
%JAVA_HOME%\bin\java.exe -Xmx1024m -XX:MaxPermSize=256m -Dweblogic.management.username=weblogic -Dweblogic.management.password=welcome1 weblogic.Server
</code>```

I've tried to use some variables in this script such as MEM_ARGS, JAVA_OPTIONS, but none of these are forwarded to the final configuration of the domain, later it always starts with 512 heap, and 128 perm, which are not enough.

WLST memory start args

We are using Eclipse, and it does call the startWebLogic.cmd as start script. It is the standard configuration.

I tried to use the following WLST script. It does set the server start arguments, but WebLogic is not using those properties and loads not enough memory.

```<code>edit()
startEdit()
cd('/Servers/myserver/ServerStart/myserver')
cmo.setArguments('-Xmx1024m -XX:MaxPermSize=256m')
activate()
</code>```

Any ideas?

答:
There is no easy way of setting values when executing WebLogic from Eclipse. It'll call the batch script and, at least at current version, does not allow to send dynamic parameters.

We solved it making the setDomainEnv.cmd file part of our versioned configuration:

Copy the setDomainEnv.cmd file to your version control configuration.

Edit whatever you want (memory, etc)

Copy the file like copy custom\setDomainEnv.cmd %DOMAIN_HOME%\bin /y when running your development environment configuration script.

Now every time you configure your development environment memory values will be ready without manual intervention.

You have to reedit your stuff when updating WebLogic, so you don't end up with an outdated component.

Body:
I've been trying to automate the creation of our development environment by combining batch files and WLST, but I am struggling to change the memory WebLogic server will start with.

Currently we are manually changing the memory settings in the <DOMAIN_HOME>/bin/setDomainEnv.cmd script, but this is a workaround. It should be possible to to do it automatically without much effort.

Setting the Domain

The script that sets the Domain in pretty simple:

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_45
set MW_HOME=C:\dev\wls1036_dev
set DOMAIN_HOME=C:\dev\domain
cd %MW_HOME%
call configure.cmd
mkdir %DOMAIN_HOME%
cd %DOMAIN_HOME%
%JAVA_HOME%\bin\java.exe -Xmx1024m -XX:MaxPermSize=256m -Dweblogic.management.username=weblogic -Dweblogic.management.password=welcome1 weblogic.Server

I've tried to use some variables in this script such as MEM_ARGS, JAVA_OPTIONS, but none of these are forwarded to the final configuration of the domain, later it always starts with 512 heap, and 128 perm, which are not enough.

WLST memory start args

We are using Eclipse, and it does call the startWebLogic.cmd as start script. It is the standard configuration.

I tried to use the following WLST script. It does set the server start arguments, but WebLogic is not using those properties and loads not enough memory.

edit()
startEdit()
cd('/Servers/myserver/ServerStart/myserver')
cmo.setArguments('-Xmx1024m -XX:MaxPermSize=256m')
activate()

Any ideas?


问:
Symfony 2.7 Doctrine don't mount query correctly
I'm trying to get the classrooms from a teacher in a many to many relation.

```<code>$classrooms = $this->getDoctrine()->getManager()->getRepository('AppBundle:Classroom')->findBy(array('teachers' => $teacher));
</code>```

But I get the error.
The doctrine is not mounting the join:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2, t0.institution_id AS institution_id_3 FROM classroom t0 WHERE classroom_teacher.teacher_id = ?' with params [4]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'classroom_teacher.teacher_id' in 'where clause'

But I'm using the many to many

Class Classroom

```<code>/**
 * Classroom
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
 */
class Classroom
{
    /**
     * @ORM\ManyToMany(targetEntity="Teacher", cascade={"persist"}, inversedBy="classrooms")
     */
    private $teachers;
    public function __construct()
    {
        $this->teachers         = new ArrayCollection();
    }
}
</code>```

Class Teacher

```<code>/**
 * Teacher
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TeacherRepository")
 */
class Teacher implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\ManyToMany(targetEntity="Classroom", mappedBy="teachers")
     */
    protected $classrooms;
    public function __construct()
    {
        $this->classrooms           = new ArrayCollection();
    }
}
</code>```

What is wrong?

答:
->findBy does not work for many to many relation.

I needed to create an function in the repository:

```<code>class ClassroomRepository extends \Doctrine\ORM\EntityRepository
{
    public function getTeachers($id)
    {
        $qb = $this->createQueryBuilder('c');
        $qb->join('c.teachers', 'ct')
           ->where($qb->expr()->eq('ct.id', $id));
        return $qb->getQuery()->getResult();
    }
}
</code>```

Body:
I'm trying to get the classrooms from a teacher in a many to many relation.

$classrooms = $this->getDoctrine()->getManager()->getRepository('AppBundle:Classroom')->findBy(array('teachers' => $teacher));

But I get the error.
The doctrine is not mounting the join:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2, t0.institution_id AS institution_id_3 FROM classroom t0 WHERE classroom_teacher.teacher_id = ?' with params [4]:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'classroom_teacher.teacher_id' in 'where clause'

But I'm using the many to many

Class Classroom

/**
 * Classroom
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
 */
class Classroom
{
    /**
     * @ORM\ManyToMany(targetEntity="Teacher", cascade={"persist"}, inversedBy="classrooms")
     */
    private $teachers;
    public function __construct()
    {
        $this->teachers         = new ArrayCollection();
    }
}

Class Teacher

/**
 * Teacher
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TeacherRepository")
 */
class Teacher implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\ManyToMany(targetEntity="Classroom", mappedBy="teachers")
     */
    protected $classrooms;
    public function __construct()
    {
        $this->classrooms           = new ArrayCollection();
    }
}

What is wrong?

Body:
->findBy does not work for many to many relation.

I needed to create an function in the repository:

class ClassroomRepository extends \Doctrine\ORM\EntityRepository
{
    public function getTeachers($id)
    {
        $qb = $this->createQueryBuilder('c');
        $qb->join('c.teachers', 'ct')
           ->where($qb->expr()->eq('ct.id', $id));
        return $qb->getQuery()->getResult();
    }
}


问:
What exactly is JSON?
I'm new to the web application domain. I have been watching some hot and eye-catching discussions regarding JSON everywhere.

Can someone briefly explain what JSON is? Do you have links to websites or forums that can help enlighten me about JSON?

答:
From json.org:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Title: What exactly is JSON?


问:
least upper bound of an infinite chain of values in a flat domain
Suppose we have an infinite list of the form

```<code>let l = [undefined,undefined] ++ [1,1..]
</code>```

The key property here is that the list forms a chain in the flat domain Integer. Is there a way in haskell to find the least upper bound of the list l? My naive approach was the following:

```<code>Prelude> import Data.Lub
Prelude Data.Lub> foldr (\x y -> x `lub` y) undefined l
1
</code>```

The problem is that a ghc process continues to use 100% of one of my CPU cores. I am using ghc version 7.10.3.

答: After taking a closer look it is indeed a bug in unamb. Here is a PR to fix it.</p>

Body:
Suppose we have an infinite list of the form

let l = [undefined,undefined] ++ [1,1..]

The key property here is that the list forms a chain in the flat domain Integer. Is there a way in haskell to find the least upper bound of the list l? My naive approach was the following:

Prelude> import Data.Lub
Prelude Data.Lub> foldr (\x y -> x `lub` y) undefined l
1

The problem is that a ghc process continues to use 100% of one of my CPU cores. I am using ghc version 7.10.3.


问:
How do I fix the display of accented characters?
I realize this is an older script, but I would appreciate
any help getting it to work properly. Years ago it worked
fine, but lately it's been acting funny.
Excuse the formatting please....

When I run it in the browser, the french accented characters
do not show properly. But in the text file that it generates,
they show just fine. What is happening here?

Perl version is v5.20.2
My database is MySQL, utf8_unicode_ci
The table is also utf8_unicode_ci

in browser: HÃ©lÃ¨ne Rollan and in file: Hélène Rollan

in browser: Coeur Ã l`Ã©coute and in file: Coeur à l`écoute

```<code>#!/usr/bin/perl --
use utf8;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw (:standard);
$q = new CGI;
use Encode;
use open ':encoding(utf8)';
binmode(STDOUT, ":unix:utf8");

$user = "manager";

require "config.cgi";
&Create_DB_Connection;
$time = time();

sub Create_DB_Connection{
  use DBI;
  $DSN  = "DBI:mysql:$mysql_database:$mysql_hostname";
  $dbh  = DBI->connect($DSN, "$mysql_username", "$mysql_password", {mysql_enable_utf8 => 1}) || die return;
  if ($dbh) { $connected = "YES"; }
  return;
}

sub Do_SQL{
  eval{
    $sth = $dbh->prepare($SQL);
  };
$dbh->do(qq{SET NAMES 'utf8';});
    $sth->execute;
    return ($sth);
}

    &downline;

# Prepare and show tree of affiliates
sub downline {
($sec, $min, $hour, $day, $mon, $year, $dweek, $dyear, $daylight) = localtime(time());
$month = $mon;
$year = $year + 1900;
print $q->header;

print<<EOF;
    <HTML><HEAD><TITLE>Network Summary</TITLE>
<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
</HEAD>
<style type="text/css">
<!--
A:visited {text-decoration: none;}
A:hover {text-decoration: underline;}
A:link {text-decoration: none;}
A:active {text-decoration: none;}
.MEMBERS {font-size: 8pt; text-decoration: none; font-family: Verdana,verdana; color: FF0000;}
-->
</style>
<BODY BGCOLOR="FFFFFF" TEXT="000000" LINK="000080" VLINK="004080">
<center><font size=4 face=arial color=000000><b>Network Summary as of $month/$year</b><br>
<font face=verdana,arial size=1><a href=wmstats_en2.cgi>[return to main page]</a></font></center>
<p>
EOF

$featured_file = "/home/bruce/data/featured.txt";

$SQL="SELECT FIRST_NAME,LAST_NAME,SPONSOR_ID,CO_SPONSOR_ID,ID FROM main_members";
&Do_SQL;
  while ($row = $sth->fetchrow_hashref){
  $info{$row->{'ID'}} = [$row->{'FIRST_NAME'},$row->{'LAST_NAME'},$row->{'SPONSOR_ID'}];
  push @{ $kids{$row->{'CO_SPONSOR_ID'}} }, $row->{'ID'};
}
$kid = "$user";

if (!$kids{$kid}) {
print<<EOF;
<center><b><font size=2 face=arial>There are currently no members in your downline</font></b><font size=4 face=arial color=000000><br><BR>
EOF
} else {
&crunch(1);
}

$o++;

sub crunch {

foreach $kid (@{ $kids{$kid} }) {
$newlevel++;
$payouts{$newlevel}++;
$levels{$newlevel}++;
$total_downline++;
while ($b < $newlevel) { $report .= "    "; $b++; } $b=0;
$report .= "$newlevel: $kid - $info{$kid}[0] $info{$kid}[1] <br>";

# I added this to generate a text file
open (FILE, ">>$featured_file");
flock(FILE, 2);
print FILE "$newlevel: $kid - $info{$kid}[0] $info{$kid}[1] \n";
flock(FILE, 8);
close (FILE);

&crunch($newlevel);
$newlevel--;
delete($info{$kid});
}
}
print<<EOF;
<center><table><tr><td valign=top nowrap>
<font face=verdana size=2>
$report
</td><td valign=top>
<table cellpadding=0><tr>
<td align=right nowrap><font face=verdana,arial size=2><b>Total Downline:<p> </td><td><font face=verdana,arial size=2><b>  $total_downline<p> </td></tr>
EOF

while (!$found_some) { $i++;
if ($levels{$i}) {
print<<EOF;
<tr><td align=right><font face=verdana,arial size=2><b>Level $i:</td><td><font face=verdana,arial size=2><b>  $levels{$i}</td></tr>
EOF
} else { $found_some = 1; }
}

print<<EOF;
</td></tr></table>
<p><font face=verdana size=2><b>
</TD></TR></TABLE></TD></TR></TABLE>
EOF
}
</code>```

答:
After removing the irrelevant bits and fixing the problem, you get the following. (If you had removed the irrelevant bits from the Question itself, it would be easier to see the differences.)

```<code># Specifies the file is encoded using UTF-8.
# This doesn't matter for this program.
use utf8;

# Set the encoding for STDIN, STDOUT and STDERR.
# Set the default encoding for file handles.
use open ':std', ':encoding(utf-8)';

use CGI      qw( );
use DBI      qw( );
use FindBin  qw( $RealBin );
use Template qw( );

my $cgi = CGI->new();

my $dbh = DBI->connect(
   "dbi:mysql:...",
   "...",
   "...",
   {
       RaiseError => 1,
       PrintError => 0,
       PrintWarn  => 1,

       # Decodes strings from the database.
       # Specifying this now performs SET NAMES 'UTF8'
       mysql_enable_utf8 => 1,
   },
);

my $val = $dbh->selectrow_array('SELECT ...');

{
   open(my $fh, '>', '...')
      or die(...);

   print($fh $val);
}

{
    print $cgi->header('text/html; charset=UTF-8');

    my %vars = (
       val => $val,
    );

    my $tt = Template->new({
       ENCODING     => "UTF-8",
       INCLUDE_PATH => "$RealBin/tmpl",
    });

    $tt->process('test.tmpl', \%vars)
       or die($tt->error());
}
</code>```

tmpl/test.tmpl:

```<code><html>
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
</head>
<body>
[% val | html %]
</body>
</html>
</code>```

That is, of course, assuming the data in the database is correct. My request to have this verified has gone unanswered.

Body:
I realize this is an older script, but I would appreciate
any help getting it to work properly. Years ago it worked
fine, but lately it's been acting funny.
Excuse the formatting please....

When I run it in the browser, the french accented characters
do not show properly. But in the text file that it generates,
they show just fine. What is happening here?

Perl version is v5.20.2
My database is MySQL, utf8_unicode_ci
The table is also utf8_unicode_ci

in browser: HÃ©lÃ¨ne Rollan and in file: Hélène Rollan

in browser: Coeur Ã l`Ã©coute and in file: Coeur à l`écoute

#!/usr/bin/perl --
use utf8;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw (:standard);
$q = new CGI;
use Encode;
use open ':encoding(utf8)';
binmode(STDOUT, ":unix:utf8");

$user = "manager";

require "config.cgi";
&Create_DB_Connection;
$time = time();

sub Create_DB_Connection{
  use DBI;
  $DSN  = "DBI:mysql:$mysql_database:$mysql_hostname";
  $dbh  = DBI->connect($DSN, "$mysql_username", "$mysql_password", {mysql_enable_utf8 => 1}) || die return;
  if ($dbh) { $connected = "YES"; }
  return;
}

sub Do_SQL{
  eval{
    $sth = $dbh->prepare($SQL);
  };
$dbh->do(qq{SET NAMES 'utf8';});
    $sth->execute;
    return ($sth);
}

    &downline;

# Prepare and show tree of affiliates
sub downline {
($sec, $min, $hour, $day, $mon, $year, $dweek, $dyear, $daylight) = localtime(time());
$month = $mon;
$year = $year + 1900;
print $q->header;

print<<EOF;
    <TITLE>Network Summary</TITLE>
<meta http-equiv="Content-type" content="text/html;charset=utf-8" />

Network Summary as of $month/$year

[return to main page]

EOF

$featured_file = "/home/bruce/data/featured.txt";

$SQL="SELECT FIRST_NAME,LAST_NAME,SPONSOR_ID,CO_SPONSOR_ID,ID FROM main_members";
&Do_SQL;
  while ($row = $sth->fetchrow_hashref){
  $info{$row->{'ID'}} = [$row->{'FIRST_NAME'},$row->{'LAST_NAME'},$row->{'SPONSOR_ID'}];
  push @{ $kids{$row->{'CO_SPONSOR_ID'}} }, $row->{'ID'};
}
$kid = "$user";

if (!$kids{$kid}) {
print<<EOF;
There are currently no members in your downline

EOF
} else {
&crunch(1);
}

$o++;

sub crunch {

foreach $kid (@{ $kids{$kid} }) {
$newlevel++;
$payouts{$newlevel}++;
$levels{$newlevel}++;
$total_downline++;
while ($b < $newlevel) { $report .= "    "; $b++; } $b=0;
$report .= "$newlevel: $kid - $info{$kid}[0] $info{$kid}[1]
";

# I added this to generate a text file
open (FILE, ">>$featured_file");
flock(FILE, 2);
print FILE "$newlevel: $kid - $info{$kid}[0] $info{$kid}[1] \n";
flock(FILE, 8);
close (FILE);

&crunch($newlevel);
$newlevel--;
delete($info{$kid});
}
}
print<<EOF;

$report

Total Downline:
 	  $total_downline

EOF

while (!$found_some) { $i++;
if ($levels{$i}) {
print<<EOF;

Level $i:	  $levels{$i}

EOF
} else { $found_some = 1; }
}

print<<EOF;

EOF
}

Body:
After removing the irrelevant bits and fixing the problem, you get the following. (If you had removed the irrelevant bits from the Question itself, it would be easier to see the differences.)

# Specifies the file is encoded using UTF-8.
# This doesn't matter for this program.
use utf8;

# Set the encoding for STDIN, STDOUT and STDERR.
# Set the default encoding for file handles.
use open ':std', ':encoding(utf-8)';

use CGI      qw( );
use DBI      qw( );
use FindBin  qw( $RealBin );
use Template qw( );

my $cgi = CGI->new();

my $dbh = DBI->connect(
   "dbi:mysql:...",
   "...",
   "...",
   {
       RaiseError => 1,
       PrintError => 0,
       PrintWarn  => 1,

       # Decodes strings from the database.
       # Specifying this now performs SET NAMES 'UTF8'
       mysql_enable_utf8 => 1,
   },
);

my $val = $dbh->selectrow_array('SELECT ...');

{
   open(my $fh, '>', '...')
      or die(...);

   print($fh $val);
}

{
    print $cgi->header('text/html; charset=UTF-8');

    my %vars = (
       val => $val,
    );

    my $tt = Template->new({
       ENCODING     => "UTF-8",
       INCLUDE_PATH => "$RealBin/tmpl",
    });

    $tt->process('test.tmpl', \%vars)
       or die($tt->error());
}

tmpl/test.tmpl:

<html>
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
</head>
<body>
[% val | html %]
</body>
</html>

That is, of course, assuming the data in the database is correct. My request to have this verified has gone unanswered.


问:
pipeline and placeholder arguments
How is it possible to pass the pipeline placeholder to the second argument in a function? </p>

```<code>defdefmodule CamelCase do
  str = "The_Stealth_Warrior"
  def to_camel_case(str) do
    str
    |> Regex(~r/_/, 'need_to_pass_str_argument_here', "")
    |> String.split(" ")
    |> Enum.map(&(String.capitalize(&1)))
    |> List.to_string
  end
end

ExUnit.start

defmodule TestCamelCase do
  use ExUnit.Case
  import CamelCase, only: [to_camel_case: 1]

  test "to_camel_case" do
    assert to_camel_case("The_Stealth_Warrior") == "TheStealthWarrior"
  end
end

# Error
iex>
  ** (FunctionClauseError) no function clause matching in Regex.replace/4
  (elixir) lib/regex.ex:504: Regex.replace("The_Stealth_Warrior", ~r/\W/, " ", [])
</code>```

答:
To pass the string as the second argument using pipes you can use anonymous function:

```<code>iex(1)> "The_Stealth_Warrior" |> (fn s -> Regex.replace(~r/_/, s, "") end).()
"TheStealthWarrior"
</code>```

But, for this specific case, you can use String.replace/3 instead which accepts a String as the first argument and Regex as the second argument:

```<code>iex(2)> "The_Stealth_Warrior" |> String.replace(~r/_/, "")
"TheStealthWarrior"
</code>```

(\W doesn't match _ so I changed it for demo purposes.)

Title: pipeline and placeholder arguments

Body:
How is it possible to pass the pipeline placeholder to the second argument in a function?

defdefmodule CamelCase do
  str = "The_Stealth_Warrior"
  def to_camel_case(str) do
    str
    |> Regex(~r/_/, 'need_to_pass_str_argument_here', "")
    |> String.split(" ")
    |> Enum.map(&(String.capitalize(&1)))
    |> List.to_string
  end
end

ExUnit.start

defmodule TestCamelCase do
  use ExUnit.Case
  import CamelCase, only: [to_camel_case: 1]

  test "to_camel_case" do
    assert to_camel_case("The_Stealth_Warrior") == "TheStealthWarrior"
  end
end

# Error
iex>
  ** (FunctionClauseError) no function clause matching in Regex.replace/4
  (elixir) lib/regex.ex:504: Regex.replace("The_Stealth_Warrior", ~r/\W/, " ", [])

Body:
To pass the string as the second argument using pipes you can use anonymous function:

iex(1)> "The_Stealth_Warrior" |> (fn s -> Regex.replace(~r/_/, s, "") end).()
"TheStealthWarrior"

But, for this specific case, you can use String.replace/3 instead which accepts a String as the first argument and Regex as the second argument:

iex(2)> "The_Stealth_Warrior" |> String.replace(~r/_/, "")
"TheStealthWarrior"

(\W doesn't match _ so I changed it for demo purposes.)


答:
The problem is that matchHeight runs after the CSS is interpreted by the browser so, panel {height: 100%} is meaningless.

You should run matchHeight() on the panel-body too..

$('.panel-body').matchHeight();

https://jsfiddle.net/rtq64o8d/

Title: Bootstrap panels - same outer height and same panel-body height


问:
Javassist throwing notfound / null pointer in CtMethod.make and getDeclaredMethod using OSGI
javassist is throwing null pointer in CtMethod.make com.company.test is the package of the Activator and Joe

```<code>public class Activator implements BundleActivator {

public Class<?> creerClasse() {
    CtClass toGenerateClass;
    ClassPool pool;
    pool = ClassPool.getDefault();
    try {
        Class c;
        c = Class.forName("com.company.test.Joe");
        pool.appendClassPath(new ClassClassPath(c));
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    pool.importPackage("com.company.test");

    toGenerateClass = pool.makeClass("Test118");

    try {
        toGenerateClass
                .addMethod(CtMethod
                        .make("public void afficher (com.company.test.Joe msg) { System.out.println(msg); } ;",
                                toGenerateClass));
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }

    try {
        return toGenerateClass.toClass();
    } catch (CannotCompileException e) {
        e.printStackTrace();
        return null;
    }
}

public void start(BundleContext context) throws Exception {

        Class<?> genClass = creerClasse();
        Class<?> c = Class.forName("com.company.test.Joe");

        for (Method me : genClass.getDeclaredMethods()) { // test print, ok
            System.out.println(me);
        }

        Method method = genClass.getDeclaredMethod("afficher", c);

        Joe person = new Joe();
        person.setId(17);
        method.invoke(genClass.newInstance(), person);

}

}
</code>```

and when i instansiate pool with pool = new ClassPool(true);
it throws  java.lang.NoClassDefFoundError: com/company/test/Joe in getDeclaredMethod

答:
i solved this issue. In OSGi environment javassit pool should be initialized in this way to find the imported classes and not throwing NullPointerException.

```<code>    pool = new ClassPool(true);
    pool.insertClassPath(new LoaderClassPath(this.getClass()
            .getClassLoader()));
</code>```

and to use the generated class and invoke it's methods it should be created in this way

```<code>toGenerateClass.toClass(this.getClass()
                .getClassLoader(), getClass().getProtectionDomain());
</code>```

don't forget to add <DynamicImport-Package>PACKAGENAME</DynamicImport-Package> to load dynamically the exported packages from the other bundles.

PS: to export a package use <Export-Package>PACKAGENAME</Export-Package>

Body:
javassist is throwing null pointer in CtMethod.make com.company.test is the package of the Activator and Joe

public class Activator implements BundleActivator {

public Class<?> creerClasse() {
    CtClass toGenerateClass;
    ClassPool pool;
    pool = ClassPool.getDefault();
    try {
        Class c;
        c = Class.forName("com.company.test.Joe");
        pool.appendClassPath(new ClassClassPath(c));
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }

    pool.importPackage("com.company.test");

    toGenerateClass = pool.makeClass("Test118");

    try {
        toGenerateClass
                .addMethod(CtMethod
                        .make("public void afficher (com.company.test.Joe msg) { System.out.println(msg); } ;",
                                toGenerateClass));
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }

    try {
        return toGenerateClass.toClass();
    } catch (CannotCompileException e) {
        e.printStackTrace();
        return null;
    }
}

public void start(BundleContext context) throws Exception {

        Class<?> genClass = creerClasse();
        Class<?> c = Class.forName("com.company.test.Joe");

        for (Method me : genClass.getDeclaredMethods()) { // test print, ok
            System.out.println(me);
        }

        Method method = genClass.getDeclaredMethod("afficher", c);

        Joe person = new Joe();
        person.setId(17);
        method.invoke(genClass.newInstance(), person);

}

}

and when i instansiate pool with pool = new ClassPool(true);
it throws  java.lang.NoClassDefFoundError: com/company/test/Joe in getDeclaredMethod

Body:
i solved this issue. In OSGi environment javassit pool should be initialized in this way to find the imported classes and not throwing NullPointerException.

    pool = new ClassPool(true);
    pool.insertClassPath(new LoaderClassPath(this.getClass()
            .getClassLoader()));

and to use the generated class and invoke it's methods it should be created in this way

toGenerateClass.toClass(this.getClass()
                .getClassLoader(), getClass().getProtectionDomain());

don't forget to add <DynamicImport-Package>PACKAGENAME</DynamicImport-Package> to load dynamically the exported packages from the other bundles.

PS: to export a package use <Export-Package>PACKAGENAME</Export-Package>