问:
Best way to convert ArrayList to string
I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String.  In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

```<code>String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets
</code>```

答:
I think you need to check if object converted to string is or is not array,because they are converted to string differently:</p>

```<code>public String listToString(List<Object> list) {
        StringBuilder sb = new StringBuilder();

        for (Object object : list) {
            if (object != null) {
                if (object.getClass().isArray()) {
                    sb.append(Arrays.toString((Object[]) object));
                } else {
                    sb.append(object.toString());
                }
            }
        }
        return sb.toString();
    }
</code>```

Title: Best way to convert ArrayList to string

Body:
I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String.  In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets

Body:
I think you need to check if object converted to string is or is not array,because they are converted to string differently:

public String listToString(List<Object> list) {
        StringBuilder sb = new StringBuilder();

        for (Object object : list) {
            if (object != null) {
                if (object.getClass().isArray()) {
                    sb.append(Arrays.toString((Object[]) object));
                } else {
                    sb.append(object.toString());
                }
            }
        }
        return sb.toString();
    }


来源: stackexchange

问:
Index error in Python( index out of range)
```<code>given_number=str(input("Enter the number:"))
total=str(0)
num=0
while num<=len(given_number):
       total+=given_number[num]
       num+=1
print(total)
</code>```

Got indexerror.Where is the fault?

答:
You are adding a "0" to the input string. you can directly do like

```<code>print("0"+input())
</code>```

Instead using the most lengthy method to append something to a string.

ContentLicense: CC BY-SA 3.0

Body:
given_number=str(input("Enter the number:"))
total=str(0)
num=0
while num<=len(given_number):
       total+=given_number[num]
       num+=1
print(total)

Got indexerror.Where is the fault?

Body:
You are adding a "0" to the input string. you can directly do like

print("0"+input())

Instead using the most lengthy method to append something to a string.


问:
org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type[EDITED]
In Android web service using POST method of REST TEMPLATE, I am trying to send an object to server which contains few parameters and and 2 Objects. Those 2 Objects contains few parameters and 3 Lists of different Objects and each of those 3 Lists of Objects contains few parameters inside them and 1 List of Object that contains a byte array alone. Like in the below pics:

Pic 1[Main Object(The one I am trying to send)]:

Pic 2[Object inside the Main Object comprising 3 Lists of Objects]:

Pic 3[An Object as List comprising 1 List of Another Object inside it, likewise for the other 2(Accommodation & Others)]:

Pic 4[List of Object inside the sub-Object containing a byre array parameter alone]:

And my code for webservice POST method:

```<code>public static final String capUrl = "http://192.168.1.7:8084/CAPWS";

public Expenses setExpensesByBatch(Expenses expenses) {

    try {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
        list.add(new MappingJacksonHttpMessageConverter());
        restTemplate.setMessageConverters(list);

        String b = restTemplate.postForObject(capUrl + "/UX/", expenses, String.class);

        Log.e("String ===============b", b + "     ++++");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("expObjPost_WsCli_EX", e.toString());
    }
    return expenses;
}
</code>```

Whatever I do it returns org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type

My LOGCAT below:

My server side code:

```<code>@RequestMapping(value = CapRestURIConstants.UPDATEEXPENSES, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
String updateExpenses(@RequestBody Expenses expenses) {
    String response = "true";

    System.out.println("incoming--------" + "UPDATEEXPENSES");
    try {
        if (expenses != null) {
            //System.out.println("expenses--------" + expenses);

            int catType = expenses.getCategoryType();
            String categoryType = String.valueOf(catType);

            String categoryId = expenses.getCategoryId();
            String batchId = expenses.getBatchId();

            System.out.println("categoryType--------" + categoryType);
            System.out.println("categoryId--------" + categoryId);
            System.out.println("batchId--------" + batchId);

            Batch batch = getBatchById(batchId);
            if (batch != null) {

                expenseDataNew(batch, expenses);
                expenseImagesNew(batch, expenses);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        response = "faslse";
    }
    return response;
}

public void expenseDataNew(Batch batch, Expenses expenses) {

    Session session = null;
    Transaction transaction = null;
    Gson gson = new Gson();

    try {

        LinkedTreeMap masterMap = (LinkedTreeMap) gson.fromJson(batch.getMasterJson(), Object.class);
        LinkedTreeMap expenseObject = (LinkedTreeMap) masterMap.get("2007");

        masterMap.replace(expenseObject, expenses);
        String masterJson = gson.toJson(masterMap);
        batch.setMasterJson(masterJson);

        session = HibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();
        session.saveOrUpdate(batch);

        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

public void expenseImagesNew(Batch batch, Expenses expenses) {

    Session session = null;
    Transaction transaction = null;
    Gson gson = new Gson();

    try {

        // DIVERTING TO IMAGE DB
        session = ImageHibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();

        if (expenses != null) {

            int catType = expenses.getCategoryType();
            String categoryType = String.valueOf(catType);
            System.out.println("categoryType--------" + categoryType);

            String categoryId = expenses.getCategoryId();
            System.out.println("categoryId--------" + categoryId);

            String travelExpenseImgId = "f257f225-41da-11e7-be05-001d92ba9634";
            String accommodationExpenseImgId = "204b4baf-41db-11e7-be05-001d92ba9634";
            String otherExpenseImgId = "45d31872-41db-11e7-be05-001d92ba9634";

            AssessorExpense assessorExpense = expenses.getAssessorExpense();
            TCExpense tCExpense = expenses.getTcExpense();

            Boolean isTravel, isAccomadation, isOthers;

            List<Travel> travelList;
            List<Accomadation> accommodationList;
            List<Others> othersList;

            ArrayList proof;
            Expense expense;
            ExpenseImage expenseImage;

            // categoryType: 1 = Assessor
            // categoryType: 4 = TC
            if (categoryType.equals("1")) {

                if (assessorExpense != null) {

                    isTravel = assessorExpense.isTravel();
                    if (isTravel) {

                        travelList = (ArrayList) assessorExpense.getTravel();
                        System.out.println("travelList.size()==" + travelList.size());

                        expense = getExpense(travelExpenseImgId);
                        System.out.println("expense==travel==1==:" + expense);
                        String expenseStr = String.valueOf(expense);
                        System.out.println("expenseStr==travel==1==:" + expenseStr);

                        for (Travel travel : travelList) {

                            List<ExpenseImageObject> expenseImageObjects = (ArrayList) travel.getExpenseImageObjects();
                            System.out.println("travel==expenseImageObjects.size()== :" + expenseImageObjects.size());

                            for (ExpenseImageObject image : expenseImageObjects) {

                                System.out.println("expense===travel==for==:" + expense);

                                expenseImage = new ExpenseImage();

                                expenseImage.setBatchId(batch.getBatchId());
                                expenseImage.setCategoryId(expenses.getCategoryId());
                                expenseImage.setExpimgId(expenseStr);
                                expenseImage.setImage(image.getImage());
                                expenseImage.setStatus(1);   // dummy status 1 - Travel, 2 - Accommodation, 3 - Other

                                session.saveOrUpdate(expenseImage);
                            }
                        }
                    }
                }
            }
        }
        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
</code>```

I am actually trying to send an object with lists of data as well list of photos in each list to the server.
Browsed through several websites and almost all topics related to the error on Stack Overflow, Been sitting on this issue for more than a week. Hope I would find some help.

答: After a hell lot of research and experts suggestions, I finally managed to find the solution to my problem. The problem is not with the code. Its actually perfect. The problem is with the Objects I use to get & set. I am using NetBeans for server side coding. What I did was, I created my necessary Objects in Android studio, copied the parameters, getters & setters and pasted them on NetBeans, Object class. The problem was with the booleans I've been using. The booleans that are created on Android Studio didn't support on NetBeans in some cases, that prevented hitting the server. And after getting expert advice, I did the Object creation on NetBeans copied the parameters, getters & setters and pasted them on Android Studio Object class. And then it worked well. Took me more than 2 weeks to solve this issue. Hope this would be of some help.

Body:
In Android web service using POST method of REST TEMPLATE, I am trying to send an object to server which contains few parameters and and 2 Objects. Those 2 Objects contains few parameters and 3 Lists of different Objects and each of those 3 Lists of Objects contains few parameters inside them and 1 List of Object that contains a byte array alone. Like in the below pics:

Pic 1[Main Object(The one I am trying to send)]:

Pic 2[Object inside the Main Object comprising 3 Lists of Objects]:

Pic 3[An Object as List comprising 1 List of Another Object inside it, likewise for the other 2(Accommodation & Others)]:

Pic 4[List of Object inside the sub-Object containing a byre array parameter alone]:

And my code for webservice POST method:

public static final String capUrl = "http://192.168.1.7:8084/CAPWS";

public Expenses setExpensesByBatch(Expenses expenses) {

    try {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
        list.add(new MappingJacksonHttpMessageConverter());
        restTemplate.setMessageConverters(list);

        String b = restTemplate.postForObject(capUrl + "/UX/", expenses, String.class);

        Log.e("String ===============b", b + "     ++++");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("expObjPost_WsCli_EX", e.toString());
    }
    return expenses;
}

Whatever I do it returns org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type

My LOGCAT below:

My server side code:

@RequestMapping(value = CapRestURIConstants.UPDATEEXPENSES, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
String updateExpenses(@RequestBody Expenses expenses) {
    String response = "true";

    System.out.println("incoming--------" + "UPDATEEXPENSES");
    try {
        if (expenses != null) {
            //System.out.println("expenses--------" + expenses);

            int catType = expenses.getCategoryType();
            String categoryType = String.valueOf(catType);

            String categoryId = expenses.getCategoryId();
            String batchId = expenses.getBatchId();

            System.out.println("categoryType--------" + categoryType);
            System.out.println("categoryId--------" + categoryId);
            System.out.println("batchId--------" + batchId);

            Batch batch = getBatchById(batchId);
            if (batch != null) {

                expenseDataNew(batch, expenses);
                expenseImagesNew(batch, expenses);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        response = "faslse";
    }
    return response;
}

public void expenseDataNew(Batch batch, Expenses expenses) {

    Session session = null;
    Transaction transaction = null;
    Gson gson = new Gson();

    try {

        LinkedTreeMap masterMap = (LinkedTreeMap) gson.fromJson(batch.getMasterJson(), Object.class);
        LinkedTreeMap expenseObject = (LinkedTreeMap) masterMap.get("2007");

        masterMap.replace(expenseObject, expenses);
        String masterJson = gson.toJson(masterMap);
        batch.setMasterJson(masterJson);

        session = HibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();
        session.saveOrUpdate(batch);

        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

public void expenseImagesNew(Batch batch, Expenses expenses) {

    Session session = null;
    Transaction transaction = null;
    Gson gson = new Gson();

    try {

        // DIVERTING TO IMAGE DB
        session = ImageHibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();

        if (expenses != null) {

            int catType = expenses.getCategoryType();
            String categoryType = String.valueOf(catType);
            System.out.println("categoryType--------" + categoryType);

            String categoryId = expenses.getCategoryId();
            System.out.println("categoryId--------" + categoryId);

            String travelExpenseImgId = "f257f225-41da-11e7-be05-001d92ba9634";
            String accommodationExpenseImgId = "204b4baf-41db-11e7-be05-001d92ba9634";
            String otherExpenseImgId = "45d31872-41db-11e7-be05-001d92ba9634";

            AssessorExpense assessorExpense = expenses.getAssessorExpense();
            TCExpense tCExpense = expenses.getTcExpense();

            Boolean isTravel, isAccomadation, isOthers;

            List<Travel> travelList;
            List<Accomadation> accommodationList;
            List<Others> othersList;

            ArrayList proof;
            Expense expense;
            ExpenseImage expenseImage;

            // categoryType: 1 = Assessor
            // categoryType: 4 = TC
            if (categoryType.equals("1")) {

                if (assessorExpense != null) {

                    isTravel = assessorExpense.isTravel();
                    if (isTravel) {

                        travelList = (ArrayList) assessorExpense.getTravel();
                        System.out.println("travelList.size()==" + travelList.size());

                        expense = getExpense(travelExpenseImgId);
                        System.out.println("expense==travel==1==:" + expense);
                        String expenseStr = String.valueOf(expense);
                        System.out.println("expenseStr==travel==1==:" + expenseStr);

                        for (Travel travel : travelList) {

                            List<ExpenseImageObject> expenseImageObjects = (ArrayList) travel.getExpenseImageObjects();
                            System.out.println("travel==expenseImageObjects.size()== :" + expenseImageObjects.size());

                            for (ExpenseImageObject image : expenseImageObjects) {

                                System.out.println("expense===travel==for==:" + expense);

                                expenseImage = new ExpenseImage();

                                expenseImage.setBatchId(batch.getBatchId());
                                expenseImage.setCategoryId(expenses.getCategoryId());
                                expenseImage.setExpimgId(expenseStr);
                                expenseImage.setImage(image.getImage());
                                expenseImage.setStatus(1);   // dummy status 1 - Travel, 2 - Accommodation, 3 - Other

                                session.saveOrUpdate(expenseImage);
                            }
                        }
                    }
                }
            }
        }
        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

I am actually trying to send an object with lists of data as well list of photos in each list to the server.
Browsed through several websites and almost all topics related to the error on Stack Overflow, Been sitting on this issue for more than a week. Hope I would find some help.


问:
Link within a text in another column php
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.</p>

```<code> echo "<b><h4>{$list["updates1"]}<a>{$list["link1"]}</a></b></h4><hr>";
</code>```

答:
Close the
 tag before the  tag, like this:

```<code>echo "<b><h4>{$list["updates1"]}<a>{$list["link1"]}</a></h4></b><hr>";
</code>```

Body:
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.

 echo "
{$list["updates1"]}{$list["link1"]}

";

Body:
Close the <h4> tag before the <b> tag, like this:

echo "<b><h4>{$list["updates1"]}<a>{$list["link1"]}</a></h4></b><hr>";


问:
heap overflow affecting other programs
I was trying to create the condition for malloc to return a NULL pointer. In the below program, though I can see malloc returning NULL, once the program is forcebly terminated, I see that all other programs are becoming slow and finally I had to reboot the system. So my question is whether the memory for heap is shared with other programs? If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution? I am using windows 10, Mingw.</p>

```<code>#include <stdio.h>
#include <malloc.h>

void mallocInFunction(void)
{
    int *ptr=malloc(500);
    if(ptr==NULL)
    {
        printf("Memory Could not be allocated\n");
    }
    else
    {
        printf("Allocated memory successfully\n");
    }
}

int main (void)
{
    while(1)
    {
        mallocInFunction();
    }

    return(0);
}
</code>```

答:
Your question cannot be answered in the context of C, the language. For C, there's no such thing as a heap, a process, ...

But it can be answered in the context of operating systems. Even a bit generically because many modern multitasking OSes do similar things.

Given a modern multitasking OS, it will use virtual address spaces for each process. The OS manages a fixed size of physical RAM and divides this into pages, when a process needs memory, such pages are mapped into the process' virtual address space (typically using a different virtual address than the physical one). So when all memory pages are claimed by the OS itself and by the processes running, the OS will typically save some of these pages that are not in active use to disk, in a swap area, in order to serve this page as a fresh page to the next process requesting one. But when the original page is touched (and this is typically the case with free(), see below), it must first be loaded from disk again, but to have a free page for this, another page must be saved to swap space.

This is, like all disk I/O, slow, and it's probably what you see happening here.

Now to fully understand this: what does malloc() do? It typically requests from the operating system to have the memory of the own process increased (and if necessary, the OS does this by mapping another page), and it uses this new memory by writing some information there about the block of memory requested (so free() can work correctly later) and ultimately returns a pointer to a block that's free to use for the program. free() uses the information written by malloc(), modifies it to indicate this block is free again, and it typically can't give any memory back to the OS because there are other malloc()d blocks in the same page. It will give memory back when possible, but that's the exception in a typical scenario where dynamic allocations are heavily used.

So, the answer to your question is: Yes, the RAM is shared because there is only one set of physical RAM. The OS does the best it can to hide that fact and virtualize RAM, but if a process consumes all that is there, this will have visible effects.

Title: heap overflow affecting other programs

Body:
I was trying to create the condition for malloc to return a NULL pointer. In the below program, though I can see malloc returning NULL, once the program is forcebly terminated, I see that all other programs are becoming slow and finally I had to reboot the system. So my question is whether the memory for heap is shared with other programs? If not, other programs should not have affected. Is OS is not allocating certain amount of memory at the time of execution? I am using windows 10, Mingw.

#include <stdio.h>
#include <malloc.h>

void mallocInFunction(void)
{
    int *ptr=malloc(500);
    if(ptr==NULL)
    {
        printf("Memory Could not be allocated\n");
    }
    else
    {
        printf("Allocated memory successfully\n");
    }
}

int main (void)
{
    while(1)
    {
        mallocInFunction();
    }

    return(0);
}


答:
```<code>echo "<b><h4>{$list['updates1']}<a href=\"{$list['link1']}\"> Your Link Title</a></h4></b><hr>";
</code>```

<p>EDIT: Try to close proper way tag </p>

Title: Link within a text in another column php

Body:
echo "<b><h4>{$list['updates1']}<a href=\"{$list['link1']}\"> Your Link Title</a></h4></b><hr>";

EDIT: Try to close proper way tag


问:
Ng dirty not showing after save button clicked
My application so far is working great. It is not a form (no form tagged used) but it is a series of input boxes that a user must enter. Each input box that a user fills, I am adding an orange border on that input field. I am doing that through:

app.css:

```<code>#modifyTop .ng-dirty{
  border: 2px orange;
}
</code>```

index.html:
...

```<code><body id="modifyTop" name="modifyTop" ng-controller="ModifyPageCtrl">

<button ng-click=save()>Save</button>
</code>```

....

Inside this index.html is a save button. Once I hit the save button, the border field goes away. I am doing this through (I used jQuery inside an Angular controller, not sure if thats acceptable):

ModifyPageCtrl.js:
....

```<code>function save(){
 ....
  $('#modifyTop .ng-dirty').removeClass('ng-dirty')
...
}
</code>```

So the problem is the following. After hitting save, if say the user wants to change again a particular input field, then it does not make that orange border show up. Only the fields that were previously untouched/not modified have the border appear. I have to reload the page, to make the border appear again in those particular input fields. Can someone please provide examples on how I can make this work? I understand I have given very small snippets of my code thats because my work doesn't allow me to paste company code but I will try to provide more details if people are unable to help with the provided information. Also, would like to mention that my app has no errors- this is a enhancement fix that i am working on.
Thank you

答:
You need to use $setPristine():

http://docs.angularjs.org/api/ng/type/form.FormController

From the docs:

Sets the form to its pristine state.

This method sets the form's $pristine state to true, the $dirty state
  to false, removes the ng-dirty class and adds the ng-pristine class.
  Additionally, it sets the $submitted state to false.

This method will also propagate to all the controls contained in this
  form.

Body:
My application so far is working great. It is not a form (no form tagged used) but it is a series of input boxes that a user must enter. Each input box that a user fills, I am adding an orange border on that input field. I am doing that through:

app.css:

#modifyTop .ng-dirty{
  border: 2px orange;
}

index.html:
...

<button ng-click=save()>Save</button>

....

Inside this index.html is a save button. Once I hit the save button, the border field goes away. I am doing this through (I used jQuery inside an Angular controller, not sure if thats acceptable):

ModifyPageCtrl.js:
....

function save(){
 ....
  $('#modifyTop .ng-dirty').removeClass('ng-dirty')
...
}

So the problem is the following. After hitting save, if say the user wants to change again a particular input field, then it does not make that orange border show up. Only the fields that were previously untouched/not modified have the border appear. I have to reload the page, to make the border appear again in those particular input fields. Can someone please provide examples on how I can make this work? I understand I have given very small snippets of my code thats because my work doesn't allow me to paste company code but I will try to provide more details if people are unable to help with the provided information. Also, would like to mention that my app has no errors- this is a enhancement fix that i am working on.
Thank you


问:
how can .NET, on Azure VWindows Server 2012, decrypt SMS text message from an AT&T gophone
I wrote a cool .NET Windows application that communicates by SMS text messages with users, or by email.  It treats SMS text messages just like email.  When my Windows server 2012 receives a text message from a mobile device, or an email, both kinds arrives into C:\inetpub\mailroot\Drop\ and my app processes them.

It all has been working great with email from Gmail, Hotmail, etc., and from SMS from Verizon.  But then my friend comes over and we test receiving from his AT&T gophone... Blooey!  I get the email (see below) from his mobile device's SMS and all looks normal, except the actual text message payload is scrambled.

How do I descramble?  Why is the text scrambled, in the first place?

```<code>X-SENDER: ##########@MMS.ATT.NET
X-RECEIVER: xxxxxxxxxx@xxxxxxx.COM
RECEIVED: FROM BTHCEG-MOMTA01-MMS.MYCINGULAR.NET ([]) BY WITH MICROSOFT SMTPSVC(8.5.9600.16384);
     MON, 5 JUN 2017 17:42:02 -0700
RETURN-PATH: <##########@@MMS.ATT.NET>
RECEIVED: FROM [] ([:14264] HELO=ALPNMS03)
    BY BTHCEG-MOMTA01 (ENVELOPE-FROM <##########@@MMS.ATT.NET>)
    (ECELERITY 3.0.23.37692 R(37717)) WITH ESMTP
    ID D2/65-04620-B5AF5395; MON, 05 JUN 2017 17:42:03 -0700
X-MMS-MESSAGE-TYPE: M-SEND-REQ
X-MMS-TRANSACTION-ID: 1496709721-5
X-MMS-MMS-VERSION: 1.2
TO: PRAY@##########@COM
FROM: ##########@@MMS.ATT.NET
DATE: MON, 5 JUN 2017 20:42:02 -0400 (EDT)
X-MMS-SENDER-VISIBILITY: SHOW
CONTENT-TYPE: MULTIPART/MIXED;
    BOUNDARY="----=_PART_7984369_300459990.1496709722943"
MIME-VERSION: 1.0
MESSAGE-ID: <1096997833.194273661496709722943.JAVAMAIL.NEMS@ALPNMS03>
X-ORIGINALARRIVALTIME: 06 JUN 2017 00:42:02.0454 (UTC) FILETIME=[B6A1AF60:01D2DE5D]

------=_PART_7984369_300459990.1496709722943
CONTENT-TYPE: TEXT/PLAIN; CHARSET=UTF-8
CONTENT-DISPOSITION: ATTACHMENT; FILENAME=TEXT_0.TXT; CHARSET=US-ASCII
CONTENT-ID: 0
CONTENT-LOCATION: TEXT_0.TXT
CONTENT-TRANSFER-ENCODING: BASE64
</code>```

..................BELOW IS THE SCRAMBLED TEXT MESSAGE: ............

```<code>TXKGCHJHEWVYIGLZOIBMB3IGSGVPZGKGDG8GAGF2ZSBWZWFJZSBPBIBOZXIGZMFTAWX5
</code>```

......THE ACTUAL MESSAGE WAS:  "My prayer is: for Heidi to have peace in her family"
    ------=_PART_7984369_300459990.1496709722943--

```<code>X-SENDER: ##########@@MMS.ATT.NET
X-RECEIVER: PRAY@##########@.ORG
RECEIVED: FROM BTHCEG-MOMTA02-MMS.MYCINGULAR.NET ([##########@]) BY PRAYSHEP WITH MICROSOFT SMTPSVC(8.5.9600.16384);
     MON, 5 JUN 2017 18:14:30 -0700
RETURN-PATH: <##########@@MMS.ATT.NET>
RECEIVED: FROM [##########@] ([##########@:51516] HELO=ALPNMS03)
    BY BTHCEG-MOMTA02 (ENVELOPE-FROM <##########@@MMS.ATT.NET>)
    (ECELERITY 3.0.23.37692 R(37717)) WITH ESMTP
    ID 29/CD-12903-7F106395; MON, 05 JUN 2017 18:14:31 -0700
X-MMS-MESSAGE-TYPE: M-SEND-REQ
X-MMS-TRANSACTION-ID: 1496711669-7
X-MMS-MMS-VERSION: 1.2
TO: PRAY@##########@.ORG
FROM: ##########@@MMS.ATT.NET
DATE: MON, 5 JUN 2017 21:14:30 -0400 (EDT)
X-MMS-SENDER-VISIBILITY: SHOW
CONTENT-TYPE: MULTIPART/MIXED;
    BOUNDARY="----=_PART_7989525_395020720.1496711670941"
MIME-VERSION: 1.0
MESSAGE-ID: <1241288163.194397521496711670942.JAVAMAIL.NEMS@ALPNMS03>
X-ORIGINALARRIVALTIME: 06 JUN 2017 01:14:30.0518 (UTC) FILETIME=[3FC4A960:01D2DE62]

------=_PART_7989525_395020720.1496711670941
CONTENT-TYPE: TEXT/PLAIN; CHARSET=UTF-8
CONTENT-DISPOSITION: ATTACHMENT; FILENAME=TEXT_0.TXT; CHARSET=US-ASCII
CONTENT-ID: 0
CONTENT-LOCATION: TEXT_0.TXT
CONTENT-TRANSFER-ENCODING: BASE64
</code>```

.................  SCRAMBLED FROM TEXT MESSAGE SMS: ...........
    QWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFH
............ACTUAL WAS ALL "AAAAAAAAAAAAA..."
    ------=_PART_7989525_395020720.1496711670941--

答:
So this HttpRequest is a Multi-part form.

Each file is split between the boundary:

```<code>BOUNDARY="----=_PART_7984369_300459990.1496709722943"
</code>```

And then each file has its own set of information:

```<code>------=_PART_7984369_300459990.1496709722943
CONTENT-TYPE: TEXT/PLAIN; CHARSET=UTF-8
CONTENT-DISPOSITION: ATTACHMENT; FILENAME=TEXT_0.TXT; CHARSET=US-ASCII
CONTENT-ID: 0
CONTENT-LOCATION: TEXT_0.TXT
CONTENT-TRANSFER-ENCODING: BASE64
</code>```

This boundary has the CONTENT-TRANSFER-ENCODING Header, meaning that all of its contents (TEXT_0.TXT) is encoded as BASE64.

I took a look at what you posted the message was and it should be case sensitive resulting in TXkgcHJheWVyIGlzOiBmb3IgSGVpZGkgdG8gaGF2ZSBwZWFjZSBpbiBoZXIgZmFtaWx5, so you may have some data corruption, or the way you are viewing the encoding is changing it.

I can't provide a code sample as I'm not sure if you are using Webforms or MVC, but here is an example with asp.net MVC Web Api 2

Body:
I wrote a cool .NET Windows application that communicates by SMS text messages with users, or by email.  It treats SMS text messages just like email.  When my Windows server 2012 receives a text message from a mobile device, or an email, both kinds arrives into C:\inetpub\mailroot\Drop\ and my app processes them.

It all has been working great with email from Gmail, Hotmail, etc., and from SMS from Verizon.  But then my friend comes over and we test receiving from his AT&T gophone... Blooey!  I get the email (see below) from his mobile device's SMS and all looks normal, except the actual text message payload is scrambled.

How do I descramble?  Why is the text scrambled, in the first place?

X-SENDER: ##########@MMS.ATT.NET
X-RECEIVER: xxxxxxxxxx@xxxxxxx.COM
RECEIVED: FROM BTHCEG-MOMTA01-MMS.MYCINGULAR.NET ([]) BY WITH MICROSOFT SMTPSVC(8.5.9600.16384);
     MON, 5 JUN 2017 17:42:02 -0700
RETURN-PATH: <##########@@MMS.ATT.NET>
RECEIVED: FROM [] ([:14264] HELO=ALPNMS03)
    BY BTHCEG-MOMTA01 (ENVELOPE-FROM <##########@@MMS.ATT.NET>)
    (ECELERITY 3.0.23.37692 R(37717)) WITH ESMTP
    ID D2/65-04620-B5AF5395; MON, 05 JUN 2017 17:42:03 -0700
X-MMS-MESSAGE-TYPE: M-SEND-REQ
X-MMS-TRANSACTION-ID: 1496709721-5
X-MMS-MMS-VERSION: 1.2
TO: PRAY@##########@COM
FROM: ##########@@MMS.ATT.NET
DATE: MON, 5 JUN 2017 20:42:02 -0400 (EDT)
X-MMS-SENDER-VISIBILITY: SHOW
CONTENT-TYPE: MULTIPART/MIXED;
    BOUNDARY="----=_PART_7984369_300459990.1496709722943"
MIME-VERSION: 1.0
MESSAGE-ID: <1096997833.194273661496709722943.JAVAMAIL.NEMS@ALPNMS03>
X-ORIGINALARRIVALTIME: 06 JUN 2017 00:42:02.0454 (UTC) FILETIME=[B6A1AF60:01D2DE5D]

------=_PART_7984369_300459990.1496709722943
CONTENT-TYPE: TEXT/PLAIN; CHARSET=UTF-8
CONTENT-DISPOSITION: ATTACHMENT; FILENAME=TEXT_0.TXT; CHARSET=US-ASCII
CONTENT-ID: 0
CONTENT-LOCATION: TEXT_0.TXT
CONTENT-TRANSFER-ENCODING: BASE64

..................BELOW IS THE SCRAMBLED TEXT MESSAGE: ............

TXKGCHJHEWVYIGLZOIBMB3IGSGVPZGKGDG8GAGF2ZSBWZWFJZSBPBIBOZXIGZMFTAWX5

......THE ACTUAL MESSAGE WAS:  "My prayer is: for Heidi to have peace in her family"
    ------=_PART_7984369_300459990.1496709722943--

X-SENDER: ##########@@MMS.ATT.NET
X-RECEIVER: PRAY@##########@.ORG
RECEIVED: FROM BTHCEG-MOMTA02-MMS.MYCINGULAR.NET ([##########@]) BY PRAYSHEP WITH MICROSOFT SMTPSVC(8.5.9600.16384);
     MON, 5 JUN 2017 18:14:30 -0700
RETURN-PATH: <##########@@MMS.ATT.NET>
RECEIVED: FROM [##########@] ([##########@:51516] HELO=ALPNMS03)
    BY BTHCEG-MOMTA02 (ENVELOPE-FROM <##########@@MMS.ATT.NET>)
    (ECELERITY 3.0.23.37692 R(37717)) WITH ESMTP
    ID 29/CD-12903-7F106395; MON, 05 JUN 2017 18:14:31 -0700
X-MMS-MESSAGE-TYPE: M-SEND-REQ
X-MMS-TRANSACTION-ID: 1496711669-7
X-MMS-MMS-VERSION: 1.2
TO: PRAY@##########@.ORG
FROM: ##########@@MMS.ATT.NET
DATE: MON, 5 JUN 2017 21:14:30 -0400 (EDT)
X-MMS-SENDER-VISIBILITY: SHOW
CONTENT-TYPE: MULTIPART/MIXED;
    BOUNDARY="----=_PART_7989525_395020720.1496711670941"
MIME-VERSION: 1.0
MESSAGE-ID: <1241288163.194397521496711670942.JAVAMAIL.NEMS@ALPNMS03>
X-ORIGINALARRIVALTIME: 06 JUN 2017 01:14:30.0518 (UTC) FILETIME=[3FC4A960:01D2DE62]

------=_PART_7989525_395020720.1496711670941
CONTENT-TYPE: TEXT/PLAIN; CHARSET=UTF-8
CONTENT-DISPOSITION: ATTACHMENT; FILENAME=TEXT_0.TXT; CHARSET=US-ASCII
CONTENT-ID: 0
CONTENT-LOCATION: TEXT_0.TXT
CONTENT-TRANSFER-ENCODING: BASE64

.................  SCRAMBLED FROM TEXT MESSAGE SMS: ...........
    QWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFHYWFH
............ACTUAL WAS ALL "AAAAAAAAAAAAA..."
    ------=_PART_7989525_395020720.1496711670941--

Body:
So this HttpRequest is a Multi-part form.

Each file is split between the boundary:

BOUNDARY="----=_PART_7984369_300459990.1496709722943"

And then each file has its own set of information:

------=_PART_7984369_300459990.1496709722943
CONTENT-TYPE: TEXT/PLAIN; CHARSET=UTF-8
CONTENT-DISPOSITION: ATTACHMENT; FILENAME=TEXT_0.TXT; CHARSET=US-ASCII
CONTENT-ID: 0
CONTENT-LOCATION: TEXT_0.TXT
CONTENT-TRANSFER-ENCODING: BASE64

This boundary has the CONTENT-TRANSFER-ENCODING Header, meaning that all of its contents (TEXT_0.TXT) is encoded as BASE64.

I took a look at what you posted the message was and it should be case sensitive resulting in TXkgcHJheWVyIGlzOiBmb3IgSGVpZGkgdG8gaGF2ZSBwZWFjZSBpbiBoZXIgZmFtaWx5, so you may have some data corruption, or the way you are viewing the encoding is changing it.

I can't provide a code sample as I'm not sure if you are using Webforms or MVC, but here is an example with asp.net MVC Web Api 2


答:
malloc() is not system call but libc library function. So when a program ask for allocating memory via malloc(), system call brk()/sbrk() OR mmap() to allocated page(s), more details here.

Please keep in mind that the memory you get is all virtual in nature, that means if you have 3GB of physical RAM you can actually allocate almost infinite memory. So how does this happens? This happens via concept called 'paging', where system stores and retrieves data from secondary memory storage(HDD/SDD) to main memory(RAM), more details here.

So with this theory, out of memory usually quite rare but program like above which is checking system limits, this can happen. This is nicely explained here.

Now, why other programs are sort of hanged OR slow? Because they all share the same operating system and system is starving for resource. In fact at a point the system will crash and reboot again.

Hope this helps?

Title: heap overflow affecting other programs


问:
In .net, is there an opposite function to Server.HTMLEncode()?
.Net's Server.HTMLEncode() is the very helpful function that takes an HTML string and replaces special characters with their entity equivalents - "<" becomes &lt ; and so forth.

Is there a (built-in) function that does the reverse?  There doesn't seem to be, and I am incredulous.  While I could certainly write my own (and have in the past) Server.HTMLEncode has all kinds of cool handling for different string encodings and high-level unicode characters that I would really not have crash my hand-rolled decoder in a year's time.

What do other people do when they need the plain HTML back?

Update:
To answer the first batch of questions, I present the MSDN article on the
Server object, which has Encode but no Decode...  I'm as amazed as anyone.

Update2: as several alert readers have pointed out, the docs I was looking at were for classic ASP, not ASP.Net.  Thanks guys, that's an important MSDN safety tip.

答:
Ah, MSDN, I love you.

There IS a Server.HTMLDecode() method, the documentation for the server object just doesn't mention that it exists.

Thanks, everybody!

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie


问:
classwork - shellsort in c#?
i need an easy way to sort an array using ShellSort in c#, please help me</p>

答: Use shell sort.</p>

Title: classwork - shellsort in c#?

Body: Use shell sort.


问:
Integration of Sauceconnect with Nightwatch/NodeJS
I have configured my scripts in Nightwatch with sauce labs and I am able to execute any public IP on sauce labs. what I want now is to execute my private URL (actual test URL) on the sauce labs. Please assist on how it is to be done.</p>

答:
Nightwatch is just a testing framework and is not capable of running SauceConnect.

Directions to test your dev site with sauce connect follow.  If you haven't already, you can download Sauce Connect here: https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy

From the terminal:

   cd into the sauce connect folder sc-4.4.x-osx/bin

   run the following command:

```<code> ./sc -u <SAUCE_USERNAME> -k <SAUCE_ACCESS_KEY>
</code>```

Once you see sauce connect up and running, go ahead and run your test suite.  You will now be able to access test sites behind your local firewall.

If you want to automate everything you will need to integrate with a CI program. There is a pretty good article on testing with nightwatch + travisCI + sauceConnect here.

Body:
Nightwatch is just a testing framework and is not capable of running SauceConnect.

Directions to test your dev site with sauce connect follow.  If you haven't already, you can download Sauce Connect here: https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy

From the terminal:

   cd into the sauce connect folder sc-4.4.x-osx/bin

   run the following command:

 ./sc -u <SAUCE_USERNAME> -k <SAUCE_ACCESS_KEY>

Once you see sauce connect up and running, go ahead and run your test suite.  You will now be able to access test sites behind your local firewall.

If you want to automate everything you will need to integrate with a CI program. There is a pretty good article on testing with nightwatch + travisCI + sauceConnect here.


问:
DataTables add html after formated data
I'm rendering this data in my DataTable:

```<code>{"data":"price",
 render: $.fn.dataTable.render.number( '.', ',', 0, '$' )
}
</code>```

It returns a number like that "$9.999", so, i want a button after this (edit button), but i don't know how to do that. Something like this.

I would appreciate any ideas.

Thanks, and i'm sorry for my bad english.

答:
try</p>

```<code>render: function(data,type,row){
                var dato = $.fn.dataTable.render.number( '.', ',', 0, '$' );
                return dato.display(data) + "  <button type='button' class='editar btn btn-primary' data-toggle='modal' data-target='#modalEditar' ><i class='fa fa-pencil-square-o'></i></button>"
            }
</code>```

Title: DataTables add html after formated data

Body:
I'm rendering this data in my DataTable:

{"data":"price",
 render: $.fn.dataTable.render.number( '.', ',', 0, '$' )
}

It returns a number like that "$9.999", so, i want a button after this (edit button), but i don't know how to do that. Something like this.

I would appreciate any ideas.

Thanks, and i'm sorry for my bad english.

Body:
try

render: function(data,type,row){
                var dato = $.fn.dataTable.render.number( '.', ',', 0, '$' );
                return dato.display(data) + "  <button type='button' class='editar btn btn-primary' data-toggle='modal' data-target='#modalEditar' ><i class='fa fa-pencil-square-o'></i></button>"
            }


问:
Scrape off some array values for asserting (Protractor)
Is there a way to scrape off or remove random or few values that are returned by the element.all array ?

The scenario i am trying to automate is to check that the word 'HTML' should be present in every row returned from the list of array.

I have used the w3Schools as a dummy test website to trial my scenario, below is the code which is failing because of assertion.

```<code>describe('Searching for word HTML', function() {
    var array=[];
    var counter=0;
    it('Beginning of the test', function() {

    browser.ignoreSynchronization = true;
    browser.get('https://www.w3schools.com/html/default.asp');

    browser.sleep(5000).then(function(){});

    var lines = element.all(by.css('#leftmenuinnerinner>a'));
    lines.count().then(function(counting){
        console.log("There are total "+counting+" links");
        counter=counter+counting;
        return counting;
    })
    lines.getText().then(function(text){

        console.log("Values:::: "+text);
        for(var k=0;k<text.length;k++){
        expect(text[k]).toContain('HTML');
        }
    })
    })
})
</code>```

I know i could use the xpath values & iterate through a loop of 76 values only but i am trying via a approach of css selector & i need to strictly get the entire list of values, so is there a way i could trim or scrape off the values 'HTTP Messages','HTTP Methods','PX to EM Converter' & 'Keyboard Shortcuts' dynamically through my code from the array returned so that my assertion passes ?

答:
You can use the filter method to only keep the elements containing the text you want. - http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.filter

```<code>lines.filter(function(elem, index) {
  return elem.getText().then(function(text) {
    return text.includes('HTML');
  });
})
</code>```

Or you can use the cssContainingText locator to get the desired elements. - http://www.protractortest.org/#/api?view=ProtractorBy.prototype.cssContainingText

```<code>var lines = element.all(by.cssContainingText('#leftmenuinnerinner>a','HTML'));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to scrape off or remove random or few values that are returned by the element.all array ?

The scenario i am trying to automate is to check that the word 'HTML' should be present in every row returned from the list of array.

I have used the w3Schools as a dummy test website to trial my scenario, below is the code which is failing because of assertion.

describe('Searching for word HTML', function() {
    var array=[];
    var counter=0;
    it('Beginning of the test', function() {

    browser.ignoreSynchronization = true;
    browser.get('https://www.w3schools.com/html/default.asp');

    browser.sleep(5000).then(function(){});

    var lines = element.all(by.css('#leftmenuinnerinner>a'));
    lines.count().then(function(counting){
        console.log("There are total "+counting+" links");
        counter=counter+counting;
        return counting;
    })
    lines.getText().then(function(text){

        console.log("Values:::: "+text);
        for(var k=0;k<text.length;k++){
        expect(text[k]).toContain('HTML');
        }
    })
    })
})

I know i could use the xpath values & iterate through a loop of 76 values only but i am trying via a approach of css selector & i need to strictly get the entire list of values, so is there a way i could trim or scrape off the values 'HTTP Messages','HTTP Methods','PX to EM Converter' & 'Keyboard Shortcuts' dynamically through my code from the array returned so that my assertion passes ?

Body:
You can use the filter method to only keep the elements containing the text you want. - http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.filter

lines.filter(function(elem, index) {
  return elem.getText().then(function(text) {
    return text.includes('HTML');
  });
})

Or you can use the cssContainingText locator to get the desired elements. - http://www.protractortest.org/#/api?view=ProtractorBy.prototype.cssContainingText

var lines = element.all(by.cssContainingText('#leftmenuinnerinner>a','HTML'));


问:
How to draw a line with mixed or multi color in android?
I don't need a solid line of drawings. I just need how to draw a line with mixed color or multi color in Android.</p>

答:
try this one

multicolor.xml

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:type="linear"
android:centerX="44%"
android:startColor="#FF00ff00"
android:centerColor="#FFFF0000"
android:endColor="#FFffff00"
android:angle="90"/>
</shape>
</code>```

line.xml

```<code><View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="@drawable/multicolor" />
</code>```

Body:
try this one

multicolor.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:type="linear"
android:centerX="44%"
android:startColor="#FF00ff00"
android:centerColor="#FFFF0000"
android:endColor="#FFffff00"
android:angle="90"/>
</shape>

line.xml

<View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="@drawable/multicolor" />


问:
Why does Eclipse complain about @Override on interface methods?
I have an existing project that uses @Override on methods that override interface methods, rather than superclass methods. I cannot alter this in code, but I would like Eclpse to stop complaining about the annotation, as I can still build with Maven.

How would I go about disabling this error?

Note: Due to project requirements, I need to compile for Java 1.5.

答:
Even after changing the compiler compliance setting to 1.6 or 1.7 from
  windows tab, then prefernces, then java, then compiler and setting the
  compiler compliance, I was still having this issue. The idea is that we
  need to go the the project folder, right click, Java and set compiler
  compliance to 1.6 or higer. This worked for me.</p>


问:
How to change navigation bar name and icons dynamically on each page based on url ? Angular 2
I need to change the navigation bar names and icons dynamically based on the page URL.

Here is my code:

```<code> <nav id="brand" class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
    <div class="navbar-header">
        <div class="navbar-brand">
            <img src="{{wifiStatusIcon}}" class="wifiStatusIcon">

        </div>
    </div>
    <div id="navbar" class="collapse navbar-collapse">

        <ul class="nav navbar-nav">
            <li><a href="" [routerLink]="['/materials']"> <h3 class="pageName"  ng-bind="$root.name">{{title}} </h3>  </a></li>
            <li><a class="headerIconATag"><img class="headerIcon" src="{{headerIcon}}"></a></li>
        </ul>
    </div>
    <!--/.nav-collapse -->
</div>
</code>```

答:
Attach click event on all links and call component function ,in that function change all your binded variable like status icon,wifiicon

```<code><ul class="nav navbar-nav">
        <li><a href="" [routerLink]="['/materials']"  (click)='routeChange("/materials")' > <h3 class="pageName"  ng-bind="$root.name">{{title}} </h3>  </a></li>
        <li><a class="headerIconATag"><img class="headerIcon" src="{{headerIcon}}"></a></li>
    </ul>
</code>```

In Component create a function named routeChange

```<code>routeChange(route:string){
      if(route==="\material"){
       this.wifiStatusIcon ="icon/"
    }else{
       this.wifiStatusIcon ="icon2"
     }
}
</code>```

Body:
I need to change the navigation bar names and icons dynamically based on the page URL.

Here is my code:

{{title}}

Body:
Attach click event on all links and call component function ,in that function change all your binded variable like status icon,wifiicon

<ul class="nav navbar-nav">
        <li><a href="" [routerLink]="['/materials']"  (click)='routeChange("/materials")' > <h3 class="pageName"  ng-bind="$root.name">{{title}} </h3>  </a></li>
        <li><a class="headerIconATag"><img class="headerIcon" src="{{headerIcon}}"></a></li>
    </ul>

In Component create a function named routeChange

routeChange(route:string){
      if(route==="\material"){
       this.wifiStatusIcon ="icon/"
    }else{
       this.wifiStatusIcon ="icon2"
     }
}


问:
Get most common column for each column value
I want the most common letter for each number. I've tried a variety of things; not sure what's the right way.

```<code>import pandas as pd
from pandas import DataFrame, Series

original = DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}
})

expected = DataFrame({'most_common_letter': {'01': 'A', '02': 'B'}})
</code>```

Ideally I'm looking to maximize readability.

答:
```<code>>>> df = pd.DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}})
>>> df['most_common_letter']=df.groupby('number')['letter'].transform(max)
>>> df = df.iloc[:,1:].drop_duplicates().set_index('number')
>>> df.index.name = None
>>> df
   most_common_letter
01                  A
02                  B
</code>```

Or this way if it helps readability:

```<code>>>> df['most_common_letter']=df.groupby('number')['letter'].transform(max)
>>> df = df.drop('letter', axis=1).drop_duplicates().rename({'number': None}).set_index('number')
>>> df
   most_common_letter
01                  A
02                  B
</code>```

Body:
I want the most common letter for each number. I've tried a variety of things; not sure what's the right way.

import pandas as pd
from pandas import DataFrame, Series

original = DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}
})

expected = DataFrame({'most_common_letter': {'01': 'A', '02': 'B'}})

Ideally I'm looking to maximize readability.

Body:
>>> df = pd.DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}})
>>> df['most_common_letter']=df.groupby('number')['letter'].transform(max)
>>> df = df.iloc[:,1:].drop_duplicates().set_index('number')
>>> df.index.name = None
>>> df
   most_common_letter
01                  A
02                  B

Or this way if it helps readability:

>>> df['most_common_letter']=df.groupby('number')['letter'].transform(max)
>>> df = df.drop('letter', axis=1).drop_duplicates().rename({'number': None}).set_index('number')
>>> df
   most_common_letter
01                  A
02                  B


问:
Python - How can I find out if a specific XML node is present using Python?
Here is a sample of some XML code I have:

```<code><VAST version="2.0">
<Ad id="602678">
<InLine>
<AdSystem>Acudeo Compatible</AdSystem>
<AdTitle>NonLinear Test Campaign 1</AdTitle>
<Description>NonLinear Test Campaign 1</Description>
<Creatives>
<Creative AdID="602678-NonLinear">
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>
</code>```

This XML is served online so I hit a specific URL in order to get this data back. However, in some cases, nothing is returned so I am looking for a way to verify whether or not the "Creatives" node is present in whatever is returned at any given time. I have tried BeautifulSoup with no luck but I think that is more for HTML rather than XML. Any help is greatly appreciated, thanks.

答:
You can also use XPath</p>

```<code>from lxml import etree

f = StringIO(YOURS_XML)
tree = etree.parse(f)

creatives_node = tree.xpath('/Creatives')
</code>```

Body:
Here is a sample of some XML code I have:

<VAST version="2.0">
<Ad id="602678">
<InLine>
<AdSystem>Acudeo Compatible</AdSystem>
<AdTitle>NonLinear Test Campaign 1</AdTitle>
<Description>NonLinear Test Campaign 1</Description>
<Creatives>
<Creative AdID="602678-NonLinear">
</Creative>
</Creatives>
</InLine>
</Ad>
</VAST>

This XML is served online so I hit a specific URL in order to get this data back. However, in some cases, nothing is returned so I am looking for a way to verify whether or not the "Creatives" node is present in whatever is returned at any given time. I have tried BeautifulSoup with no luck but I think that is more for HTML rather than XML. Any help is greatly appreciated, thanks.

Body:
You can also use XPath

from lxml import etree

f = StringIO(YOURS_XML)
tree = etree.parse(f)

creatives_node = tree.xpath('/Creatives')


问:
Effect of ffmpeg "-clev" and "-slev" switches on non-surround audio
Do the -clev and -slev switches have any effect on non-surround audio (e.g., mono and stereo) or are they safely ignored in the absence of the center and surround channels?

答: Yes, the functions that make of these switches check for the presence of a center or side/back channels, correspondingly.</p>


问:
Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

```<code>private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

答:
User has to on the location service manually. Here is the code.Use the following method to turn on location services. Also place manifest permissions

```<code> public void checkLocationService() {
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }

    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    if (!gps_enabled && !network_enabled) {
        // notify user
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("GPS Not Enabled");
        dialog.setCancelable(false);
        dialog.setPositiveButton("Set", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(myIntent);
                //get gps
            }
        });
        dialog.setNegativeButton("Skip", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
        dialog.show();
    }
}
</code>```

Permissions:

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
 />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

Body:
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

Body:
User has to on the location service manually. Here is the code.Use the following method to turn on location services. Also place manifest permissions

 public void checkLocationService() {
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }

    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    if (!gps_enabled && !network_enabled) {
        // notify user
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("GPS Not Enabled");
        dialog.setCancelable(false);
        dialog.setPositiveButton("Set", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub
                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(myIntent);
                //get gps
            }
        });
        dialog.setNegativeButton("Skip", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

            }
        });
        dialog.show();
    }
}

Permissions:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
 />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


问:
Drools updating rules dynamically
I am working on a requirement on updating rule dynamically. I have scheduler which picks rules from DB once in every one hour. The requirement is to discard the previously loaded rules entirely with the new set of rules read from DB.

Currently i have initialized the file system and that gets reinitialized every time the scheduler reads the rules every time.

```<code>private KieServices kieServices = KieServices.Factory.get();
private KieFileSystem  kieFileSystem = kieServices.newKieFileSystem();

public reinitialize() {
    kieServices = KieServices.Factory.get();
    kieFileSystem = kieServices.newKieFileSystem();
}
</code>```

But i am not sure if this is a good approach. What i have read from Drools documentation is, the rules are written as a library with a POM file. I am not sure if this approach will end of with lots of in memory file system and at the end system will be very slow.

Can someone suggest the right way to replace the old rules with new rules dynamically?

答: To load/update rules dynamically at runtime you can use KieScanner API's. Its maven based approach, once updated kjar is available in maven repository client will pick latest version of kjar and updated rules will be executed. Go through document for more details on this approach.</p>

Title: Drools updating rules dynamically

Body:
I am working on a requirement on updating rule dynamically. I have scheduler which picks rules from DB once in every one hour. The requirement is to discard the previously loaded rules entirely with the new set of rules read from DB.

Currently i have initialized the file system and that gets reinitialized every time the scheduler reads the rules every time.

private KieServices kieServices = KieServices.Factory.get();
private KieFileSystem  kieFileSystem = kieServices.newKieFileSystem();

public reinitialize() {
    kieServices = KieServices.Factory.get();
    kieFileSystem = kieServices.newKieFileSystem();
}

But i am not sure if this is a good approach. What i have read from Drools documentation is, the rules are written as a library with a POM file. I am not sure if this approach will end of with lots of in memory file system and at the end system will be very slow.

Can someone suggest the right way to replace the old rules with new rules dynamically?


问:
Link within a text in another column php
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.</p>

```<code> echo "<b><h4>{$list["updates1"]}<a>{$list["link1"]}</a></b></h4><hr>";
</code>```

答:
in php you can go through

```<code>echo "<b><h4><a href='".$list["link1"]."'>".$list['updates1']."</a></b></h4><hr>";
</code>```

Body:
I am trying to create a link within a text, I have 2 columns in my table (updates1) and (link1) updates 1 contains a text while link 1 contains a link. The problem is whenever im trying to call it the data or the link itself is being an output besides the text. I need it to be stored inside the text.

 echo "
{$list["updates1"]}{$list["link1"]}

";

Body:
in php you can go through

echo "<b><h4><a href='".$list["link1"]."'>".$list['updates1']."</a></b></h4><hr>";


问:
Is Drupal 6 is compatible with PHP 7?
I have a website in Drupal 6 version. But now I wanted to change the server and php version to 7.

So just wanted to confirm that is Drupal 6 is compatible with PHP 7?

答:
Apparently it is not a good idea : https://www.drupal.org/node/2735435

Drupal 6 support was dropped before php 7 release and if you add to that the contribued modules wich might be totally incompatible, the cost of going to php 7 will not be light.

It might be easier to go from drupal 6 to 7 (not much changed btw these 2 versions) or if you have more time to remake your site go for drupal 8 (drupal 7 and 8 are compatible php7, drupal 7 might have some contribued modules that are not compatibles).

Title: Is Drupal 6 is compatible with PHP 7?


问:
Sum of properties in an object array AngularJS
I am fairly new to both angularjs and javascript and am in need of some guidance. I am making an application which records time logs for a project. One of the columns needs to be delta time - the time difference between starting a log and finishing it and taking away interval time (for example if I started a project at 1pm, finished at 3pm but had a 30 minute break inbetween the delta time would be 2 & 1/2 hours).
Here is my code so far, whatever I try do either comes up with the wrong time or NaN. Any help would be appreciated!

View:

```<code><div class="main" ng-controller="MainController">
  <div class="container-fluid">

    <div class="header">
  <div class="container-fluid">
    <h1>{{ title }}</h1>
  </div>
</div>

    <div class="row container-fluid">
        <!--<div class="col-md-4">-->
            <div class="panel panel-default">
                <div class="panel-body">
                    <!--<<form ng-submit="addNew(timeLogs)" >-->
                    <form>

                        <div class="form-group col-md-6">
                            <label>Project</label>
                            <input type="text" class="form-control" placeholder="Project" ng-model="project" >
                        </div>

                        <div class="form-group col-md-6">
                            <label>Phase</label>
                            <input type="text" class="form-control" placeholder="Phase" ng-model="phase" >
                        </div>

                        <div class="form-group col-md-6">
                            <label>Date</label>
                            <input type="date" class="form-control" placeholder="dd-MM-yyyy" ng-model="date" >
                        </div>

                        <div class="form-group col-md-6">
                            <label>Start Time</label>
                            <input type="time" class="form-control" placeholder="HH:mm:ss" ng-model="startTime" required>
                        </div>

                        <div class="form-group col-md-6">
                            <label>Interval Time (mins)</label>
                            <input type="text" class="form-control without" placeholder="Int Time" ng-model="intTime" >
                        </div>

                        <div class="form-group col-md-6">
                            <label>End Time</label>
                            <input type="time" class="form-control" placeholder="HH:mm:ss" ng-model="endTime" required>
                        </div>

                        <div class="form-group col-md-6">
                            <label>Comments</label>
                            <input type="text" class="form-control" placeholder="Comments" ng-model="comments" >
                        </div>

                            <button ng-click="addLog()">Add</button>

                    </form>
                </div>
            </div>
        <!--</div>-->
    </div>

    <table class="table table-striped col-md-4">
      <tr>
        <th>Project</th>
        <th>Phase</th>
        <th>Date</th>
        <th>Start Time</th>
        <th>Int Time (mins)</th>
        <th>Stop Time</th>
        <th>Delta Time</th>
        <th>Comments</th>
        <th>Make Changes</th>
      </tr>
      <tr data-ng-repeat="log in logs">
        <td>{{ log.project }}</td>
        <td>{{ log.phase }}</td>
        <td>{{ log.date | date:'dd/MM/yyyy' }}</td>
        <td>{{ log.startTime | date:'hh:mma' }}</td>
        <td>{{ log.intTime }}</td>
        <td>{{ log.endTime | date:'hh:mma' }}</td>
        <td>{{ log.startTime -- log.endTime | date:'hh:mma' }}</td>
        <td>{{ log.comments }}</td>
        <td>
          <button class="btn btn-primary" ng-click="main.editClickHandler(item)">Edit</button>
          <button class="btn btn-danger" ng-click="main.removeClickHandler(item)">Remove</button>
        </td>
      </tr>
    </table>

  </div>
</div>

<!-- Modules -->
<script src="js/app.js"></script>

<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
</code>```

Controller:

```<code>app.controller('MainController', ['$scope', function($scope) {
 $scope.title = 'Time Log';
 //$scope.promo = 'The most popular books this month.';

 $scope.logs = [];

 $scope.addLog = function() {

  $scope.logs.push({
   project: $scope.project,
   phase: $scope.phase,
   date: $scope.date,
   startTime: $scope.startTime,
   intTime: $scope.intTime,
   endTime: $scope.endTime,
   comments: $scope.comments
  });

  // Clear input fields after push
  $scope.project = "";
  $scope.phase = "";
  $scope.date = "";
  $scope.startTime = "";
  $scope.intTime = "";
  $scope.endTime = "";
  $scope.comments = "";
 };

 $scope.deltaTime = function(logs) {

  return $scope.startTime - $scope.endTime;

  ;
 }
}]);
</code>```

答:
Try like this  </p>

```<code>$scope.deltaTime = function(logs) {
      return new Date($scope.startTime) - new Date($scope.endTime);
     }
</code>```

Body:
I am fairly new to both angularjs and javascript and am in need of some guidance. I am making an application which records time logs for a project. One of the columns needs to be delta time - the time difference between starting a log and finishing it and taking away interval time (for example if I started a project at 1pm, finished at 3pm but had a 30 minute break inbetween the delta time would be 2 & 1/2 hours).
Here is my code so far, whatever I try do either comes up with the wrong time or NaN. Any help would be appreciated!

View:

{{ title }}

                    <form>

                            Project
                            <input type="text" class="form-control" placeholder="Project" ng-model="project" >

                            Phase
                            <input type="text" class="form-control" placeholder="Phase" ng-model="phase" >

                            Date
                            <input type="date" class="form-control" placeholder="dd-MM-yyyy" ng-model="date" >

                            Start Time
                            <input type="time" class="form-control" placeholder="HH:mm:ss" ng-model="startTime" required>

                            Interval Time (mins)
                            <input type="text" class="form-control without" placeholder="Int Time" ng-model="intTime" >

                            End Time
                            <input type="time" class="form-control" placeholder="HH:mm:ss" ng-model="endTime" required>

                            Comments
                            <input type="text" class="form-control" placeholder="Comments" ng-model="comments" >

                            <button ng-click="addLog()">Add</button>

                    </form>

        Project
        Phase
        Date
        Start Time
        Int Time (mins)
        Stop Time
        Delta Time
        Comments
        Make Changes

        {{ log.project }}
        {{ log.phase }}
        {{ log.date | date:'dd/MM/yyyy' }}
        {{ log.startTime | date:'hh:mma' }}
        {{ log.intTime }}
        {{ log.endTime | date:'hh:mma' }}
        {{ log.startTime -- log.endTime | date:'hh:mma' }}
        {{ log.comments }}

          <button class="btn btn-primary" ng-click="main.editClickHandler(item)">Edit</button>
          <button class="btn btn-danger" ng-click="main.removeClickHandler(item)">Remove</button>

Controller:

app.controller('MainController', ['$scope', function($scope) {
 $scope.title = 'Time Log';
 //$scope.promo = 'The most popular books this month.';

 $scope.logs = [];

 $scope.addLog = function() {

  $scope.logs.push({
   project: $scope.project,
   phase: $scope.phase,
   date: $scope.date,
   startTime: $scope.startTime,
   intTime: $scope.intTime,
   endTime: $scope.endTime,
   comments: $scope.comments
  });

  // Clear input fields after push
  $scope.project = "";
  $scope.phase = "";
  $scope.date = "";
  $scope.startTime = "";
  $scope.intTime = "";
  $scope.endTime = "";
  $scope.comments = "";
 };

 $scope.deltaTime = function(logs) {

  return $scope.startTime - $scope.endTime;

  ;
 }
}]);

Body:
Try like this

$scope.deltaTime = function(logs) {
      return new Date($scope.startTime) - new Date($scope.endTime);
     }


问:
Renderer is deprecated as a favor for renderer2, alternative for `invokeElementMethod`?
For a side project of mine, I want to implement a chat stream where new message is added to the bottom and the windows should scroll to the bottom to display the latest message.

In order to do that, I have opted to use ViewChildren on the component to find the last message(latest) and use scrollIntoView on the nativeElement.

In order not to call the method by accessing the DOM API directly nativeElement.scrollIntoView(). I believe I will need to use renderer.invokeElementMethod(nativeElement, 'scrollIntoView').

Problem is renderer is deprecated in favor of renderer2 and I cant seem to find alternative for the method invokeElementMethod in renderer2.

Question is, is there a method that I missed in renderer2 that do just that? or we have a new way doing invoking element method now?

答:
You can use selectRootElement method of Renderer2.

For example:

```<code>constructor(private renderer: Renderer2) {}

this.renderer.selectRootElement('#domElementId').scrollIntoView()
</code>```

, where domElementId is id='domElementId' in your html

UPDATE

Supply a Second Argument for selectRootElement as per Angular's Official Documentation as it is used to preserve your content

selectRootElement(selectorOrNode: any, preserveContent?: boolean): any

```<code>this.renderer
  .selectRootElement'#domElementId', true)  // Supply true for the 2nd arg to make sure your content is preserved.
  .scrollIntoView()                      // Or ({ behavior: 'smooth' }) for smooth scrolling
</code>```

Body:
You can use selectRootElement method of Renderer2.

For example:

constructor(private renderer: Renderer2) {}

this.renderer.selectRootElement('#domElementId').scrollIntoView()

, where domElementId is id='domElementId' in your html

UPDATE

Supply a Second Argument for selectRootElement as per Angular's Official Documentation as it is used to preserve your content

selectRootElement(selectorOrNode: any, preserveContent?: boolean): any

this.renderer
  .selectRootElement'#domElementId', true)  // Supply true for the 2nd arg to make sure your content is preserved.
  .scrollIntoView()                      // Or ({ behavior: 'smooth' }) for smooth scrolling


问:
Windows Mobile - Low Level Format (Hard Reset) C#
How to Format(Hard Reset) Windows mobile using C# and .NETCF 2.0?</p>

答:
In earlier versions of Pocket PC you could make a call to KernelIoControl of ExitWindowsEx. Since WinMo 5.0, though, those calls can no longer hard reset the device.

My guess is that since users rarely will want their device hard reset, and if they do they want to be the ones to initiate that reset, any mechanism to do it programmatically (i.e. from a malicious piece of code) was removed.


问:
For PHP REST API, how can I define/set the database connection parameters outside the class definition?
I'm using the PHP REST API example that appears all over the web. Here's basically what it is:

```<code><?php

    require_once("Rest.inc.php");

    class API extends REST {

        const DB_SERVER     = "myhost";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        public $data = "";
        private $db = NULL;

        public function __construct(){
            parent::__construct();
            $this->dbConnect();
        }

        private function dbConnect(){

            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }

        public function processApi(){

            $func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));

            if((int)method_exists($this,$func) > 0) {
                $this->$func();
            } else {
                $this->response('',404);
            }

        }

        private function activity(){
            ...
        }

        private function client(){
            ...
        }

        private function facility(){
            ...
        }

        etc...

        private function json($data){
            if(is_array($data)){
                return json_encode($data);
            }
        }
    }

    // Initiiate Library

    $api = new API;
    $api->processApi();

?>
</code>```

It works fine, except that I don't want to hardcode the database connection parameters in that script. What is the best way (or is there a way) to separate them from this script? I can't use an include file inside the class declaration. Can I put the whole dbConnect() function in an include file, and include that outside the class definition? Any other options? I just want it so that there is nothing tying this script to a specific server. I would prefer to have the db server defined in a separate file that could be different on each server. I'm new to PHP and just wondering how the experts handle this.

**Edit: Got it working! This is a bit of a hybrid of the supplied answers.

dbConnect.php

```<code><?php
    class DB {

        const DB_SERVER     = "myserver";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        private $db = null;

        public function __construct() {
            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }
    }
?>
</code>```

api.php

```<code><?php

    require_once("Rest.inc.php");
    require_once("dbConnect.php");

    class API extends REST {
        public $data = "";
        private $db = null;

        public function __construct(DB $mydb){
            parent::__construct();
            $this->db = mydb->db;
        }
    }

    // Initiiate Library

    $api = new API(new DB());
    $api->processApi();

?>
</code>```

答:
You need to use Dependency Injection pattern, it will help you. And you will have something like this:

```<code>interface DB
{
    // Here you need to declare your common methods for all DB classes.
}

class MasterDB implements DB
{
    const DB_SERVER     = "myhost";
    const DB_USER       = "myuser";
    const DB_PASSWORD   = "mypassword";
    const DB_NAME       = "mydb";

    private $db = null;

    private function __construct()
    {
        try {
            $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }
    }
}

class SlaveDB implements DB
{
    // Here you need to provide another connection
}

class API extends REST
{
    private $db = null;

    public function __construct(DB $db)
    {
        parent::__construct();
        $this->db = $db;
    }
}

$api = new API(new MasterDB());
// or
$api = new API(new SlaveDB());
$api->processApi();
</code>```

It is not a perfect example, but this one will help you solve your problem! Next step probably is - create parent or abstract class for MasterDB and SlaveDB...

Body:
I'm using the PHP REST API example that appears all over the web. Here's basically what it is:

<?php

    require_once("Rest.inc.php");

    class API extends REST {

        const DB_SERVER     = "myhost";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        public $data = "";
        private $db = NULL;

        public function __construct(){
            parent::__construct();
            $this->dbConnect();
        }

        private function dbConnect(){

            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }

        public function processApi(){

            $func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));

            if((int)method_exists($this,$func) > 0) {
                $this->$func();
            } else {
                $this->response('',404);
            }

        }

        private function activity(){
            ...
        }

        private function client(){
            ...
        }

        private function facility(){
            ...
        }

        etc...

        private function json($data){
            if(is_array($data)){
                return json_encode($data);
            }
        }
    }

    // Initiiate Library

    $api = new API;
    $api->processApi();

?>

It works fine, except that I don't want to hardcode the database connection parameters in that script. What is the best way (or is there a way) to separate them from this script? I can't use an include file inside the class declaration. Can I put the whole dbConnect() function in an include file, and include that outside the class definition? Any other options? I just want it so that there is nothing tying this script to a specific server. I would prefer to have the db server defined in a separate file that could be different on each server. I'm new to PHP and just wondering how the experts handle this.

**Edit: Got it working! This is a bit of a hybrid of the supplied answers.

dbConnect.php

<?php
    class DB {

        const DB_SERVER     = "myserver";
        const DB_USER       = "myuser";
        const DB_PASSWORD   = "mypassword";
        const DB_NAME       = "mydb";

        private $db = null;

        public function __construct() {
            try {
                $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
        }
    }
?>

api.php

<?php

    require_once("Rest.inc.php");
    require_once("dbConnect.php");

    class API extends REST {
        public $data = "";
        private $db = null;

        public function __construct(DB $mydb){
            parent::__construct();
            $this->db = mydb->db;
        }
    }

    // Initiiate Library

    $api = new API(new DB());
    $api->processApi();

?>

Body:
You need to use Dependency Injection pattern, it will help you. And you will have something like this:

interface DB
{
    // Here you need to declare your common methods for all DB classes.
}

class MasterDB implements DB
{
    const DB_SERVER     = "myhost";
    const DB_USER       = "myuser";
    const DB_PASSWORD   = "mypassword";
    const DB_NAME       = "mydb";

    private $db = null;

    private function __construct()
    {
        try {
            $this->db = new PDO("mysql:host=" . self::DB_SERVER . ";dbname=" . self::DB_NAME, self::DB_USER, self::DB_PASSWORD);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            echo "Connection failed: " . $e->getMessage();
        }
    }
}

class SlaveDB implements DB
{
    // Here you need to provide another connection
}

class API extends REST
{
    private $db = null;

    public function __construct(DB $db)
    {
        parent::__construct();
        $this->db = $db;
    }
}

$api = new API(new MasterDB());
// or
$api = new API(new SlaveDB());
$api->processApi();

It is not a perfect example, but this one will help you solve your problem! Next step probably is - create parent or abstract class for MasterDB and SlaveDB...