问:
Counting Words in vector
Currently I have enrolled in a R course and one of the practice exercises is building a R program to count words in a string. We cannot use the function table but must return an output of the most popular word in a string using conventional means.
i.e. The fox jumped over the cone and the...
So the program would have to return "the" as it is the most popular phrase.

So far I have the following:

```<code>string_read<- function(phrase) {

  phrase <- strsplit(phrase, " ")[[1]]
  for (i in 1:length(phrase)){
    phrase.freq <- ....
#if Word already exists then increase counter by 1

      }
</code>```

I've hit a road block however as I'm not sure how to increase the counter for specific words. Can anyone give me a pointer in the right direction? My psuedo code would be something like: "For every word that is looped through, increase wordIndex by 1. If word has already occured before, increase wordIndex counter."

答:
You started off correctly by splitting the string into words, then we loop over each word using sapply and sum the similar words in the vector. I have used tolower assuming this operation is not case sensitive.

```<code>string_read<- function(phrase) {
   temp = tolower(unlist(strsplit(phase, " ")))
   which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"

string_read(phrase)
#the
#  1
</code>```

This returns output as the word and its index position which is 1 in this case. If you just want the word with maximum count , you can change the last line to

```<code>temp[which.max(sapply(temp, function(x) sum(x == temp)))]
</code>```

Title: Counting Words in vector

Body:
Currently I have enrolled in a R course and one of the practice exercises is building a R program to count words in a string. We cannot use the function table but must return an output of the most popular word in a string using conventional means.
i.e. The fox jumped over the cone and the...
So the program would have to return "the" as it is the most popular phrase.

So far I have the following:

string_read<- function(phrase) {

  phrase <- strsplit(phrase, " ")[[1]]
  for (i in 1:length(phrase)){
    phrase.freq <- ....
#if Word already exists then increase counter by 1

      }

I've hit a road block however as I'm not sure how to increase the counter for specific words. Can anyone give me a pointer in the right direction? My psuedo code would be something like: "For every word that is looped through, increase wordIndex by 1. If word has already occured before, increase wordIndex counter."

Body:
You started off correctly by splitting the string into words, then we loop over each word using sapply and sum the similar words in the vector. I have used tolower assuming this operation is not case sensitive.

string_read<- function(phrase) {
   temp = tolower(unlist(strsplit(phase, " ")))
   which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"

string_read(phrase)
#the
#  1

This returns output as the word and its index position which is 1 in this case. If you just want the word with maximum count , you can change the last line to

temp[which.max(sapply(temp, function(x) sum(x == temp)))]


来源: stackexchange

问:
Select2 - Trigger open on click without library function for open
i'm using this library: https://select2.github.io

When you use this library and you want to force your select menu to open programmatically you run the following:

```<code>$('#fromAccIdx').select2('open');
</code>```

and the select menu opens.

However if you run:

```<code>$('#fromAccIdx').click();
</code>```

to simulate the click which is opening the menu it's not working like it's working with the mouse on this element.

I would like to know how can i open the select menu without using the open() function from the library itself.

Is it possible ?

答:
Try this. it works.

```<code> document.getElementById("fromAccIdx").click();
</code>```

Instead of $('#fromAccIdx').click();

ContentLicense: CC BY-SA 3.0

Body:
i'm using this library: https://select2.github.io

When you use this library and you want to force your select menu to open programmatically you run the following:

$('#fromAccIdx').select2('open');

and the select menu opens.

However if you run:

$('#fromAccIdx').click();

to simulate the click which is opening the menu it's not working like it's working with the mouse on this element.

I would like to know how can i open the select menu without using the open() function from the library itself.

Is it possible ?

Body:
Try this. it works.

 document.getElementById("fromAccIdx").click();

Instead of $('#fromAccIdx').click();


问:
How to return this result using linq in entity framework( 2 foreign key mapping table)
I have a table that contains 2 foreign key that reference separately to 2 different table.
I would like to return the result of all person that has course of "Science".

How to retrieve the record back using LINQ?
This is what i gotten so far:

```<code>       return
        _ctx.Person
            .Include(u => u.Course
            .Where(ug=>ug.CourseName== "Science"));
</code>```

This is not working as it shows the error.

The Include path expression must refer to a navigation property
  defined on the type

```<code>public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Courses { get; set; }
}
</code>```

This is the mapping table. Only contains 2 foreign key from 2 different table.
I could not use this table inside the solution.As the code first won't generate this table as it doesn't contain it's own PK.

```<code>//This is not shown in the EntityFramework when generating Code First.
    public class PersonCouseMap
    {
      public int PersonID {get; set;}
      public int CourseID {get; set;}
    }
</code>```

Update : this works after I switched the entity.

```<code>return _ctx.Course
       .Include(u=>u.Person)
       .Where(ug=>ug.CourseName == "Sciene");
</code>```

Anyone can explain why it won't work the another way round.
I need to display a List of Person who have course of "Science",
not Course Science that has a list of user.

答:
Include Foreign Key Mapping</p>

```<code>public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}
    public virtual ICollection<Person> Person {get; set}
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Course {get; set;}
}

using System.ComponentModel.DataAnnotation.Schema;
public class PersonCouseMap
{
   [ForeignKey("Person")]
   public int PersonID {get; set;}
   [ForeignKey("Course")]
   public int CourseID {get; set;}

   public virtual ICollection<Person> Person {get; set;}
   public virtual ICollection<Course> Course {get; set;}
}
</code>```

Body:
I have a table that contains 2 foreign key that reference separately to 2 different table.
I would like to return the result of all person that has course of "Science".

How to retrieve the record back using LINQ?
This is what i gotten so far:

       return
        _ctx.Person
            .Include(u => u.Course
            .Where(ug=>ug.CourseName== "Science"));

This is not working as it shows the error.

The Include path expression must refer to a navigation property
  defined on the type

public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Courses { get; set; }
}

This is the mapping table. Only contains 2 foreign key from 2 different table.
I could not use this table inside the solution.As the code first won't generate this table as it doesn't contain it's own PK.

//This is not shown in the EntityFramework when generating Code First.
    public class PersonCouseMap
    {
      public int PersonID {get; set;}
      public int CourseID {get; set;}
    }

Update : this works after I switched the entity.

return _ctx.Course
       .Include(u=>u.Person)
       .Where(ug=>ug.CourseName == "Sciene");

Anyone can explain why it won't work the another way round.
I need to display a List of Person who have course of "Science",
not Course Science that has a list of user.

Body:
Include Foreign Key Mapping

public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}
    public virtual ICollection<Person> Person {get; set}
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Course {get; set;}
}

using System.ComponentModel.DataAnnotation.Schema;
public class PersonCouseMap
{
   [ForeignKey("Person")]
   public int PersonID {get; set;}
   [ForeignKey("Course")]
   public int CourseID {get; set;}

   public virtual ICollection<Person> Person {get; set;}
   public virtual ICollection<Course> Course {get; set;}
}


问:
How to create a conditional end of a string?
I'm generating a string like this:

```<code>if (_.includes(api.historyModeServers, api.env)) {
  return api.viewerUrl + '/' + this.building.sharecode + '?ui=true'
} else {
  return api.viewerUrl + '/#!/' + this.building.sharecode + '?ui=true'
}
</code>```

How can I make the ?ui=true conditional? Say like if hasUi add that part and if not don't add it?

答:
You could use a conditional (ternary) operator ?:

```<code>string += hasUi ? '?ui=true' : '';
</code>```

Body:
I'm generating a string like this:

if (_.includes(api.historyModeServers, api.env)) {
  return api.viewerUrl + '/' + this.building.sharecode + '?ui=true'
} else {
  return api.viewerUrl + '/#!/' + this.building.sharecode + '?ui=true'
}

How can I make the ?ui=true conditional? Say like if hasUi add that part and if not don't add it?

Body:
You could use a conditional (ternary) operator ?:

string += hasUi ? '?ui=true' : '';


问:
"File Not Found" while trying to compile an RC file (probably dumb mistake)
Following these steps for adding a UAC manifest to my C# project embedded as a resource.

Step 1 works fine, I create the RC file in my project as a simple text file as described.

```<code>#include <winuser.h>
#define IDR_MANIFEST 1 // 2 for a DLL

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
{
 "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
   <asmv3:trustInfo xmlns:asmv3=""urn:schemas-microsoft-com:asm.v3"">
     <asmv3:security>
       <asmv3:requestedPrivileges>
         <asmv3:requestedExecutionLevel
           level=""asInvoker""
           uiAccess=""false"" />
       </asmv3:requestedPrivileges>
     </asmv3:security>
   </asmv3:trustInfo>
  </assembly>"
}
</code>```

Then using the Visual Studio Command Prompt, I get the following output at step 2:

```<code>  c:\myproject>rc MyResourceFile.rc
  Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
  Copyright (C) Microsoft Corporation.  All rights reserved.

  ConfigurationManager.rc(4) : error RC2135 : file not found: 1
</code>```

I assume this is something quite dumb, right?

答: No repro, I don't see anything wrong.  The C# compiler already embeds a UAC manifest into the assembly since VS2008 (possibly VS2005 SP1 for Vista).  If you want to modify it then use Project + Add New Item and select the "Application Manifest File" item template.</p>

ContentLicense: CC BY-SA 2.5

Body:
Following these steps for adding a UAC manifest to my C# project embedded as a resource.

Step 1 works fine, I create the RC file in my project as a simple text file as described.

#include <winuser.h>
#define IDR_MANIFEST 1 // 2 for a DLL

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
{
 "<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
   <asmv3:trustInfo xmlns:asmv3=""urn:schemas-microsoft-com:asm.v3"">
     <asmv3:security>
       <asmv3:requestedPrivileges>
         <asmv3:requestedExecutionLevel
           level=""asInvoker""
           uiAccess=""false"" />
       </asmv3:requestedPrivileges>
     </asmv3:security>
   </asmv3:trustInfo>
  </assembly>"
}

Then using the Visual Studio Command Prompt, I get the following output at step 2:

  c:\myproject>rc MyResourceFile.rc
  Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
  Copyright (C) Microsoft Corporation.  All rights reserved.

  ConfigurationManager.rc(4) : error RC2135 : file not found: 1

I assume this is something quite dumb, right?


问:
pytest function without return value
I'm trying to do a pytest on a function without return value, but obviously value is None in pytets. I was wondering if there is a solution for that?

here is function which I'm trying to test:

```<code>  def print_top_movies_url():
    for item in movie_link[:100]:
        print item.contents[1]
</code>```

答:
The best thing to do would be to separate getting the top movies and printing them.

For example, you could have a top_movie_urls which looks like this:

```<code>def top_movie_urls():
    urls = []
    for item in movie_link[:100]:
        urls.append(item.contents[1])
    return urls
</code>```

(or make it a generator function)

That's easy to test, and wherever you call it, you can now just do something like print('\n'.join(top_movie_urls())).

If you really want to test the output instead, you can use pytest's output capturing to access the output of the tested function and check that.

Title: pytest function without return value

Body:
I'm trying to do a pytest on a function without return value, but obviously value is None in pytets. I was wondering if there is a solution for that?

here is function which I'm trying to test:

  def print_top_movies_url():
    for item in movie_link[:100]:
        print item.contents[1]

Body:
The best thing to do would be to separate getting the top movies and printing them.

For example, you could have a top_movie_urls which looks like this:

def top_movie_urls():
    urls = []
    for item in movie_link[:100]:
        urls.append(item.contents[1])
    return urls

(or make it a generator function)

That's easy to test, and wherever you call it, you can now just do something like print('\n'.join(top_movie_urls())).

If you really want to test the output instead, you can use pytest's output capturing to access the output of the tested function and check that.


问:
How can make my ViewPager load only one page at a time ie setOffscreenPageLimit(0);
I understand the lowest number I can give setOffscreenPageLimit(int) is 1. but I need to load one page at a time because memory problems.

Am i going to have to use the old style tabhost etc? or is there a way/hack I can make my viewPager load one page at a time?

My Adapter extends BaseAdapter with the ViewHolder patern.

答:
I was having the same problem and I found the solution for it:

Steps:

1) First Download the CustomViewPager Class from this link.

2) Use that class as mentioned below:

In Java:

```<code>CustomViewPager mViewPager;
mViewPager = (CustomViewPager) findViewById(R.id.swipePager);
mViewPager.setOffscreenPageLimit(0);
</code>```

In XML:

```<code><com.yourpackagename.CustomViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipePager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

Now only one page will be loaded at once.

P.S: As per the question's requirement, I have posted the solution for Viewpager. I haven't tried the same with TabLayout yet. If I will find any solution for that I will update the answer.

In this file, KeyEventCompat is used it  may not be found by the Android studio because KeyEnentCompat class was deprecated in API level 26.0.0 so you need to replace  KeyEventCompat with event for more details you can view
https://developer.android.com/sdk/support_api_diff/26.0.0-alpha1/changes/android.support.v4.view.KeyEventCompat

Body:
I was having the same problem and I found the solution for it:

Steps:

1) First Download the CustomViewPager Class from this link.

2) Use that class as mentioned below:

In Java:

CustomViewPager mViewPager;
mViewPager = (CustomViewPager) findViewById(R.id.swipePager);
mViewPager.setOffscreenPageLimit(0);

In XML:

<com.yourpackagename.CustomViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipePager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Now only one page will be loaded at once.

P.S: As per the question's requirement, I have posted the solution for Viewpager. I haven't tried the same with TabLayout yet. If I will find any solution for that I will update the answer.

In this file, KeyEventCompat is used it  may not be found by the Android studio because KeyEnentCompat class was deprecated in API level 26.0.0 so you need to replace  KeyEventCompat with event for more details you can view
https://developer.android.com/sdk/support_api_diff/26.0.0-alpha1/changes/android.support.v4.view.KeyEventCompat

ContentLicense: CC BY-SA 4.0


问:
How should I approach the logic for writing the code for a more complex ng-model feature?
First, let me explain the effect I am looking for:

Layout:

Header at the top of the page that says "Choose between...".

Two input boxes below, input1 and input2

Effect

If the user begins typing first in [choice1] in input1, the header auto-updates and says "Choose between [choice 1] and..."

If the user begins typing first in [choice2] in input2, the header auto-updates and says "Choose between ___ and [choice2]"

If the user has already written in one input and begins writing in the other input, the header auto-updates and says "Choose between [choice1] and [choice2]".

Now, I have already written the angular-js code to achieve this. I am not looking for an answer on how to achieve the effect. Instead, I want to know the logic for the best way to achieve this effect because I think the way I did it could be improved.

Finally, here is the logic I used:

Create 4 divs with 4 ng-switch-when properties. Each div contains a header. First div contains header with "Choose between..." written on it. Second div contains header with "Choose between [input1text] and..." written on it. Third div contains a header with "Choose between ___ and [input2text]" written on it. Final div has "Choose between [input1text] and [input2text]" written on it. Each div has an ng-switch-when property, they are: "not-pressed", "first-pressed", "second-pressed", and "both-pressed", respectively

If someone starts typing in input1, I see if either second-pressed state or both-pressed state is currently active. If one is, I set the state to both-pressed. Otherwise, I set the state to first-pressed.

If someone starts typing in input2, I see if either first-pressed state or both-pressed state is currently active. If one is, I set the state to both-pressed. Otherwise, I set the state to second-pressed.

I think the way I wrote it is really clunky and messy and I'd like an opinion on if there is a better way to apprach the logic to this feature. Again, I am not looking for code. I just want to see if there is better logic.

答: I would assign ng-model to each of the inputs. Then have three divs for each header each referencing the required ng-model (choice1, choice 2 and both). I would then use ng-if on each of the three divs to test if the ng-model was empty for either choice or not.</p>


问:
How to debug aws lambda functions written in node js
We have been developing AWS Lambda functions in Node JS for a few months. Can we debug, i.e. step through the Node JS code as we can with .Net C# code in Visual Studio?</p>

答:
You cannot debug the lambda code like you do in VS but you can invoke some test data and check everything is fine.

You can run lambda locally in your machine using lambda-local and serverless-offline

So invoke your lambda with some test event & data and you can log and see whats happening for different inputs


问:
Maximum execution time of 30 seconds exceeded [magento] zend server
```<code>Fatal error: Maximum execution time of 30 seconds exceeded in C:\Program Files (x86)\Zend\Apache2\htdocs\tokopetaninew\branches\development\lib\Zend\Locale\Format.php on line 442
Array
(
    [type] => 1
    [message] => Maximum execution time of 30 seconds exceeded
    [file] => C:\Program Files (x86)\Zend\Apache2\htdocs\tokopetaninew\branches\development\lib\Zend\Locale\Format.php
    [line] => 442
)
</code>```

i have install magento in my localhost with zend server and port localhost:8080
and i got that error message, please help me

答:
Every script has a maximum running time ("max execution time"). Depending on your php configuration it can be several values (appearing to be 30 seconds in your case).

Your script is taking longer than this 30 seconds to execute so the server interrupts it and cancels the script giving you this error.

Possible solutions:

Modify script to be quicker

Modify your php.ini to increase execution time on your whole installation

increase script max execution time inline for just that script (see http://php.net/manual/en/function.set-time-limit.php for info)

Be careful with increasing the max execution time above a specific point tho. Keep in mind a running script will occupy one core of your server. In case you have a quad core and 4 scripts are running for five minutes your server will appear dead for that time as no requests can be taken while the others run.

Body:
Fatal error: Maximum execution time of 30 seconds exceeded in C:\Program Files (x86)\Zend\Apache2\htdocs\tokopetaninew\branches\development\lib\Zend\Locale\Format.php on line 442
Array
(
    [type] => 1
    [message] => Maximum execution time of 30 seconds exceeded
    [file] => C:\Program Files (x86)\Zend\Apache2\htdocs\tokopetaninew\branches\development\lib\Zend\Locale\Format.php
    [line] => 442
)

i have install magento in my localhost with zend server and port localhost:8080
and i got that error message, please help me


问:
Passing a function pointer as parameter to fopen
I created a small C program for creating a time stamp and append it to a file text name:

```<code>#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

void time_stamp(){
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [80];
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buffer,80,"myFile_%F.txt",timeinfo);
    printf ("%s", buffer);
}

int main ()
{
    void (*filename_ptr)();
    filename_ptr = &time_stamp;

    FILE * fp;

    fp = fopen (filename_ptr, "w+");
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}
</code>```

But I can't get fopen to accept the pointer to the function creating the name with the time stamp. It is expecting a const char. How can i cast my function pointer to it?

答:
fopen() expects a const char * as the first argument:

```<code>FILE *fopen(const char *path, const char *mode);
</code>```

In your function time_stamp() you are printing  the timestamp and returning nothing, i.e.: void.

Your new time_stamp() function could be instead (note the static at the declaration of buffer):

```<code>const char* time_stamp(){
   time_t rawtime;
   struct tm * timeinfo;
   static char buffer [80];
   time (&rawtime);
   timeinfo = localtime (&rawtime);

   strftime (buffer,80,"myFile_%F.txt",timeinfo);
   return buffer;
}
</code>```

You could then call this new function at the moment of calling fopen(). The value returned by time_stamp() will turn into the first argument of fopen():

```<code>const char * (*filename_ptr)();
filename_ptr = &time_stamp;
// ...
fp = fopen (filename_ptr(), "w+");
</code>```

Note that the type of the value returned from time_stamp() matches now the type of the first argument that fopen() expects (i.e.: const char *).

Note on thread-safety

Since the function time_stamp() contains statically allocated storage (buffer), it is unsafe to use this function in a multi-threading program, since all the threads that call this function will be sharing a single instance of this storage.

Body:
I created a small C program for creating a time stamp and append it to a file text name:

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>

void time_stamp(){
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [80];
    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buffer,80,"myFile_%F.txt",timeinfo);
    printf ("%s", buffer);
}

int main ()
{
    void (*filename_ptr)();
    filename_ptr = &time_stamp;

    FILE * fp;

    fp = fopen (filename_ptr, "w+");
    fprintf(fp, "%s %s %s %d", "We", "are", "in", 2017);

    fclose(fp);

    return 0;
}

But I can't get fopen to accept the pointer to the function creating the name with the time stamp. It is expecting a const char. How can i cast my function pointer to it?

Body:
fopen() expects a const char * as the first argument:

FILE *fopen(const char *path, const char *mode);

In your function time_stamp() you are printing  the timestamp and returning nothing, i.e.: void.

Your new time_stamp() function could be instead (note the static at the declaration of buffer):

const char* time_stamp(){
   time_t rawtime;
   struct tm * timeinfo;
   static char buffer [80];
   time (&rawtime);
   timeinfo = localtime (&rawtime);

   strftime (buffer,80,"myFile_%F.txt",timeinfo);
   return buffer;
}

You could then call this new function at the moment of calling fopen(). The value returned by time_stamp() will turn into the first argument of fopen():

const char * (*filename_ptr)();
filename_ptr = &time_stamp;
// ...
fp = fopen (filename_ptr(), "w+");

Note that the type of the value returned from time_stamp() matches now the type of the first argument that fopen() expects (i.e.: const char *).

Note on thread-safety

Since the function time_stamp() contains statically allocated storage (buffer), it is unsafe to use this function in a multi-threading program, since all the threads that call this function will be sharing a single instance of this storage.


答:
Change the max_execution_time

```<code>ini_set('max_execution_time', 300); //300 seconds = 5 minutes
</code>```

Title: Maximum execution time of 30 seconds exceeded [magento] zend server

Body:
Change the max_execution_time

ini_set('max_execution_time', 300); //300 seconds = 5 minutes


Title: Pandas - Resort Column Location

Body:
I have a pandas frame. When I print the columns (shown below), its turns out that my columns are out of order. Is there a way to sort only the first 30 columns so they are in order (30,60,90...900)?

[in]   df.columns

[out]  Index(['120', '150', '180', '210', '240', '270', '30', '300', '330', '360',
   '390', '420', '450', '480', '510', '540', '570', '60', '600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870', '90', '900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'],
  dtype='object')

The fixed frame would be as follows:

[out]  Index(['30','60','90,'120', '150', '180', '210', '240', '270','300', '330', '360',
   '390', '420', '450', '480', '510', '540', '570','600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870','900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'],
  dtype='object')

Body:
You need select first column names, convert to int and sort. Then convert back to str if necessary and use reindex_axis:

np.sort(df.columns[:30].astype(int)).astype(str).tolist() +
             df.columns[30:].tolist()

Sample:

df = pd.DataFrame(np.arange(36).reshape(1,-1),
   columns=['120', '150', '180', '210', '240', '270', '30', '300',
   '330', '360','390', '420', '450', '480', '510', '540', '570', '60', '600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870', '90', '900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'])

print (df)
   120  150  180  210  240  270  30  300  330  360     ...      840  870  90  \
0    0    1    2    3    4    5   6    7    8    9     ...       26   27  28

   900  Item  Price  Size  Time  Type  Unnamed: 0
0   29    30     31    32    33    34          35

[1 rows x 36 columns]

df = df.reindex_axis(np.sort(df.columns[:30].astype(int)).astype(str).tolist() +
                     df.columns[30:].tolist(), axis=1)
print (df)
   30  60  90  120  150  180  210  240  270  300     ...      810  840  870  \
0   6  17  28    0    1    2    3    4    5    7     ...       25   26   27

   900  Item  Price  Size  Time  Type  Unnamed: 0
0   29    30     31    32    33    34          35

[1 rows x 36 columns]


问:
Use of git tags in package.json (for git dependencies)
Is it possible some how to get update behaviour for git dependencies a like for NPM packages?

So I have git dependency:

```<code>"dependencies": {
  "my-module": "github:me/my-module"
}
</code>```

And want it be updated each time I do npm install, adding revision hash is solution but requires more work to track and update in package.json each time package is update on Github.

There are also git tags (which also can be set using npm version command - it creates commit with tag v1.2.3. Is there is way to use these tags in dependencies in package.json?

git tag on repo gives me:

```<code>v1.0.1
v1.0.0
</code>```

If I try to add in package.json after module name version like: #1.0.0 or #v1.0.1

```<code>```
"dependencies": {
"my-module": "github:me/my-module#1.0.1"
}
```
</code>```

Install fails with error:

```<code>Command failed: git -c core.longpaths=true rev-list -n1 1.0.0
fatal: ambiguous argument '1.0.0': unknown revision or path not in the
ree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

If you need help, you may report this error at:
    <https://github.com/npm/npm/issues>
</code>```

答:
I tried using git+ssh but didn't work. Finally this worked for me for repo in bitbucket</p>

```<code>"my-module": "git+https://bitbucket.org/repos/myrepo/#0.1.0"
</code>```

Body:
Is it possible some how to get update behaviour for git dependencies a like for NPM packages?

So I have git dependency:

"dependencies": {
  "my-module": "github:me/my-module"
}

And want it be updated each time I do npm install, adding revision hash is solution but requires more work to track and update in package.json each time package is update on Github.

There are also git tags (which also can be set using npm version command - it creates commit with tag v1.2.3. Is there is way to use these tags in dependencies in package.json?

git tag on repo gives me:

v1.0.1
v1.0.0

If I try to add in package.json after module name version like: #1.0.0 or #v1.0.1

```
"dependencies": {
"my-module": "github:me/my-module#1.0.1"
}
```

Install fails with error:

Command failed: git -c core.longpaths=true rev-list -n1 1.0.0
fatal: ambiguous argument '1.0.0': unknown revision or path not in the
ree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

If you need help, you may report this error at:
    <https://github.com/npm/npm/issues>

Body:
I tried using git+ssh but didn't work. Finally this worked for me for repo in bitbucket

"my-module": "git+https://bitbucket.org/repos/myrepo/#0.1.0"


问:
Windows Phone 7 Map Control with custom layer in offline mode
Hi WP7 mobile passionate developers!

I'm trying to use the default provided Bing Map control from Windows Phone controls.
Specifically I'm trying to use a custom TileSource to provide a custom made tiled map that will be stored in the project as a folder (Content files) or in isolate storage.

Down I present the custom class I try to use with map tiles/images stored in "map" folder in ZXY storage format as content files.

```<code>public class CustomTileSource : Microsoft.Phone.Controls.Maps.TileSource
{

    private string uriFormat = @"map/{0}/{1}/{2}.png";
    public string UriFormat
    {
        get { return uriFormat; }
        set { uriFormat = value; }
    }

    public override Uri GetUri(int x, int y, int zoomLevel)
    {
        var url = string.Format(UriFormat, zoomLevel, x, y);
        return new Uri(url, UriKind.Relative);
    }
}
</code>```

Trying to use this is not working and custom tiles are not shown although no error is thrown.
Does anyone tried to use windows phone map control this way?
If that's not the right approach which one is? Any workaround?

Thank you in advance!

Claudiu

答:
The Exception is:

```<code>This operation is not supported on a relative URI.
   at System.Uri.get_AbsoluteUri()
   at System.Windows.Media.MultiScaleTileSource.GetTileLayerUrl(IntPtr nativeTarget, Int32 tileLevel, Int32 tileX, Int32 tileY, Int32 uTileImageIndex, IntPtr& fullTileUri, UInt32& fullTileUriLength)
</code>```

How to get an image from IsolatedStorage, Ressource or MediaLibrary with UriKind.Absolute i not already found out
...maybe you know?

Body:
Hi WP7 mobile passionate developers!

I'm trying to use the default provided Bing Map control from Windows Phone controls.
Specifically I'm trying to use a custom TileSource to provide a custom made tiled map that will be stored in the project as a folder (Content files) or in isolate storage.

Down I present the custom class I try to use with map tiles/images stored in "map" folder in ZXY storage format as content files.

public class CustomTileSource : Microsoft.Phone.Controls.Maps.TileSource
{

    private string uriFormat = @"map/{0}/{1}/{2}.png";
    public string UriFormat
    {
        get { return uriFormat; }
        set { uriFormat = value; }
    }

    public override Uri GetUri(int x, int y, int zoomLevel)
    {
        var url = string.Format(UriFormat, zoomLevel, x, y);
        return new Uri(url, UriKind.Relative);
    }
}

Trying to use this is not working and custom tiles are not shown although no error is thrown.
Does anyone tried to use windows phone map control this way?
If that's not the right approach which one is? Any workaround?

Thank you in advance!

Claudiu

Body:
The Exception is:

This operation is not supported on a relative URI.
   at System.Uri.get_AbsoluteUri()
   at System.Windows.Media.MultiScaleTileSource.GetTileLayerUrl(IntPtr nativeTarget, Int32 tileLevel, Int32 tileX, Int32 tileY, Int32 uTileImageIndex, IntPtr& fullTileUri, UInt32& fullTileUriLength)

How to get an image from IsolatedStorage, Ressource or MediaLibrary with UriKind.Absolute i not already found out
...maybe you know?


问:
Object approach to database which has variable scheme
I am developing a C# app where I have to read/write existing MS SQL database. I decided to use object class for the database but the table columns can be changed during runtime and that causes an exception because of an attempt to write a new row (in the case of a new not null column).
Is there any recommendation how to preserve object approach to the database and deal with variable database tables? It is not necessary to have the object updated in the runtime, just to handle the new columns - fill them with a valid default value.

More details to my solution:
I used Data Source Configuration Wizard in VS2015 what generates objects for the database and everything is fine. When a table has a new column I have to run the wizard again to update the objects and define appropriate new value.
I can't modify anything in the database structure (existing ERP system). The database is huge (hundreds of tables, each has around 60+ columns) so I am looking for the automated ways how to generate the database objects.

I hope I just overlooked (as a newbie) some obvious solution.
Thanks for all suggestions in advance.

Petr

答:
I would recommend to do the following:

Create a set of import tables with the needed columns and leave those tables fixed

Let your application copy data to the import tables

Update the production tables on the database from the import tables with a stored procedure


问:
Selenium - Chrome binary ignored
I prefer to use old Selenium 2.53.1 with old version of Chromium 52.0 and chromedriver 2.24. I'm running following on Windows 7:

```<code>start java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe -Dwebdriver.chrome.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,binary="C:\dev\selenium\chrome-win32\chrome.exe",chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -host 0.0.0.0 -port 4444
</code>```

As you can see I have tried a lot of variants trying both binary and chrome_binary. But Selenium Server ignores those options and starts a default Chrome Browser. How to make it run the binary I specified C:\dev\selenium\chrome-win32\chrome.exe?

```<code>09:22:53.149 INFO - Launching a standalone Selenium Server
Setting system property webdriver.chrome.driver to C:\dev\selenium\chromedriver.exe
Setting system property webdriver.chrome.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
09:22:53.480 INFO - Java: Oracle Corporation 25.65-b01
09:22:53.480 INFO - OS: Windows 7 6.1 amd64
09:22:53.490 INFO - v2.53.1, with Core v2.53.1. Built from revision a36b8b1
09:22:53.569 INFO - Driver class not found: com.opera.core.systems.OperaDriver
09:22:53.569 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
09:22:53.579 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped:
registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform VISTA
09:22:53.579 INFO - Driver class not found: org.openqa.selenium.htmlunit.HtmlUnitDriver
09:22:53.579 INFO - Driver provider org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
09:22:53.928 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
09:22:53.928 INFO - Selenium Server is up and running
09:22:54.331 INFO - Executing: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]])
09:22:54.345 INFO - Creating a new session for Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]
Starting ChromeDriver 2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf) onport 4923
Only local connections are allowed.
09:22:55.137 INFO - Done: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]]
</code>```

Related (unaswered):

How to specify the Chrome binary location via the selenium server standalone command line?

答:
Change your command to something like below

```<code>start java  -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe
-Dwebdriver.chrome.binary=C:\dev\selenium\chrome-win32\chrome.exe
-Dwebdriver.chrome.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe
-Dwebdriver.chrome.capabilities.binary=C:\dev\selenium\chrome-win32\chrome.exe
-Dwebdriver.chrome.capabilities.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe
-jar selenium-server-standalone-2.53.1.jar -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,binary="C:\dev\selenium\chrome-win32\chrome.exe",chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -host 0.0.0.0 -port 4444
</code>```

and try again ? You should put the -D JVM argument before the -jar.

For more information refer here.

Title: Selenium - Chrome binary ignored

Body:
I prefer to use old Selenium 2.53.1 with old version of Chromium 52.0 and chromedriver 2.24. I'm running following on Windows 7:

start java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe -Dwebdriver.chrome.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,binary="C:\dev\selenium\chrome-win32\chrome.exe",chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -host 0.0.0.0 -port 4444

As you can see I have tried a lot of variants trying both binary and chrome_binary. But Selenium Server ignores those options and starts a default Chrome Browser. How to make it run the binary I specified C:\dev\selenium\chrome-win32\chrome.exe?

09:22:53.149 INFO - Launching a standalone Selenium Server
Setting system property webdriver.chrome.driver to C:\dev\selenium\chromedriver.exe
Setting system property webdriver.chrome.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
09:22:53.480 INFO - Java: Oracle Corporation 25.65-b01
09:22:53.480 INFO - OS: Windows 7 6.1 amd64
09:22:53.490 INFO - v2.53.1, with Core v2.53.1. Built from revision a36b8b1
09:22:53.569 INFO - Driver class not found: com.opera.core.systems.OperaDriver
09:22:53.569 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
09:22:53.579 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped:
registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform VISTA
09:22:53.579 INFO - Driver class not found: org.openqa.selenium.htmlunit.HtmlUnitDriver
09:22:53.579 INFO - Driver provider org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
09:22:53.928 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
09:22:53.928 INFO - Selenium Server is up and running
09:22:54.331 INFO - Executing: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]])
09:22:54.345 INFO - Creating a new session for Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]
Starting ChromeDriver 2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf) onport 4923
Only local connections are allowed.
09:22:55.137 INFO - Done: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]]

Related (unaswered):

How to specify the Chrome binary location via the selenium server standalone command line?

Body:
Change your command to something like below

start java  -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe
-Dwebdriver.chrome.binary=C:\dev\selenium\chrome-win32\chrome.exe
-Dwebdriver.chrome.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe
-Dwebdriver.chrome.capabilities.binary=C:\dev\selenium\chrome-win32\chrome.exe
-Dwebdriver.chrome.capabilities.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe
-jar selenium-server-standalone-2.53.1.jar -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,binary="C:\dev\selenium\chrome-win32\chrome.exe",chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -host 0.0.0.0 -port 4444

and try again ? You should put the -D JVM argument before the -jar.

For more information refer here.


问:
How can I add JAR files to the web-inf/lib folder in Eclipse?
I'm using Eclipse and I need to be able to add Java libraries (JAR files) into my web application's WEB-INF/lib folder. How do I achieve this?

答:
They are automatically added to the project classpath if its a web project. Sometimes it does not work properly, a refresh or close/open of the project helps.

if its not a web project you can right click on the library and go to "Build Path" -> "Add to Build Path"


问:
In Aurelia, can a slot be used in a repeat.for binding?
I'd like to create a custom element that loops through an array and applies the  to each item in the array.  For example, the view template of the custom element would contain something like:

```<code><div repeat.for="i of items">
  <div with.bind="i">
    <slot></slot>
  </div>
</div>
</code>```

When I remove the repeat.for and with.bind attributes, the slot displays a single time.  Is there a way to make it repeat for each item in the list?

答:
No, you cannot use slots with repeat.for or bind today. To do this you have to use replaceable parts. For example:

```<code><div repeat.for="i of items">
  <div with.bind="i">
    <template replaceable part="content"></template>
  </div>
</div>
</code>```

Usage:

```<code><my-component>
  <template replace-part="content">Some Content - ${somePropertyOfI}</template>
</my-component>
</code>```

Runnable example: https://gist.run/?id=29aa1c1199f080c9ba0e72845044799b

Body:
I'd like to create a custom element that loops through an array and applies the  to each item in the array.  For example, the view template of the custom element would contain something like:

    <slot></slot>

When I remove the repeat.for and with.bind attributes, the slot displays a single time.  Is there a way to make it repeat for each item in the list?

Body:
No, you cannot use slots with repeat.for or bind today. To do this you have to use replaceable parts. For example:

<div repeat.for="i of items">
  <div with.bind="i">
    <template replaceable part="content"></template>
  </div>
</div>

Usage:

<my-component>
  <template replace-part="content">Some Content - ${somePropertyOfI}</template>
</my-component>

Runnable example: https://gist.run/?id=29aa1c1199f080c9ba0e72845044799b


问:
Personal Access Token in Github not working
I have a private repository on my personal Github account that I work on from time to time, but not on a daily basis.

The repository has been cloned using HTTPS (not SSH or git://).
In order to access the repository from the command line, I set up a personal access token as explained here: https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/

I am positive it did work back then (I moved away from SSH precisely because this kind of persistent headache).

However, when I try to push to my repository after a few weeks I get the dreaded:

```<code>$ remote: Repository not found. fatal: repository
$ 'https://github.com/nicolas-miari/MyPrivateRepo.git/' not found
</code>```

What am I missing?

Addendum: I deleted the token on Github, created a new one, and followed the instructions here: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/ to clear the old token stored in the keychain. I was able to re-clone my private repository. However,

This still doesn't explain why the previous access token suddenly stopped working, and

My keychain had two "Internet password" entries matching the host github.com: The access token I just deleted, and the my web login password for a different Github account (work). Maybe this has something to do with it?

Background info: To avoid having to log in/out frequently, I have my work account's web credentials saved in Safari (and the Keychain), and my personal account's web credentials saved in Firefox.

Addendum 2: After running the command given on the linked help page:

```<code>$ git credential-osxkeychain erase
  host=github.com
  protocol=https
  [enter]
</code>```

...the additional password is gone from the Keychain (only my newly added Personal Token remains), however I can still log in to my account on Safari...?

Update: Now I can't push to repos from my work account (which credentials I deleted from Keychain...). This system really needs a healthy dose of Just Works...

答:
Don't forget that Safari has access to iCloud Keychain

That could explain why, even though you have cleared your local OSX keychain, you still can log on to GitHub with Safari.

Body:
I have a private repository on my personal Github account that I work on from time to time, but not on a daily basis.

The repository has been cloned using HTTPS (not SSH or git://).
In order to access the repository from the command line, I set up a personal access token as explained here: https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/

I am positive it did work back then (I moved away from SSH precisely because this kind of persistent headache).

However, when I try to push to my repository after a few weeks I get the dreaded:

$ remote: Repository not found. fatal: repository
$ 'https://github.com/nicolas-miari/MyPrivateRepo.git/' not found

What am I missing?

Addendum: I deleted the token on Github, created a new one, and followed the instructions here: https://help.github.com/articles/updating-credentials-from-the-osx-keychain/ to clear the old token stored in the keychain. I was able to re-clone my private repository. However,

This still doesn't explain why the previous access token suddenly stopped working, and

My keychain had two "Internet password" entries matching the host github.com: The access token I just deleted, and the my web login password for a different Github account (work). Maybe this has something to do with it?

Background info: To avoid having to log in/out frequently, I have my work account's web credentials saved in Safari (and the Keychain), and my personal account's web credentials saved in Firefox.

Addendum 2: After running the command given on the linked help page:

$ git credential-osxkeychain erase
  host=github.com
  protocol=https
  [enter]

...the additional password is gone from the Keychain (only my newly added Personal Token remains), however I can still log in to my account on Safari...?

Update: Now I can't push to repos from my work account (which credentials I deleted from Keychain...). This system really needs a healthy dose of Just Works...


答:
```<code>return api.viewerUrl + (_.includes(api.historyModeServers, api.env) ? '/' : '/#!/') + this.building.sharecode + (hasUi ? '?ui=true' : '');
</code>```

Title: How to create a conditional end of a string?

Body:
I'm generating a string like this:

if (_.includes(api.historyModeServers, api.env)) {
  return api.viewerUrl + '/' + this.building.sharecode + '?ui=true'
} else {
  return api.viewerUrl + '/#!/' + this.building.sharecode + '?ui=true'
}

How can I make the ?ui=true conditional? Say like if hasUi add that part and if not don't add it?


问:
Adding a char at the end of every line in while loop
Can someone please help me with this problem, I want my program to print + with every end of line.

My code is:

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

int main()
{

char str[65];
char * pch;
char str1[65];

fgets (str, 100, stdin);

  pch = strtok (str," ");
  while (pch != NULL)
  {
   str1=pch;
    printf("=");
    printf ("%s\n",pch);
    pch = strtok (NULL, " ");
  }

return 0;
}
</code>```

With input, "Muhannad Stack" (output wrong):

```<code>=Muhannad
=Stack
</code>```

Correct:

```<code>=Muhannad+
=Stack+
</code>```

Therefore, my problem is how to add + at the end of every printed line

答:
Here is what would work:</p>

```<code>#include <stdio.h>
#include <string.h>
int main()
{
  char str[65];
  char * pch;
  char str1[65];
  fgets (str, 100, stdin);
  pch = strtok (str,"\n");
  pch = strtok (pch," ");
  while (pch != NULL) {
    printf ("=%s+\n",pch);
    pch = strtok (NULL, " ");
  }
  return 0;
}
</code>```

Body:
Can someone please help me with this problem, I want my program to print + with every end of line.

My code is:

#include <stdio.h>
#include <string.h>

int main()
{

char str[65];
char * pch;
char str1[65];

fgets (str, 100, stdin);

  pch = strtok (str," ");
  while (pch != NULL)
  {
   str1=pch;
    printf("=");
    printf ("%s\n",pch);
    pch = strtok (NULL, " ");
  }

return 0;
}

With input, "Muhannad Stack" (output wrong):

=Muhannad
=Stack

Correct:

=Muhannad+
=Stack+

Therefore, my problem is how to add + at the end of every printed line

Body:
Here is what would work:

#include <stdio.h>
#include <string.h>
int main()
{
  char str[65];
  char * pch;
  char str1[65];
  fgets (str, 100, stdin);
  pch = strtok (str,"\n");
  pch = strtok (pch," ");
  while (pch != NULL) {
    printf ("=%s+\n",pch);
    pch = strtok (NULL, " ");
  }
  return 0;
}


问:
How to run React Native project on Emulator in WebStorm
I'm using WebStorm IDE for develop my React Native Android project. I have followed these steps in their website. But there is no way to connect with Emulator. When I run the project it show bellow error.

Update

答:
There could be always something missing when you trying to use a library etc. My recommendation is npm uninstall realm and install again and check android directory if it is not realm linked decent, relink again manually or with following code react-native link realm.

edit for updated post: try adb reverse tcp:8081 tcp:8081 .  If you have remotely debugging problem then try adb forward tcp:8082 tcp:8082


问:
error in PDO connection
Hye, kindly need your help to assist me finding the error of this connection. The reason is that i didn't get submitting the data in a form to the database.</p>

```<code><?php
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=;charset=utf8', 'root', '');
}
catch(Exception $e)
{
        die('Erreur : '.$e->getMessage());
}
</code>```

答:
You are missing the database name.

dbname=You Forgot The Name Here;

P.S. if you don't want to include the database, you should leave the entire part.

Title: error in PDO connection

Body:
Hye, kindly need your help to assist me finding the error of this connection. The reason is that i didn't get submitting the data in a form to the database.

<?php
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=;charset=utf8', 'root', '');
}
catch(Exception $e)
{
        die('Erreur : '.$e->getMessage());
}


问:
By using c# , how can I make disappear the grey unnecessary zone in my datagridview?
Here is the screenshot of the datagridView, By using c# , how can I make disappear the grey unnecessary zone in my datagridview?

答:
There are 2 Options.

Option 1:

Add this line to your Form_Load Event:

```<code>dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
</code>```

Option 2:

Change the AutoSizeColumnsMode property in Datagridview to Fill

Body:
There are 2 Options.

Option 1:

Add this line to your Form_Load Event:

dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

Option 2:

Change the AutoSizeColumnsMode property in Datagridview to Fill


问:
Command line MSBuild not exluding Debug libraries
So I have build a UWP application which I have built an .appxupload package through Visual Studio and submitted it to the store and it has been accepted to the store fine.

I am now trying to use Visual Studio Online to Automate my build process.

I am building my project in a new configuration I have defined called AppStore that looks like the following:

```<code>  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'AppStore|AnyCPU'">
    <OutputPath>bin\AppStore\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
</code>```

And my Command line arguments for the Automated build are:

```<code>/p:Configuration=AppStore;AppxBundle=Always;AppxBundlePlatforms="x86|x64|ARM";AppxPackageDir="$(Build.BinariesDirectory)\AppxPackages\\";UapAppxPackageBuildMode=StoreUpload
</code>```

This then created my .appxupload package on request which was great.. BUT... when I uploaded to the store I get the following:

Debug configuration

Error Found: The debug configuration test detected the following errors:

The binary MyApp.Logging.dll is built in debug mode.

The binary MyApp.Reports.dll is built in debug mode.

The binary MyApp.DataAccess.dll is built in debug mode.

The binary MyApp.Business.dll is built in debug mode.

The binary MyApp.Core.dll is built in debug mode.

Are my MsBuild arguments incorrect?

Update

this is the command MSBuild is running:

```<code>"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe" "C:\agent\_work\1\s\MyApp\MyApp\MyApp.UWP\MyApp.UWP.csproj" /nologo /nr:false /t:"Clean" /dl:CentralLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.118.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=ebe5f0fb-1da0-4f6b-aa54-d80c73ac3060|SolutionDir=C:\agent\_work\1\s\MyApp\MyApp\MyApp.UWP"*ForwardingLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.118.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll" /p:Configuration=AppStore;AppxBundle=Always;AppxBundlePlatforms="x86|x64|ARM";AppxPackageDir="C:\agent\_work\1\b\AppxPackages\\";UapAppxPackageBuildMode=StoreUpload /p:configuration="AppStore" /p:VisualStudioVersion="15.0" /p:_MSDeployUserAgent="VSTS_7c0e42bd-65b9-486e-9338-1c87ca14bb55_build_3_1182"
</code>```

It seems to produce x86 in Release mode and x64 and ARM in debug and thats where my app fails Windows Certification Checks

答:
Refer to these steps to change configuration:

Right click solution file in VS > Configuration Manager

Select AppStore configuration

Change configurations of MyApp.Logging, MyApp.Reports, MyApp.DataAccess … (e.g. release)

Body:
So I have build a UWP application which I have built an .appxupload package through Visual Studio and submitted it to the store and it has been accepted to the store fine.

I am now trying to use Visual Studio Online to Automate my build process.

I am building my project in a new configuration I have defined called AppStore that looks like the following:

  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'AppStore|AnyCPU'">
    <OutputPath>bin\AppStore\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <Optimize>true</Optimize>
    <DebugType>pdbonly</DebugType>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>

And my Command line arguments for the Automated build are:

/p:Configuration=AppStore;AppxBundle=Always;AppxBundlePlatforms="x86|x64|ARM";AppxPackageDir="$(Build.BinariesDirectory)\AppxPackages\\";UapAppxPackageBuildMode=StoreUpload

This then created my .appxupload package on request which was great.. BUT... when I uploaded to the store I get the following:

Debug configuration

Error Found: The debug configuration test detected the following errors:

The binary MyApp.Logging.dll is built in debug mode.

The binary MyApp.Reports.dll is built in debug mode.

The binary MyApp.DataAccess.dll is built in debug mode.

The binary MyApp.Business.dll is built in debug mode.

The binary MyApp.Core.dll is built in debug mode.

Are my MsBuild arguments incorrect?

Update

this is the command MSBuild is running:

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe" "C:\agent\_work\1\s\MyApp\MyApp\MyApp.UWP\MyApp.UWP.csproj" /nologo /nr:false /t:"Clean" /dl:CentralLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.118.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=ebe5f0fb-1da0-4f6b-aa54-d80c73ac3060|SolutionDir=C:\agent\_work\1\s\MyApp\MyApp\MyApp.UWP"*ForwardingLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.118.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll" /p:Configuration=AppStore;AppxBundle=Always;AppxBundlePlatforms="x86|x64|ARM";AppxPackageDir="C:\agent\_work\1\b\AppxPackages\\";UapAppxPackageBuildMode=StoreUpload /p:configuration="AppStore" /p:VisualStudioVersion="15.0" /p:_MSDeployUserAgent="VSTS_7c0e42bd-65b9-486e-9338-1c87ca14bb55_build_3_1182"

It seems to produce x86 in Release mode and x64 and ARM in debug and thats where my app fails Windows Certification Checks


问:
How to use MultiDex with a custom Application class?
Ok so I am making an App that has uses the .App class to get Context statically, the class does not work unless placed in manifest under
    <application android:name=.App but the issue is I clocked 65k so I have multiDex and MultiDex too needs to be in Manifest under the <application android:name=.MultiDex otherwise my App will not run, how can I get past this problem without affected multidex which is my worst fear looking at how much trouble I went through just to make it work?

答:
BaseAppplication is custom Application class</p>

```<code>public class BaseApplication extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            // your custom code here
        }

    // Add multidex Code or other Application Class here
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(base);
            MultiDex.install(this);
        }
    }
</code>```

Body:
BaseAppplication is custom Application class

public class BaseApplication extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            // your custom code here
        }

    // Add multidex Code or other Application Class here
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(base);
            MultiDex.install(this);
        }
    }


问:
Required Mime Type for CSV
Is there some way to get proper mime type for .csv files to include in the attachment of my jsp page?</p>

答:
At the top of your JSP:</p>

```<code><% response.setHeader("Content-Type", "text/csv"); %>
</code>```

Title: Required Mime Type for CSV

Body:
At the top of your JSP:

<% response.setHeader("Content-Type", "text/csv"); %>


问:
How to draw circle with leaflet.draw and CRS.Simple
I am using leaflet.draw plugin, working on a simple image with L.CRS.Simple.
The drawing toolbar works fine except for drawing circles.

http://playground-leaflet.rhcloud.com/kapi/edit?html,output

How to enable drawing circles on a Leaflet map with Leaflet.draw plugin when using L.CRS.Simple?

答:
The issue is with the using L.CRS.simple and trying to draw a circle.
When circles are drawn (L.Draw.circle_drawShape()) the radius is set from the result of L.LatLng.distanceTo and this distance is actually calculated based on L.CRS.Earth

When L.CRS.Smple is used the radius becomes really huge, going out of bounds.
While drawing other shapes this will not be a problem as they does not use L.LatLng.distanceTo method.

As a work around,what you can do this override :

```<code>L.LatLng.prototype.distanceTo = function (currentPostion) {
    var dx = currentPostion.lng - this.lng;
    var dy = currentPostion.lat - this.lat;
    return Math.sqrt(dx*dx + dy*dy);
}
</code>```

This will do the trick.

A detailed explanation of the issue is given in the below link :
https://github.com/Leaflet/Leaflet.draw/issues/611

Hope this helps!!!

Body:
The issue is with the using L.CRS.simple and trying to draw a circle.
When circles are drawn (L.Draw.circle_drawShape()) the radius is set from the result of L.LatLng.distanceTo and this distance is actually calculated based on L.CRS.Earth

When L.CRS.Smple is used the radius becomes really huge, going out of bounds.
While drawing other shapes this will not be a problem as they does not use L.LatLng.distanceTo method.

As a work around,what you can do this override :

L.LatLng.prototype.distanceTo = function (currentPostion) {
    var dx = currentPostion.lng - this.lng;
    var dy = currentPostion.lat - this.lat;
    return Math.sqrt(dx*dx + dy*dy);
}

This will do the trick.

A detailed explanation of the issue is given in the below link :
https://github.com/Leaflet/Leaflet.draw/issues/611

Hope this helps!!!


问:
Custom tumblr like button
I've created a custom tumblr like button and have put the iframe above it to make it clickable but I must have done something wrong because it doesn't work.. I haven't quite understood how it works sorry if this is a dumb question! I know you have to create your custom button and just put tumblr's iframe above but...

window.onload = function() {
  document.body.insertAdjacentHTML('beforeEnd', '');
  document.addEventListener('click', function(event) {
    var myLike = event.target;
    if (myLike.className.indexOf('like') > -1) {
      var frame = document.getElementById('my-like-frame'),
        liked = (myLike.className == 'liked'),
        command = liked ? 'unlike' : 'like',
        reblog = myLike.getAttribute('data-reblog'),
        id = myLike.getAttribute('data-id'),
        oauth = reblog.slice(-8);
      frame.src = 'http://www.tumblr.com/' + command + '/' + oauth + '?id=' + id;
      liked ? myLike.className = 'like' : myLike.className = 'liked';
    };
  }, false);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.controls i {
  height: 10px;
  width: 10px;
  background: #ce9c87;
  border-radius: 100%;
  padding: 5px;
  display: block;
  overflow: visible;
  text-align: center;
  color: #fff;
  -webkit-transition: .2s ease;
  -moz-transition: .2s ease;
  -o-transition: .2s ease;
  transition: .2s ease;
}

.controls {
  float: right;
  margin-right: 10px;
}

.controls a {
  position: relative;
  display: inline-block;
  overflow: hidden;
  padding: 1px 2px;
  width: auto;
  height: auto;
  margin-left: 1em;
  float: right;
}

.like {
  position: relative;
  display: inline-block;
  overflow: hidden;
  padding: 1px 2px;
  width: auto;
  height: auto;
  margin-left: 1em;
  float: right;
  cursor: pointer;
}

.controls .like .liked+i,
.controls i:hover {
  color: #ce9c87;
  background-color: #fff;
}</code>```

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

{LikeButton}

```

If it isn't clear here is the link to the page..

Thank you!

答: Possibly the problem you are having is because tumblr no longer allows you to like posts on any of your own blogs. You can work around this by opening the console and clicking your like button and if this error occurs it means your like button works but tumblr is preventing you from liking your own posts.

Title: Custom tumblr like button

Body:
I've created a custom tumblr like button and have put the iframe above it to make it clickable but I must have done something wrong because it doesn't work.. I haven't quite understood how it works sorry if this is a dumb question! I know you have to create your custom button and just put tumblr's iframe above but...

window.onload = function() {
  document.body.insertAdjacentHTML('beforeEnd', '');
  document.addEventListener('click', function(event) {
    var myLike = event.target;
    if (myLike.className.indexOf('like') > -1) {
      var frame = document.getElementById('my-like-frame'),
        liked = (myLike.className == 'liked'),
        command = liked ? 'unlike' : 'like',
        reblog = myLike.getAttribute('data-reblog'),
        id = myLike.getAttribute('data-id'),
        oauth = reblog.slice(-8);
      frame.src = 'http://www.tumblr.com/' + command + '/' + oauth + '?id=' + id;
      liked ? myLike.className = 'like' : myLike.className = 'liked';
    };
  }, false);
};

.controls i {
  height: 10px;
  width: 10px;
  background: #ce9c87;
  border-radius: 100%;
  padding: 5px;
  display: block;
  overflow: visible;
  text-align: center;
  color: #fff;
  -webkit-transition: .2s ease;
  -moz-transition: .2s ease;
  -o-transition: .2s ease;
  transition: .2s ease;
}

.controls {
  float: right;
  margin-right: 10px;
}

.controls a {
  position: relative;
  display: inline-block;
  overflow: hidden;
  padding: 1px 2px;
  width: auto;
  height: auto;
  margin-left: 1em;
  float: right;
}

.like {
  position: relative;
  display: inline-block;
  overflow: hidden;
  padding: 1px 2px;
  width: auto;
  height: auto;
  margin-left: 1em;
  float: right;
  cursor: pointer;
}

.controls .like .liked+i,
.controls i:hover {
  color: #ce9c87;
  background-color: #fff;
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

{LikeButton}

If it isn't clear here is the link to the page..

Thank you!


问:
Choose an aggregate function for Group BY in SQL Server
I have a query like this:

```<code>Select Count(*) as TotalCount, Object2_ID, Object_ID, Object_Description
from Table1
inner join table2 on...
Group BY Object2_ID, Object_ID
</code>```

I can't run this query because the column Object_Description isn't in GROUP BY or under aggregate function. Object_Description is a text column. I need any value of Object_Description. Now I use MAX(Object_Description) because it gives me right results, because Object_Description is the same for each group.

I can use MAX() or MIN() etc. - I will get right results in my query.

The question is - what is the most sufficient way to do this ?

I think that MAX() or MIN() produces small overheads.

答:
You can get Object Description later, after calculation quantity (assumed that description in in table1 and you need get count from Table2):</p>

```<code>SELECT Object_Id, Object_Description, Qty
FROM
(
  SELECT Object_Id, Count(*) Qty
  FROM Table2
  GROUP BY Object_Id
) t
JOIN Table1 t2 on t2.Object_Id = t.Object_Id
</code>```

Body:
I have a query like this:

Select Count(*) as TotalCount, Object2_ID, Object_ID, Object_Description
from Table1
inner join table2 on...
Group BY Object2_ID, Object_ID

I can't run this query because the column Object_Description isn't in GROUP BY or under aggregate function. Object_Description is a text column. I need any value of Object_Description. Now I use MAX(Object_Description) because it gives me right results, because Object_Description is the same for each group.

I can use MAX() or MIN() etc. - I will get right results in my query.

The question is - what is the most sufficient way to do this ?

I think that MAX() or MIN() produces small overheads.

Body:
You can get Object Description later, after calculation quantity (assumed that description in in table1 and you need get count from Table2):

SELECT Object_Id, Object_Description, Qty
FROM
(
  SELECT Object_Id, Count(*) Qty
  FROM Table2
  GROUP BY Object_Id
) t
JOIN Table1 t2 on t2.Object_Id = t.Object_Id


问:
How do I begin working on the Project Tango?
after a couple of weeks I have been unable to get the android set of tools to a functioning level with c++ before and have been given the opportunity of using a project tango, and though that sounds awesome and wondrous and would open a world of opportunity for working with VR... I feel like I am stuck at step -4.  My understanding is limited, so bear with me.

I stumbled upon the PCL built for running algorithms on point cloud data, it was open source and appeared like a wonderful solution, it is written in C++ and I have a mild understanding of both c++ and java.
I have tried using Eclipse and the NDK and actually managed to get a project 'deployed' to the tango, however upon attempting to edit any file in the project, java or c++, it breaks and will never deploy again.

Now I am trying to use Android Studio, and after following about 5 conflicting tutorials on 'how to get C++/ndk working in android studio' I have yet to get a working environment.
So here is my question, and we can start at step one, any help is appreciated. How does one get c++ and the PCL working on a google project tango, is there a better way for someone of my skill level?  The end result is a mapped 3d space with the project tango, with exportable data sets of manageable size. I have seen it done in demos on youtube, but thus far, like i said, I am stuck on step -4.

答:
Tango NDK Tutorial Will help but the basic layout is

Setup a new project

Create your Java activity

Create a JNI file to bridge Java to the C++

Create your C++ logic

Setup your Makefiles and Gradle (probably the most annoying part)


问:
lifecycle hooks of input population from sibling component angular2
I have two siblings component like below

```<code><broker-list (onBrokerClicked)="onBrokerClicked= $event"></broker-list>
<station-list [(broker)]="onBrokerClicked" [(ngModel)]="stations"></station-list><!--broker is an input-->
</code>```

when user click on broker-list, in station-list component broker which is an @Input gets populated. ngModel in stationlist can be populated only after it's sibling component is clicked or in other words the input broker gets populated. I want the exact moment when the input gets populated form the sibling component which is not in ngOnInit. is there any event or something which is raised after input population that I can do some stuff in it???

答:
You can Use ngOnChanges by importing onChanges from @angular/core.

What ngOnChanges does ?
ngOnChanges gets fired whenever input values change.

```<code>import { onChanges } from @angular/core;
</code>```

define your ngOnChanges inside the class :

```<code>export your_class_name implements onChanges{

 ngOnChanges(){
 //Do your stuff with the input
 }
}
</code>```

Body:
I have two siblings component like below

<broker-list (onBrokerClicked)="onBrokerClicked= $event"></broker-list>
<station-list [(broker)]="onBrokerClicked" [(ngModel)]="stations"></station-list>

when user click on broker-list, in station-list component broker which is an @Input gets populated. ngModel in stationlist can be populated only after it's sibling component is clicked or in other words the input broker gets populated. I want the exact moment when the input gets populated form the sibling component which is not in ngOnInit. is there any event or something which is raised after input population that I can do some stuff in it???

Body:
You can Use ngOnChanges by importing onChanges from @angular/core.

What ngOnChanges does ?
ngOnChanges gets fired whenever input values change.

import { onChanges } from @angular/core;

define your ngOnChanges inside the class :

export your_class_name implements onChanges{

 ngOnChanges(){
 //Do your stuff with the input
 }
}


问:
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>```

答:
I would suggest you to define a ini configuration file, and configure the database configuration inside the ini file.

Use the method parse_ini_file to get the configurations from ini file. By this way, you will have different configurations for each server.

Documentation on creating and parsing ini file can be found here

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();

?>


问:
Enabling English UK spell check in a UWP app
I am trying to enable spell check in my UWP application (Windows 10) using English UK spelling.

So far the only way I have managed to get spell check to work at all is by installing the English (US) language pack onto my device, but I would like to have UK spelling not US. I also noticed that the Spelling settings (as seen in this article) only show up under Typing when the US language pack is installed. There is no Spelling section even when I have English (UK) installed.

Other notes: the device I am using is a Surface 3 tablet and my default language pack is English (New Zealand).

How can I get the spell check working in UWP for English (UK)?

答:
Also, some users might use an Input Method Editor (IME) to enter another language into your app, and that language might be supported. For example, when building a Japanese language app, even though the spell checking engine might not currently recognize that language, don't turn spell checking off. The user may switch to an English IME and type English into the app; if spell checking is enabled, the English will get spell checked.

For more info, please refer the Guidelines for spell checking.

When we set the English(United Kingdom) as the default language in Settings, it will spell check English(GB) typing. When we switch input method to Englich(United States), it can also spell check English(US) typing.

We can open the Manage optional features in Apps & features in Settings. It lists Optional features, we can see English (GB) typing: Spelling, text prediction, and document searching for English(GB).


问:
angularjs - validation error message
Can someone explain me the following code, I'm new to angular please help me :

```<code>{% if validation_error %}
   <div>{{ validation_error }}</div>
{% endif %}
</code>```

On web page :

Full code :

```<code><form name="login" method="POST" action="/app/login">
    <div class="form-container">
        <fieldset class="form-group">
            <input class="form-control form-control-sm text-uppercase" id="username" name="username" type="text" placeholder="Username">
            <input class="form-control form-control-sm" name="password" type="password" placeholder="Password">
        </fieldset>
        <button class="btn btn-primary btn-sm btn-block">signin</button>
        {% if validation_error %}
            <div class="small text-danger m-t-1">{{ validation_error }}</div>
        {% endif %}
    </div>
</form>
</code>```

答:
Add ng-show tag to div

```<code><div ng-show="login.username.$invalid && !login.username.$pristine" class="small text-danger m-t-1">You name is required.</div>
</code>```

Title: angularjs - validation error message

Body:
Can someone explain me the following code, I'm new to angular please help me :

{% if validation_error %}

{{ validation_error }}

{% endif %}

On web page :

Full code :

<form name="login" method="POST" action="/app/login">

        <fieldset class="form-group">
            <input class="form-control form-control-sm text-uppercase" id="username" name="username" type="text" placeholder="Username">
            <input class="form-control form-control-sm" name="password" type="password" placeholder="Password">
        </fieldset>
        <button class="btn btn-primary btn-sm btn-block">signin</button>
        {% if validation_error %}

{{ validation_error }}

        {% endif %}

</form>

Body:
Add ng-show tag to div

<div ng-show="login.username.$invalid && !login.username.$pristine" class="small text-danger m-t-1">You name is required.</div>


问:
How to change the size of the radio button using CSS?
Is there a way to control the size of the radio button in CSS ?</p>

答:
try this code... it may be the ans what you exactly looking for

body, html{
  height: 100%;
  background: #222222;
}

.container{
  display: block;
  position: relative;
  margin: 40px auto;
  height: auto;
  width: 500px;
  padding: 20px;
}

h2 {
 color: #AAAAAA;
}

.container ul{
  list-style: none;
  margin: 0;
  padding: 0;
 overflow: auto;
}

ul li{
  color: #AAAAAA;
  display: block;
  position: relative;
  float: left;
  width: 100%;
  height: 100px;
 border-bottom: 1px solid #333;
}

ul li input[type=radio]{
  position: absolute;
  visibility: hidden;
}

ul li label{
  display: block;
  position: relative;
  font-weight: 300;
  font-size: 1.35em;
  padding: 25px 25px 25px 80px;
  margin: 10px auto;
  height: 30px;
  z-index: 9;
  cursor: pointer;
  -webkit-transition: all 0.25s linear;
}

ul li:hover label{
 color: #FFFFFF;
}

ul li .check{
  display: block;
  position: absolute;
  border: 5px solid #AAAAAA;
  border-radius: 100%;
  height: 25px;
  width: 25px;
  top: 30px;
  left: 20px;
 z-index: 5;
 transition: border .25s linear;
 -webkit-transition: border .25s linear;
}

ul li:hover .check {
  border: 5px solid #FFFFFF;
}

ul li .check::before {
  display: block;
  position: absolute;
 content: '';
  border-radius: 100%;
  height: 15px;
  width: 15px;
  top: 5px;
 left: 5px;
  margin: auto;
 transition: background 0.25s linear;
 -webkit-transition: background 0.25s linear;
}

input[type=radio]:checked ~ .check {
  border: 5px solid #0DFF92;
}

input[type=radio]:checked ~ .check::before{
  background: #0DFF92;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <input type="radio" id="f-option" name="selector">
    <label for="f-option">Male</label>

    <div class="check"></div>
  </li>

  <li>
    <input type="radio" id="s-option" name="selector">
    <label for="s-option">Female</label>

    <div class="check"><div class="inside"></div></div>
  </li>

  <li>
    <input type="radio" id="t-option" name="selector">
    <label for="t-option">Transgender</label>

    <div class="check"><div class="inside"></div></div>
  </li>
</ul></code>```

Body:
try this code... it may be the ans what you exactly looking for

body, html{
  height: 100%;
  background: #222222;
}

.container{
  display: block;
  position: relative;
  margin: 40px auto;
  height: auto;
  width: 500px;
  padding: 20px;
}

h2 {
 color: #AAAAAA;
}

.container ul{
  list-style: none;
  margin: 0;
  padding: 0;
 overflow: auto;
}

ul li{
  color: #AAAAAA;
  display: block;
  position: relative;
  float: left;
  width: 100%;
  height: 100px;
 border-bottom: 1px solid #333;
}

ul li input[type=radio]{
  position: absolute;
  visibility: hidden;
}

ul li label{
  display: block;
  position: relative;
  font-weight: 300;
  font-size: 1.35em;
  padding: 25px 25px 25px 80px;
  margin: 10px auto;
  height: 30px;
  z-index: 9;
  cursor: pointer;
  -webkit-transition: all 0.25s linear;
}

ul li:hover label{
 color: #FFFFFF;
}

ul li .check{
  display: block;
  position: absolute;
  border: 5px solid #AAAAAA;
  border-radius: 100%;
  height: 25px;
  width: 25px;
  top: 30px;
  left: 20px;
 z-index: 5;
 transition: border .25s linear;
 -webkit-transition: border .25s linear;
}

ul li:hover .check {
  border: 5px solid #FFFFFF;
}

ul li .check::before {
  display: block;
  position: absolute;
 content: '';
  border-radius: 100%;
  height: 15px;
  width: 15px;
  top: 5px;
 left: 5px;
  margin: auto;
 transition: background 0.25s linear;
 -webkit-transition: background 0.25s linear;
}

input[type=radio]:checked ~ .check {
  border: 5px solid #0DFF92;
}

input[type=radio]:checked ~ .check::before{
  background: #0DFF92;
}

<ul>
  <li>
    <input type="radio" id="f-option" name="selector">
    <label for="f-option">Male</label>

    <div class="check"></div>
  </li>

  <li>
    <input type="radio" id="s-option" name="selector">
    <label for="s-option">Female</label>

    <div class="check"><div class="inside"></div></div>
  </li>

  <li>
    <input type="radio" id="t-option" name="selector">
    <label for="t-option">Transgender</label>

    <div class="check"><div class="inside"></div></div>
  </li>
</ul>


问:
Get the day change point(s) between two UNIX timestamps
I have the date range (two UNIX timestamps) and I need to find point(s) at 23:59:59 if exists.
How I can do it with Perl?

P.S. I think for() is not good idea because I can have very big range. Anything another variants?

答: use DateTime;</p>

Body: use DateTime;


问:
ReactNative custom port support for run-android command, McAfee workaround
I am trying to configure react native for windows for android app development but I am unable to use port 8081 as it is used by McAfee agent on my laptop.
I am able to start node js server on different port (8090)

```<code>react-native start --port=8090
</code>```

But when I run the command:

```<code>react-native run-android
</code>```

I am unable to specify port option. Looks to be that it is hardcoded with 8081.

Is there anyway I can start react-native run-android for custom port(8090) port on windows?
I am completely new to reactnative and following below link to configure sample Awesomeproject for android on windows.

https://facebook.github.io/react-native/docs/getting-started.html#content

答:
There is a small work around for this. Anyone running this on a physical device(or even otherwise) can restart their adb session using a different port.

eg.

```<code>react-native start --port=1234
</code>```

On a different cmd/terminal window.

```<code>react-native run-android
</code>```

After which I am greeted by these messages.

```<code>BUILD SUCCESSFUL

Total time: 22.589 secs
Running C:\SDK/platform-tools/adb -s VY0025160560725694 reverse tcp:8081
tcp:8081
</code>```

This runs it on default reverse port of 8081, which is blocked by McAfee.

Work around:

```<code>adb reverse tcp:8081 tcp:1234
</code>```

Note: You may have to kill and re-open the app.

Currently I am unable to provide an answer for an emulated device since I do not have one installed on my system. But the steps should be similar.

Body:
I am trying to configure react native for windows for android app development but I am unable to use port 8081 as it is used by McAfee agent on my laptop.
I am able to start node js server on different port (8090)

react-native start --port=8090

But when I run the command:

react-native run-android

I am unable to specify port option. Looks to be that it is hardcoded with 8081.

Is there anyway I can start react-native run-android for custom port(8090) port on windows?
I am completely new to reactnative and following below link to configure sample Awesomeproject for android on windows.

https://facebook.github.io/react-native/docs/getting-started.html#content

Body:
There is a small work around for this. Anyone running this on a physical device(or even otherwise) can restart their adb session using a different port.

eg.

react-native start --port=1234

On a different cmd/terminal window.

react-native run-android

After which I am greeted by these messages.

BUILD SUCCESSFUL

Total time: 22.589 secs
Running C:\SDK/platform-tools/adb -s VY0025160560725694 reverse tcp:8081
tcp:8081

This runs it on default reverse port of 8081, which is blocked by McAfee.

Work around:

adb reverse tcp:8081 tcp:1234

Note: You may have to kill and re-open the app.

Currently I am unable to provide an answer for an emulated device since I do not have one installed on my system. But the steps should be similar.


问:
Error in Web.Config adding NotFoundMvc in ASP.Net MVC
I got this error after I added NotFoundMvc in my project. If I remove NotFoundMvc  I don't get this error. What should I change in Web.Config file?

答:
First of all check the given line is there within the top of your transform file.

```<code><?xml version="1.0"?>
</code>```

If it is there, I would also check that the following is not within your actual transformed web.config.

```<code><configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
</code>```

I have found the web essentials extension invaluable for resolving errors like this before I deploy.

You can simply right-click your transform file and select preview from Visual Studio and if you encounter any problems you can investigate/fix locally.

Web essentials 2012

Body:
First of all check the given line is there within the top of your transform file.

<?xml version="1.0"?>

If it is there, I would also check that the following is not within your actual transformed web.config.

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

I have found the web essentials extension invaluable for resolving errors like this before I deploy.

You can simply right-click your transform file and select preview from Visual Studio and if you encounter any problems you can investigate/fix locally.

Web essentials 2012


问:
How to run HTML based sql query from MultilineTextBox?
I have a multiline textbox from which I am updating my sql store procedure. In my store procedure I'm sending email(Html Formated) to user via SQL Job.
Problem is when I try to put below code in my textbox my submit button is stop working and perform no action.

```<code>Set @link = ' <br> URL: <a href=abc.com/default4.aspx> abc.com/default4.aspx</a> <br> ' -- For Test
</code>```

I'm also tried to put validateRequest="false" in my page directive but nothing happened.

Sorry here I mentioned one thing more that when I remove
 tag from above code my submit button works fine. But when I put only
 in my ASP.Net Textbox submit button again perform no action on submit.

How can I able to insert HTML Tags in ASP.Net Textbox.

Also I found below links regarding to my question but these links not works for me.

Allow HTML tags in TextBox control

ASP.Net Text with LineBreak from Multi-Line-TextBox to save in a database

ASP.NET Replacing Line Break with HTML br not working

答:
After spending some time on internet I found my answer.

Here I'm sharing my findings.

I put below in my page header

```<code><script>
    function fnescape() {
        document.getElementById('myTextBox1').value = window.escape(document.getElementById('myTextBox1').value);
    };

    function fnunescape() {
        document.getElementById('myTextBox1').value = window.unescape(document.getElementById('myTextBox1').value);
    }
</script>
</code>```

and put below code before closing body tag

```<code><script>
    fnunescape();
</script>
</code>```

set ClientIDMode="Static" to ASP.Net Textbox

Codebehind:

put below code inside submit button clicked

var query = System.Uri.UnescapeDataString(txtInsertQuery.Text.ToString().Trim());

Reference Link

Unescape JavaScript's escape() using C#

Body:
I have a multiline textbox from which I am updating my sql store procedure. In my store procedure I'm sending email(Html Formated) to user via SQL Job.
Problem is when I try to put below code in my textbox my submit button is stop working and perform no action.

Set @link = '
 URL:  abc.com/default4.aspx
 ' -- For Test

I'm also tried to put validateRequest="false" in my page directive but nothing happened.

Sorry here I mentioned one thing more that when I remove
 tag from above code my submit button works fine. But when I put only
 in my ASP.Net Textbox submit button again perform no action on submit.

How can I able to insert HTML Tags in ASP.Net Textbox.

Also I found below links regarding to my question but these links not works for me.

Allow HTML tags in TextBox control

ASP.Net Text with LineBreak from Multi-Line-TextBox to save in a database

ASP.NET Replacing Line Break with HTML br not working

Body:
After spending some time on internet I found my answer.

Here I'm sharing my findings.

I put below in my page header

<script>
    function fnescape() {
        document.getElementById('myTextBox1').value = window.escape(document.getElementById('myTextBox1').value);
    };

    function fnunescape() {
        document.getElementById('myTextBox1').value = window.unescape(document.getElementById('myTextBox1').value);
    }
</script>

and put below code before closing body tag

<script>
    fnunescape();
</script>

set ClientIDMode="Static" to ASP.Net Textbox

Codebehind:

put below code inside submit button clicked

var query = System.Uri.UnescapeDataString(txtInsertQuery.Text.ToString().Trim());

Reference Link

Unescape JavaScript's escape() using C#


问:
how to represent members in a list of list as a list in python
I have a list of lists. How can I get a specific index members in each element as a list without using a loop and assignment. Below code snippet is an example. Actual list contains more than 3 sublists. Output should be like a list say mem_lst given below.</p>

```<code>    alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
    o/p: mem_lst = [ 'abc', 'cde', 'xyz']
</code>```

Body:
I have a list of lists. How can I get a specific index members in each element as a list without using a loop and assignment. Below code snippet is an example. Actual list contains more than 3 sublists. Output should be like a list say mem_lst given below.

    alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
    o/p: mem_lst = [ 'abc', 'cde', 'xyz']

Body:
You could do this, in python 2.x,

zip(*alst)[0]

>>> lst = [['abc', 1, 2], ['cde', 2, 2], ['xyz', 2, 2]]
>>> zip(*lst)[0]
('abc', 'cde', 'xyz')
>>>

In python 3, you can do it just like this,

list(zip(*alst))[0]

>>> lst
[['abc', 1, 2], ['cde', 2, 2], ['xyz', 2, 2]]
>>> list(zip(*lst))[0]
('abc', 'cde', 'xyz')
>>>