问:
Knowing about Sticky intent in Android
In android there are 3 kinds of Intents,

Intent,

Sticky Intent,

Pending intent.

so What is sticky intent?

答: Sticky Intent allows a communication between function and a service sendStickyBroadcast() performs a sendBroadcast(Intent) know as sticky, the Intent you are sending stays around after the broadcast is complete so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this works the same as sendBroadcast(Intent).</p>

Title: Knowing about Sticky intent in Android


来源: stackexchange

问:
Is triple des Encryption /Decryption Support in sql server 2000?
For Example:

Here, Is this function EncryptByPassPharase() support in sql server 2000? If Not Then is there any function like that in sql server 2000? How Can I do same thing in sql server 2000?

```<code>INSERT INTO  login_details(username,password) VALUES('smith2',EncryptByPassPhrase('12','XXX'))
</code>```

答: No, the function EncryptByPassPharase() is not support for SQL Server <  2008. On microsoft doc has been detail about it. You can se more detail here ENCRYPTBYPASSPHRASE</p>

ContentLicense: CC BY-SA 3.0

Body:
For Example:

Here, Is this function EncryptByPassPharase() support in sql server 2000? If Not Then is there any function like that in sql server 2000? How Can I do same thing in sql server 2000?

INSERT INTO  login_details(username,password) VALUES('smith2',EncryptByPassPhrase('12','XXX'))


问:
Cross-compiling OpenSSH for Android fails in getrrsetbyname.c
I'm trying to cross-compile OpenSSH 7.6p1 for Android. It fails in getrrsetbyname.c. Here's the clang-output for that file:

```<code>(cd openbsd-compat && /Applications/Xcode.app/Contents/Developer/usr/bin/make)
/Users/johannes/src/android_ssh/android_ndk_arm_api21/bin/clang -I/Users/johannes/src/android_ssh/prefix/include -pipe -Qunused-arguments -Wunknown-warning-option -Wall -Wpointer-arith -Wuninitialized -Wsign-compare -Wformat-security -Wsizeof-pointer-memaccess -Wno-pointer-sign -Wno-unused-result -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -fno-builtin-memset -fstack-protector-strong   -I. -I.. -I. -I./.. -I~/src/android_ssh/prefix/include/openssl  -DHAVE_CONFIG_H -c getrrsetbyname.c
getrrsetbyname.c:219:12: error: incomplete definition of type 'struct state'
        if ((_resp->options & RES_INIT) == 0 && res_init() == -1) {
             ~~~~~^
getrrsetbyname.c:71:8: note: forward declaration of 'struct state'
struct __res_state _res;
       ^
../config.h:1785:21: note: expanded from macro '__res_state'
#define __res_state state
                    ^
getrrsetbyname.c:219:24: error: use of undeclared identifier 'RES_INIT'
        if ((_resp->options & RES_INIT) == 0 && res_init() == -1) {
                              ^
getrrsetbyname.c:71:20: error: tentative definition has type 'struct state' that is never completed
struct __res_state _res;
                   ^
getrrsetbyname.c:71:8: note: forward declaration of 'struct state'
struct __res_state _res;
       ^
../config.h:1785:21: note: expanded from macro '__res_state'
#define __res_state state
                    ^
3 errors generated.
make[1]: *** [getrrsetbyname.o] Error 1
make: *** [openbsd-compat/libopenbsd-compat.a] Error 2
</code>```

So it's missing a constant (RES_INIT) and a struct (struct __res_state) which are, at least on macOS and probably also on Linux, defined in the system resolv.h. However, the resolv.h in Android's NDK doesn't define those.

Am I missing something, or is getrssetbyname.c just not compatible in its current form with Android NDK?

答: If anyone is interested in cross-compiling OpenSSH for Android, I suggest to take a look into the Termux project, especially into termux-packages. </p>

Body:
I'm trying to cross-compile OpenSSH 7.6p1 for Android. It fails in getrrsetbyname.c. Here's the clang-output for that file:

(cd openbsd-compat && /Applications/Xcode.app/Contents/Developer/usr/bin/make)
/Users/johannes/src/android_ssh/android_ndk_arm_api21/bin/clang -I/Users/johannes/src/android_ssh/prefix/include -pipe -Qunused-arguments -Wunknown-warning-option -Wall -Wpointer-arith -Wuninitialized -Wsign-compare -Wformat-security -Wsizeof-pointer-memaccess -Wno-pointer-sign -Wno-unused-result -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -fno-builtin-memset -fstack-protector-strong   -I. -I.. -I. -I./.. -I~/src/android_ssh/prefix/include/openssl  -DHAVE_CONFIG_H -c getrrsetbyname.c
getrrsetbyname.c:219:12: error: incomplete definition of type 'struct state'
        if ((_resp->options & RES_INIT) == 0 && res_init() == -1) {
             ~~~~~^
getrrsetbyname.c:71:8: note: forward declaration of 'struct state'
struct __res_state _res;
       ^
../config.h:1785:21: note: expanded from macro '__res_state'
#define __res_state state
                    ^
getrrsetbyname.c:219:24: error: use of undeclared identifier 'RES_INIT'
        if ((_resp->options & RES_INIT) == 0 && res_init() == -1) {
                              ^
getrrsetbyname.c:71:20: error: tentative definition has type 'struct state' that is never completed
struct __res_state _res;
                   ^
getrrsetbyname.c:71:8: note: forward declaration of 'struct state'
struct __res_state _res;
       ^
../config.h:1785:21: note: expanded from macro '__res_state'
#define __res_state state
                    ^
3 errors generated.
make[1]: *** [getrrsetbyname.o] Error 1
make: *** [openbsd-compat/libopenbsd-compat.a] Error 2

So it's missing a constant (RES_INIT) and a struct (struct __res_state) which are, at least on macOS and probably also on Linux, defined in the system resolv.h. However, the resolv.h in Android's NDK doesn't define those.

Am I missing something, or is getrssetbyname.c just not compatible in its current form with Android NDK?


问:
Number of days in particular month of particular year?
How to know how many days has particular month of particular year?</p>

```<code>String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this
</code>```

答:
```<code>public class Main {

    private static LocalDate local=LocalDate.now();
    public static void main(String[] args) {

            int month=local.lengthOfMonth();
            System.out.println(month);

    }
}
</code>```

Body:
How to know how many days has particular month of particular year?

String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this


问:
Windows Phone 7 mocking framework?
Are there any mocking frameworks for Windows Phone 7 or do I need to create fakes manually?

I've not found any on google, and although I found Moq listed on WP7 resources page, I couldn't get it working.

答:
There are no Mocking frameworks that support WP7 and I suspect there will never be any until WP7 supports Reflection.Emit.

On the .net framework there are many options that exist for the creation of a mocking framework (Profiler API, CodeDem, Refleciton.Emit, et al). The majority of these techniques won't work on Silverlight itself as it's missing quite a lot of the BCL/CLR. All existing Silverlight mocking frameworks use Reflection.Emit. WP7 does not support Reflection.Emit and thus no Silverlight mocking framework will work on WP7.

Because of that reason, I personally test WP7 assemblies on the Silverlight runtime. It's far from optimal (it sucks), but it's the best that can be done under the circumstances.

One could theoretically build a Mocking framework that uses Post-Build MSIL weaving that should work on WP7, but it's yet to be done.

If you'd like WP7 to support Reflection.Emit consider voting on this uservoice issue: WP7 should support Reflection.Emit for Mocking frameworks

EDIT 2/12/2011: Refleciton.Emit is supported on Mango. Hooray! Reflection.Emit based Mocking frameworks should just work.

ContentLicense: CC BY-SA 2.5

Title: Windows Phone 7 mocking framework?


问:
search in a text field which contains json
My Application is in RoR and DB is in MYSQL. I have  a User Table. It contains a field name. Its type is text.
It contains the value like {"first_name"=> 'Allen', "last_name"=> 'PAul'} and some other information.

I am able to store the same in DB by using store: accessors: [], coder: JSON.

Now, I want to retrive all records whose first_name == 'Allen'. So how to achieve this in rails

答:
I don't think you'll be able to search in JSON fields with classic ActiveRecord.

But you can execute raw sql:

edit: Your name field must be a json field.

```<code>@users = ActiveRecord::Base.connection.execute("SELECT * FROM users WHERE JSON_SEARCH(name, 'all', '#{first_name_to_search}') IS NOT NULL;")
</code>```

more info here

Body:
I don't think you'll be able to search in JSON fields with classic ActiveRecord.

But you can execute raw sql:

edit: Your name field must be a json field.

@users = ActiveRecord::Base.connection.execute("SELECT * FROM users WHERE JSON_SEARCH(name, 'all', '#{first_name_to_search}') IS NOT NULL;")

more info here


问:
< followed by space or not in regex
I have a multi-line textbox, if I enter below string:

```<code>index a<3

2<x
</code>```

By using regex I need to add space after character '<' if there is no space.
And if already have space after character '<' then keep as it is don't add additional space.

Expected result should be:

```<code>index a< 3

2< x
</code>```

I tried (?<=<)(?!$) and <[^\s]+  these but giving syntax error, when used inside Javascript.

I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.

答:
You can use \S to match any non-space character(which is a short handler for a negated character class, [^\s]). Since Javascript doesn't support look-behind you need to match < symbol followed by non-space character and then replace it with space contained < symbol.

```<code>str = str.replace(/<(?=\S)/g, '< ');

// or with negative lookahead
str = str.replace(/<(?!\s)/g, '< ');
</code>```

var str = 'index a<3\n2<x';

console.log(
  str.replace(/<(?=\S)/g, '< '),
  '\n\n',
  str.replace(/<(?!\s)/g, '< ')
)```

Title: < followed by space or not in regex

Body:
I have a multi-line textbox, if I enter below string:

index a<3

2<x

By using regex I need to add space after character '<' if there is no space.
And if already have space after character '<' then keep as it is don't add additional space.

Expected result should be:

index a< 3

2< x

I tried (?<=<)(?!$) and <[^\s]+  these but giving syntax error, when used inside Javascript.

I can use them in back end(C#) but I don't want to put server request for it, as it not a good option.

Body:
You can use \S to match any non-space character(which is a short handler for a negated character class, [^\s]). Since Javascript doesn't support look-behind you need to match < symbol followed by non-space character and then replace it with space contained < symbol.

str = str.replace(/<(?=\S)/g, '< ');

// or with negative lookahead
str = str.replace(/<(?!\s)/g, '< ');

var str = 'index a<3\n2<x';

console.log(
  str.replace(/<(?=\S)/g, '< '),
  '\n\n',
  str.replace(/<(?!\s)/g, '< ')
)


问:
How to read the state of current permission status?
In my app, I need GPS to locate the user. I wish my app provide following kinds of result.

```<code>1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)
</code>```

I use LocationManager to do the job.

```<code>locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
</code>```

If the permission is denied, the location will be null.

But I don't know what the location will be if the function failed. And I 'm not sure whether that location is null and user refuse to open GPS are equal.

With the following code, I might know whether the permission is added in the AndroidManifest.xml. But I can't get the information I need.

```<code>boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));
</code>```

答:
First implement an onRequestPermissionResult like this:</p>

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
            String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, do your stuff!
                locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                } else {
                //location wasn't found
                }

            } else {

               //user denied permission additionally you can check
               //ActivityCompat.shouldShowRequestPermissionRationale if user checked on "do not show again" while clicking deny
            }
            return;
        }
     }
}
</code>```

Body:
In my app, I need GPS to locate the user. I wish my app provide following kinds of result.

1.The current location.(Success)
2.Failed to get current location because of device error or something else. (Failed)
3.The user refused the permission. (Permission denied)

I use LocationManager to do the job.

locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

If the permission is denied, the location will be null.

But I don't know what the location will be if the function failed. And I 'm not sure whether that location is null and user refuse to open GPS are equal.

With the following code, I might know whether the permission is added in the AndroidManifest.xml. But I can't get the information I need.

boolean getLocationOn = (PackageManager.PERMISSION_GRANTED ==
           pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "my_package"));

Body:
First implement an onRequestPermissionResult like this:

@Override
public void onRequestPermissionsResult(int requestCode,
            String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, do your stuff!
                locationManager = (LocationManager)mActivity.getSystemService(Context.LOCATION_SERVICE);
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                } else {
                //location wasn't found
                }

            } else {

               //user denied permission additionally you can check
               //ActivityCompat.shouldShowRequestPermissionRationale if user checked on "do not show again" while clicking deny
            }
            return;
        }
     }
}


问:
Only display the values to the right of a Decimal Number
I use SQL Server 2005 and need to test whether values in a column that's metadata has been specified as DECIMAL(18.3) actually contains data that has values to the right of the Decimal point, and if so, what these values are.

I've read a few articles that only discuss how to drop off the decimal places or how to round the values, but not how to ONLY display what is stored to the right of the decimal point.

Your help would be greatly appreciated.

Kind Regards,

Ignacio.

答:
Try:</p>

```<code>SELECT a - FLOOR(a)
FROM ...
</code>```

OwnerDisplayName: Ignacio

LastEditorDisplayName: cletus

Body:
Try:

SELECT a - FLOOR(a)
FROM ...

OwnerDisplayName: cletus


问:
What is wrong with using 'Not In' in this SQL query?
I have table called BST as shown below:

Here N is value of node of Binary Tree and P is its Parent node. I have to write a query that will determine if a node is a Root Node, Leaf Node or Inner Node. I wrote below SQL query for this:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST) then 'Leaf'
end as type
from BST
</code>```

However, this is not giving me desired result as last condition for 'Leaf' in Case statement doesn't satisfy for leaf node. I am getting below output in this case:

I have a workaround for now as below query which is giving me expected output:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
else 'Leaf'
end as type
from BST
</code>```

Expected Output:

But I can't figure out what's wrong with the first one. Could someone explain me this?

答:
Try this:

```<code>DECLARE @DataSource TABLE
(
    [N] TINYINT
   ,[P] TINYINT
);

INSERT INTO @DataSource ([N], [P])
VALUES (1, 2)
      ,(3, 2)
      ,(5, 6)
      ,(7, 6)
      ,(2, 4)
      ,(6, 4)
      ,(4, 15)
      ,(8, 9)
      ,(10, 9)
      ,(12, 13)
      ,(14, 13)
      ,(9, 11)
      ,(13, 11)
      ,(11, 15)
      ,(15, NULL);

SELECT DISTINCT
       DS1.[N]
      ,CASE WHEN DS2.[N] IS NULL THEN 'IsLeaf' ELSE CASE WHEN DS3.[N] IS NOT NULL THEN 'Inner' ELSE ' Root' END END AS [Type]
FROM @DataSource DS1
LEFT JOIN @DataSource DS2
    ON DS1.[N] = DS2.[P]
LEFT JOIN @DataSource DS3
    ON DS1.[P] = DS3.[N]
ORDER BY [Type];
</code>```

The idea is to use two LEFT JOINs in order to see if the current node is child and if the current not is parent.

Body:
I have table called BST as shown below:

Here N is value of node of Binary Tree and P is its Parent node. I have to write a query that will determine if a node is a Root Node, Leaf Node or Inner Node. I wrote below SQL query for this:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST) then 'Leaf'
end as type
from BST

However, this is not giving me desired result as last condition for 'Leaf' in Case statement doesn't satisfy for leaf node. I am getting below output in this case:

I have a workaround for now as below query which is giving me expected output:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
else 'Leaf'
end as type
from BST

Expected Output:

But I can't figure out what's wrong with the first one. Could someone explain me this?

Body:
Try this:

DECLARE @DataSource TABLE
(
    [N] TINYINT
   ,[P] TINYINT
);

INSERT INTO @DataSource ([N], [P])
VALUES (1, 2)
      ,(3, 2)
      ,(5, 6)
      ,(7, 6)
      ,(2, 4)
      ,(6, 4)
      ,(4, 15)
      ,(8, 9)
      ,(10, 9)
      ,(12, 13)
      ,(14, 13)
      ,(9, 11)
      ,(13, 11)
      ,(11, 15)
      ,(15, NULL);

SELECT DISTINCT
       DS1.[N]
      ,CASE WHEN DS2.[N] IS NULL THEN 'IsLeaf' ELSE CASE WHEN DS3.[N] IS NOT NULL THEN 'Inner' ELSE ' Root' END END AS [Type]
FROM @DataSource DS1
LEFT JOIN @DataSource DS2
    ON DS1.[N] = DS2.[P]
LEFT JOIN @DataSource DS3
    ON DS1.[P] = DS3.[N]
ORDER BY [Type];

The idea is to use two LEFT JOINs in order to see if the current node is child and if the current not is parent.


问:
Insert and select data in sql server
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test
</code>```

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

答:
Try using this:</p>

```<code>Insert into sp_emp(empid,amount)
Select empid,amount from sp_test
</code>```

Title: Insert and select data in sql server

Body:
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

Body:
Try using this:

Insert into sp_emp(empid,amount)
Select empid,amount from sp_test


问:
Set Map Language with Bing Maps JavaScript V8 API
In Bing Maps V7 there was an mkt param to set the language of the map. This is gone in V8 and instead the browsers default language is used:

The Bing Maps v8 web control no longer requires the use of a mkt
  parameter to localize the map. If one is not provided the map will
  automatically attempt to set the language of the map based on the
  user’s browser settings and/or location.

But we need to set the language according to the website's user setting (which can be different from the browser language). Is there a way to set this using the Bing Maps V8 JavaScript API?

答:
In Bing v8 we can use setLang and setMkt parameters to override the default localization setting.

please find below example for setting localization parameters:

```<code><script type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap&setMkt=en-IN&setLang=en'
async defer>
</script>
</code>```

Please find the below link from where I found this information :
https://msdn.microsoft.com/en-us/library/mt712553.aspx#Localizing the Map

Body:
In Bing v8 we can use setLang and setMkt parameters to override the default localization setting.

please find below example for setting localization parameters:

<script type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap&setMkt=en-IN&setLang=en'
async defer>
</script>

Please find the below link from where I found this information :
https://msdn.microsoft.com/en-us/library/mt712553.aspx#Localizing the Map


答:
The problem is because one of your P values is null. Remove this by saying select distinct p from t where p is not null in at least the Not In one of your subqueries

http://sqlfiddle.com/#!6/77fb8/3

hence:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST where p is not null) then 'Leaf'
end as type
from BST
</code>```

the null P value gets included in the list of distinct values selected, and not in can not determine if a given value of N is equal/not equal to the null coming from the root node of P.

It's somewhat counter intuitive but nothing is ever equal to or not equal to a null, not even null. using = with one side being null results in null, not true and not false

IN can be used to check if a value IS in the list, but not if it's not, if the list includes a null

```<code>1 IN (1,2,null) --true
3 IN (1,2,null) --null, not false, null which isn't true
3 NOT IN (1,2,null) --null, not false, null which isn't true
</code>```

The ELSE form is the way to go here. Or put the disctinct query in as a subquery in the FROM block and do a left join to it

Title: What is wrong with using 'Not In' in this SQL query?

Body:
The problem is because one of your P values is null. Remove this by saying select distinct p from t where p is not null in at least the Not In one of your subqueries

http://sqlfiddle.com/#!6/77fb8/3

hence:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST where p is not null) then 'Leaf'
end as type
from BST

the null P value gets included in the list of distinct values selected, and not in can not determine if a given value of N is equal/not equal to the null coming from the root node of P.

It's somewhat counter intuitive but nothing is ever equal to or not equal to a null, not even null. using = with one side being null results in null, not true and not false

IN can be used to check if a value IS in the list, but not if it's not, if the list includes a null

1 IN (1,2,null) --true
3 IN (1,2,null) --null, not false, null which isn't true
3 NOT IN (1,2,null) --null, not false, null which isn't true

The ELSE form is the way to go here. Or put the disctinct query in as a subquery in the FROM block and do a left join to it


问:
How to use threshold to remove false positives?
I am using OpenCV EM to segment a image on the HSV domain. Therefore, the segmentation detect some false positives [Highlights in Yellow]. Below, you can see the input image.

And below, the image segmented with false positives.

I try to remove it by using threshold as you can see without success.

Any help on how to keep only the Leaf will be appreciated!

答:
The "false positives" you see are compression artefacts caused by JPEG compression.

https://en.wikipedia.org/wiki/JPEG

You cannot segment this perfectly in Hue or Saturation channel.

Ideally process uncompressed images or use brightness information which usually is preserved in higher frequencies than colour.

Unfortunately you did not provide the actual input image so I cannot help you any further.


问:
inability to read from a file corectly in C
Hey guys im new here and im working on some code that is meant to read in 2 files.  The file opens just fine, everything gets allocated ok later on down the line, however, when I read in individual lines from the file thats when I run into issues.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
char filename1[100];
    //Seting the file name for entery and seting the limit to 100
    //this one is for my matrix//
FILE* fp1;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename1);
    //scans in the name of the first file the file type needs to be
included//

fp1 = fopen(filename1, "r");
    //This will open the file as entered by the user//
if (fp1 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
int i;
int row1;
int col1;

fscanf(fp1, "%d,", &row1);
printf("%d \n ", row1);
fscanf(fp1, "%d,", &col1);  //WHY IS THIS SCANING WRONG!!!!//
printf("%d \n ", col1);
    //This will scan for the number of rows and columns in the matrix//
    //thats all for reading in the first file//

char filename2[100];
    //Seting the file name for entery and seting the limit to 100//
FILE* fp2;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename2);
    //Scans in the name of the first file//

fp2 = fopen(filename2, "r");
    //This will open the file as entered by the user//
if (fp2 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
return 0;
}
</code>```

This is what I get when i compile and run the full program.  compiling

What should appear is a 5 and a 3 after loading in the data file.

the data is in the attached image but also here:

```<code>5
3
3.4,  6.5,  4.1
1.8,  3.3,  4.5
2.6,  7.4,  4.9
5.5,  6.1,  2.4
1.9,  2.7,  4.2
</code>```

Everything else in my code works just fine with the exception of that.

答:
Okay so based on your input this is is a minimal working code </p>

```<code>    int i, j;
    int row1;
    int col1;
    float v;
    fscanf(fp1, "%d\n", &row1);
    fscanf(fp1, "%d\n", &col1);

    for ( i = 0 ; i < row1; i ++ )
    {
            for( j = 0 ; j < col1; j ++ )
            {
                    fscanf(fp1, "%f, ", &v);
            }
    }
</code>```

Body:
Hey guys im new here and im working on some code that is meant to read in 2 files.  The file opens just fine, everything gets allocated ok later on down the line, however, when I read in individual lines from the file thats when I run into issues.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
char filename1[100];
    //Seting the file name for entery and seting the limit to 100
    //this one is for my matrix//
FILE* fp1;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename1);
    //scans in the name of the first file the file type needs to be
included//

fp1 = fopen(filename1, "r");
    //This will open the file as entered by the user//
if (fp1 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
int i;
int row1;
int col1;

fscanf(fp1, "%d,", &row1);
printf("%d \n ", row1);
fscanf(fp1, "%d,", &col1);  //WHY IS THIS SCANING WRONG!!!!//
printf("%d \n ", col1);
    //This will scan for the number of rows and columns in the matrix//
    //thats all for reading in the first file//

char filename2[100];
    //Seting the file name for entery and seting the limit to 100//
FILE* fp2;
    //FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
    //This will pull in the name entered by the user//
scanf("%s", filename2);
    //Scans in the name of the first file//

fp2 = fopen(filename2, "r");
    //This will open the file as entered by the user//
if (fp2 == NULL)
{
    printf("\nError, file not found\n");
    exit(0);
}
return 0;
}

This is what I get when i compile and run the full program.  compiling

What should appear is a 5 and a 3 after loading in the data file.

the data is in the attached image but also here:

5
3
3.4,  6.5,  4.1
1.8,  3.3,  4.5
2.6,  7.4,  4.9
5.5,  6.1,  2.4
1.9,  2.7,  4.2

Everything else in my code works just fine with the exception of that.

Body:
Okay so based on your input this is is a minimal working code

    int i, j;
    int row1;
    int col1;
    float v;
    fscanf(fp1, "%d\n", &row1);
    fscanf(fp1, "%d\n", &col1);

    for ( i = 0 ; i < row1; i ++ )
    {
            for( j = 0 ; j < col1; j ++ )
            {
                    fscanf(fp1, "%f, ", &v);
            }
    }


问:
Is it possible to implement voice chat in a browser without plugins?
CampFireNow has a voice chat over the browser. It seems that you do not need any plugins to install to get it working. This is a contrast to Gmail, where I needed to install an app.

I would like to implement a similar feature for my application.  Is there a way to do this without requiring a plugin?

答:
In case anyone comes looking for a possible solution, WebRTC lets you do just that. For more info, visit https://webrtc.org/

From the website, "WebRTC is a free, open project that provides browsers and mobile applications with Real-Time Communications (RTC) capabilities via simple APIs. The WebRTC components have been optimized to best serve this purpose."


答:
You can use the following, using only the needed columns:

```<code>INSERT INTO sp_emp (empid, amount)
SELECT empid, amount FROM sp_test
</code>```

This INSERT INTO command is only working if the other columns of sp_emp are nullable or a DEFAULT value is available. If a columns is not nullable and there is no DEFAULT value set you have to specifiy a valid value for the column. You only need to define columns in the INSERT INTO column list if there is no default value and the column is not nullable.

To set a value you can add the value to the SELECT column list as value:

```<code>INSERT INTO sp_emp (empid, amount, regisno, itemid, year, month, week,paymentdate)
SELECT empid, amount, 1, 1, 2017, 11, 40, '2017-11-14' FROM sp_test
</code>```

Title: Insert and select data in sql server

Body:
You can use the following, using only the needed columns:

INSERT INTO sp_emp (empid, amount)
SELECT empid, amount FROM sp_test

This INSERT INTO command is only working if the other columns of sp_emp are nullable or a DEFAULT value is available. If a columns is not nullable and there is no DEFAULT value set you have to specifiy a valid value for the column. You only need to define columns in the INSERT INTO column list if there is no default value and the column is not nullable.

To set a value you can add the value to the SELECT column list as value:

INSERT INTO sp_emp (empid, amount, regisno, itemid, year, month, week,paymentdate)
SELECT empid, amount, 1, 1, 2017, 11, 40, '2017-11-14' FROM sp_test


答:
This error occurs when the number of columns in your source list does not match the number of columns on your destination.

For example when you are trying to insert into 5 column or a table but in the select statement or values, you have specified only 4 columns or you have given 6 columns then you will get the same error.

Here, Your Query is trying to insert values to 8 Columns on the table sp_emp and for that, you are selecting all the columns from the table sp_test. So When you are doing so you must make sure that the number of columns, There order and data type match as in the destination or else you should specify the column names instead of *. So I changed your script as below - assuming that the column names are same in both tables

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
SELECT regisno,empid,itemid,year,month,week,amount,paymentdate FROM sp_test
</code>```

If there is any miss match in the data type , then you can cast the source values accordingly

Title: Insert and select data in sql server

Body:
This error occurs when the number of columns in your source list does not match the number of columns on your destination.

For example when you are trying to insert into 5 column or a table but in the select statement or values, you have specified only 4 columns or you have given 6 columns then you will get the same error.

Here, Your Query is trying to insert values to 8 Columns on the table sp_emp and for that, you are selecting all the columns from the table sp_test. So When you are doing so you must make sure that the number of columns, There order and data type match as in the destination or else you should specify the column names instead of *. So I changed your script as below - assuming that the column names are same in both tables

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
SELECT regisno,empid,itemid,year,month,week,amount,paymentdate FROM sp_test

If there is any miss match in the data type , then you can cast the source values accordingly


答:
Hope this works  </p>

```<code>User.where("name LIKE ?", , '%first_name: #{query}%')
</code>```

Title: search in a text field which contains json

Body:
My Application is in RoR and DB is in MYSQL. I have  a User Table. It contains a field name. Its type is text.
It contains the value like {"first_name"=> 'Allen', "last_name"=> 'PAul'} and some other information.

I am able to store the same in DB by using store: accessors: [], coder: JSON.

Now, I want to retrive all records whose first_name == 'Allen'. So how to achieve this in rails

Body:
Hope this works

User.where("name LIKE ?", , '%first_name: #{query}%')


问:
URL link not redirecting properly in Angularjs
I have a link in my announce.obj. But when I clicked it, it's giving me the wrong url (http://www./) in the browser.

html

```<code><p>
  <a ng-href="{{data.links}}" target="_blank">{{data.links}}</a>
</p>
</code>```

data.links value

```<code>www.google.com
</code>```

Should I add an https when saving my links in the db or something ?

答:
Try this like $scope.myVar = 'https://www.w3schools.com';:

var app = angular.module('myAngularApp', []);

var myController = app.controller('myController', MyController);

myController.$inject = ['$scope'];

function MyController($scope){

    $scope.myVar = 'https://www.w3schools.com';

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html>

<body ng-app="myAngularApp">

<div ng-controller = "myController">
<h1>Tutorials</h1>
<p>Go to {{myVar}} to learn!</p>
</div>

<p>This example could use the original href attribute, but in AngularJS, the ng-href attribute is safer.</p>

</body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a link in my announce.obj. But when I clicked it, it's giving me the wrong url (http://www./) in the browser.

html

  {{data.links}}

data.links value

www.google.com

Should I add an https when saving my links in the db or something ?

Body:
Try this like $scope.myVar = 'https://www.w3schools.com';:

var app = angular.module('myAngularApp', []);

var myController = app.controller('myController', MyController);

myController.$inject = ['$scope'];

function MyController($scope){

    $scope.myVar = 'https://www.w3schools.com';

}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html>

<body ng-app="myAngularApp">

<div ng-controller = "myController">
<h1>Tutorials</h1>
<p>Go to <a ng-href="{{myVar}}">{{myVar}}</a> to learn!</p>
</div>

<p>This example could use the original href attribute, but in AngularJS, the ng-href attribute is safer.</p>

</body>
</html>


问:
Custom bootloader booted via USB drive produces incorrect output on some computers
I am fairly new to assembly, but I'm trying to dive into the world of low level computing. I'm trying to learn how to write assembly code that would run as bootloader code; so independent of any other OS like Linux or Windows. After reading this page and a few other lists of x86 instruction sets, I came up with some assembly code that is supposed to print 10 A's on the screen and then 1 B.

```<code>      BITS 16
start:
    mov ax, 07C0h       ; Set up 4K stack space after this bootloader
    add ax, 288     ; (4096 + 512) / 16 bytes per paragraph
    mov ss, ax
    mov sp, 4096

    mov ax, 07C0h       ; Set data segment to where we're loaded
    mov ds, ax

    mov cl, 10          ; Use this register as our loop counter
    mov ah, 0Eh         ; This register holds our BIOS instruction

.repeat:
    mov al, 41h         ; Put ASCII 'A' into this register
    int 10h             ; Execute our BIOS print instruction
    cmp cl, 0           ; Find out if we've reached the end of our loop
    dec cl              ; Decrement our loop counter
    jnz .repeat         ; Jump back to the beginning of our loop
    jmp .done           ; Finish the program when our loop is done

.done:
    mov al, 42h         ; Put ASCII 'B' into this register
    int 10h             ; Execute BIOS print instruction
    ret

times 510-($-$$) db 0   ; Pad remainder of boot sector with 0s
dw 0xAA55
</code>```

So the output should look like this:

```<code>AAAAAAAAAAB
</code>```

I assembled the code using the nasm assembler running on the Windows 10 Ubuntu Bash program. After it produced the .bin file, I opened it using a hex editor. I used the same hex editor to copy the contents of that .bin file into the first 512 bytes of a flash drive. Once I had written my program to the flash drive, I disconnected it and plugged it into a computer with an Intel Core i3-7100. On bootup, I selected my USB flash drive as the boot device, only to get the following output:

```<code>A
</code>```

After changing various things in the program, I finally got frustrated and tried the program on another computer. The other computer was a laptop with an i5-2520m. I followed the same process as I mentioned before. Sure enough, it gave me the expected output:

```<code>AAAAAAAAAAB
</code>```

I immediately tried it on my original computer with the i3, but it still didn't work.

So my question is: Why does my program work with one x86 processor but not the other? They both support the x86 instruction set. What gives?

Solution:

Ok, I've been able to track down the real solution with some help. If you read Michael Petch's answer below, you'll find a solution that will fix my problem, and another problem of a BIOS looking for a BPB.

Here was the problem with my code: I was writing the program to the first bytes of my flash drive. Those bytes were loaded into memory, but some BIOS interrupts were using those bytes for itself. So my program was being overwritten by the BIOS. To prevent this, you can add a BPB description as shown below. If your BIOS works the same way mine does, it will simply overwrite the BPB in memory, but not your program. Alternatively, you can add the following code to the top of your program:

```<code>jmp start
resb 0x50

start:
;enter code here
</code>```

This code (courtesy of Ross Ridge) will push your program to memory location 0x50 (offset from 0x7c00) to prevent it from being overwritten by the BIOS during execution.

Also keep in mind that whenever you call any subroutine, the values of the registers you were using could be overwritten. Make sure you either use push, pop or save your values to memory before calling a subroutine. Look at Martin Rosenau's answer below to read more about that.

Thank you to all who replied to my question. I now have a better understanding of how this low-level stuff works.

答:
Assembly code only works on one of my two x86 processors

It is not the processors but the BIOSes:

The int instruction actually is a special variant of the call instruction. The instruction calls some sub-routine (typically written in assembler).

(You can even replace that sub-routine by your own one - which is actually done by MS-DOS, for example.)

On two computers you have two different BIOS versions (or even vendors) which means that the sub-routine called by the int 10h instruction has been written by different programmers and therefore does not exactly do the same.

only to get the following output

The problem I suspect here is that the sub-routine called by int 10h on the first computer does not save the register values while the routine on the second computer does.

In other words:

On the first computer the routine called by int 10h may look like this:

```<code>...
mov cl, 5
mov ah, 6
...
</code>```

... so after the int 10h call the ah register does no longer contain the value 0Eh and it may even be the case that the cl register is modified (which will end in an endless loop then).

To avoid the problem you could save the cl register using push (you have to save the entire cx register) and restore it after the int instruction. You also have to set the value of the ah register before each call of the int 10h sub-routine because you cannot be sure that it has not modified since then:

```<code>push cx
mov ah, 0Eh
int 10h
pop cx
</code>```

mov sp, ... ... ret

Please think about Peter Cordes' comment:

How does the ret instruction work and how is it related to the sp and ss registers?

The ret instruction here will definitely not do what you expect!

On floppy disks the boot sectors typically contain the following code instead:

```<code>mov ax, 0  ; (may be written as "xor ax, ax")
int 16h
int 19h
</code>```

int 19h does exactly what you expect from the ret instruction.

However the BIOS will boot the computer again which means that it will load the code from your USB stick and execute it again.

You'll get the following result:

AAAAABAAAAABAAAAABAAAAAB...

Therefore the int 16h instruction is inserted. This will wait for the user to press a key on the keyboard when the ax register has the value 0 before calling the int 16h sub-routine.

Alternatively you can simply add an endless loop:

```<code>.endlessLoop:
    jmp .endlessLoop
</code>```

mov ss, ...

When an interrupt occurs between these two instructions:

```<code>mov ss, ax
    ; <--- Here
mov sp, 4096
</code>```

... the combination of the sp and ss registers does not represent a "valid" representation of values.

If you are unlucky the interrupt will write data somewhere to memory where you don't want it. It may even overwrite your program!

Therefore you typically lock interrupts when modifying the ss register:

```<code>cli          ; Forbid interrupts
mov ss, ax
mov sp, 4096
sti          ; Allow interrupts again
</code>```

Body:
I am fairly new to assembly, but I'm trying to dive into the world of low level computing. I'm trying to learn how to write assembly code that would run as bootloader code; so independent of any other OS like Linux or Windows. After reading this page and a few other lists of x86 instruction sets, I came up with some assembly code that is supposed to print 10 A's on the screen and then 1 B.

      BITS 16
start:
    mov ax, 07C0h       ; Set up 4K stack space after this bootloader
    add ax, 288     ; (4096 + 512) / 16 bytes per paragraph
    mov ss, ax
    mov sp, 4096

    mov ax, 07C0h       ; Set data segment to where we're loaded
    mov ds, ax

    mov cl, 10          ; Use this register as our loop counter
    mov ah, 0Eh         ; This register holds our BIOS instruction

.repeat:
    mov al, 41h         ; Put ASCII 'A' into this register
    int 10h             ; Execute our BIOS print instruction
    cmp cl, 0           ; Find out if we've reached the end of our loop
    dec cl              ; Decrement our loop counter
    jnz .repeat         ; Jump back to the beginning of our loop
    jmp .done           ; Finish the program when our loop is done

.done:
    mov al, 42h         ; Put ASCII 'B' into this register
    int 10h             ; Execute BIOS print instruction
    ret

times 510-($-$$) db 0   ; Pad remainder of boot sector with 0s
dw 0xAA55

So the output should look like this:

AAAAAAAAAAB

I assembled the code using the nasm assembler running on the Windows 10 Ubuntu Bash program. After it produced the .bin file, I opened it using a hex editor. I used the same hex editor to copy the contents of that .bin file into the first 512 bytes of a flash drive. Once I had written my program to the flash drive, I disconnected it and plugged it into a computer with an Intel Core i3-7100. On bootup, I selected my USB flash drive as the boot device, only to get the following output:

A

After changing various things in the program, I finally got frustrated and tried the program on another computer. The other computer was a laptop with an i5-2520m. I followed the same process as I mentioned before. Sure enough, it gave me the expected output:

AAAAAAAAAAB

I immediately tried it on my original computer with the i3, but it still didn't work.

So my question is: Why does my program work with one x86 processor but not the other? They both support the x86 instruction set. What gives?

Solution:

Ok, I've been able to track down the real solution with some help. If you read Michael Petch's answer below, you'll find a solution that will fix my problem, and another problem of a BIOS looking for a BPB.

Here was the problem with my code: I was writing the program to the first bytes of my flash drive. Those bytes were loaded into memory, but some BIOS interrupts were using those bytes for itself. So my program was being overwritten by the BIOS. To prevent this, you can add a BPB description as shown below. If your BIOS works the same way mine does, it will simply overwrite the BPB in memory, but not your program. Alternatively, you can add the following code to the top of your program:

jmp start
resb 0x50

start:
;enter code here

This code (courtesy of Ross Ridge) will push your program to memory location 0x50 (offset from 0x7c00) to prevent it from being overwritten by the BIOS during execution.

Also keep in mind that whenever you call any subroutine, the values of the registers you were using could be overwritten. Make sure you either use push, pop or save your values to memory before calling a subroutine. Look at Martin Rosenau's answer below to read more about that.

Thank you to all who replied to my question. I now have a better understanding of how this low-level stuff works.

Body:
Assembly code only works on one of my two x86 processors

It is not the processors but the BIOSes:

The int instruction actually is a special variant of the call instruction. The instruction calls some sub-routine (typically written in assembler).

(You can even replace that sub-routine by your own one - which is actually done by MS-DOS, for example.)

On two computers you have two different BIOS versions (or even vendors) which means that the sub-routine called by the int 10h instruction has been written by different programmers and therefore does not exactly do the same.

only to get the following output

The problem I suspect here is that the sub-routine called by int 10h on the first computer does not save the register values while the routine on the second computer does.

In other words:

On the first computer the routine called by int 10h may look like this:

...
mov cl, 5
mov ah, 6
...

... so after the int 10h call the ah register does no longer contain the value 0Eh and it may even be the case that the cl register is modified (which will end in an endless loop then).

To avoid the problem you could save the cl register using push (you have to save the entire cx register) and restore it after the int instruction. You also have to set the value of the ah register before each call of the int 10h sub-routine because you cannot be sure that it has not modified since then:

push cx
mov ah, 0Eh
int 10h
pop cx

mov sp, ... ... ret

Please think about Peter Cordes' comment:

How does the ret instruction work and how is it related to the sp and ss registers?

The ret instruction here will definitely not do what you expect!

On floppy disks the boot sectors typically contain the following code instead:

mov ax, 0  ; (may be written as "xor ax, ax")
int 16h
int 19h

int 19h does exactly what you expect from the ret instruction.

However the BIOS will boot the computer again which means that it will load the code from your USB stick and execute it again.

You'll get the following result:

AAAAABAAAAABAAAAABAAAAAB...

Therefore the int 16h instruction is inserted. This will wait for the user to press a key on the keyboard when the ax register has the value 0 before calling the int 16h sub-routine.

Alternatively you can simply add an endless loop:

.endlessLoop:
    jmp .endlessLoop

mov ss, ...

When an interrupt occurs between these two instructions:

mov ss, ax
    ; <--- Here
mov sp, 4096

... the combination of the sp and ss registers does not represent a "valid" representation of values.

If you are unlucky the interrupt will write data somewhere to memory where you don't want it. It may even overwrite your program!

Therefore you typically lock interrupts when modifying the ss register:

cli          ; Forbid interrupts
mov ss, ax
mov sp, 4096
sti          ; Allow interrupts again


问:
Logstash with Windows shows JAVA error
Logstash is giving me this error: "Cannot find Java 1.5 or higher."

The command I'm running is "bin\logstash -f \mypath\logstash-simple.conf"

I DO NOT have ruby installed on my windows 10 computer.
I have JAVA my PATH. "C:\Program Files\Java\jre1.8.0_151\bin"

How do I fix this issue? Do I need ruby?

答:
You need to set both the Java_Home property and add in PATH property such as mentioned below:-</p>

```<code>JAVA_HOME = C:\Program Files\Java\jre1.8.0_151
PATH = C:\Program Files\Java\jre1.8.0_151\bin
</code>```

Title: Logstash with Windows shows JAVA error

Body:
You need to set both the Java_Home property and add in PATH property such as mentioned below:-

JAVA_HOME = C:\Program Files\Java\jre1.8.0_151
PATH = C:\Program Files\Java\jre1.8.0_151\bin


问:
Get selected element type
I want to get the type of element, that I've got selected using jQuery selectors.

Markup:

```<code><select name="a"></select>
<input name="b" type="text" />
<textarea name="c"></textarea>
</code>```

Javascript:

```<code>var field_names = new Array(
    'a',
    'b',
    'c'
);

for(var i = 0; i < field_names.length; i++) {
    var field = $('[name=' + required_fields[i] + ']:visible');

    // ?????
    // What do I write here to get one of those outputs:
    //    Element with name a is <select>
    //    Element with name b is <input>
    //    Element with name c is <textarea>

    alert('Element with name ' + required_fields[i] + ' is ' + element_type);
}
</code>```

答:
Simple:

```<code>var element_type = '<' + field.get(0).tagName.toLowerCase() + '>';
</code>```

In a nutshell, this retrieves the DOM element associated with field and gets its tag name via the tagName attribute inherited from DOMElement, then transforms the result to lowercase using String's toLowerCase() method. Some browsers will return the tagName in uppercase, so for consistency you should transform it to lower case.

Title: Get selected element type

Body:
I want to get the type of element, that I've got selected using jQuery selectors.

Markup:

<select name="a"></select>
<input name="b" type="text" />
<textarea name="c"></textarea>

Javascript:

var field_names = new Array(
    'a',
    'b',
    'c'
);

for(var i = 0; i < field_names.length; i++) {
    var field = $('[name=' + required_fields[i] + ']:visible');

    // ?????
    // What do I write here to get one of those outputs:
    //    Element with name a is <select>
    //    Element with name b is <input>
    //    Element with name c is <textarea>

    alert('Element with name ' + required_fields[i] + ' is ' + element_type);
}

Body:
Simple:

var element_type = '<' + field.get(0).tagName.toLowerCase() + '>';

In a nutshell, this retrieves the DOM element associated with field and gets its tag name via the tagName attribute inherited from DOMElement, then transforms the result to lowercase using String's toLowerCase() method. Some browsers will return the tagName in uppercase, so for consistency you should transform it to lower case.


问:
How to copy one branch to other in Git
I have a branch with name A on which I have my running project. I have a friend who is working on branch B. Recently we did the major version changes in our source code, so the branch B is now up to date. I need to copy all the source code and files/folders to my branch so that branch A is sync with B and is also up to date. As I do not have much idea about git commands I simply thought of pulling the branch by using commands:

```<code>git checkout B
git pull origin B
</code>```

Now after these two commands, all the changes of B was in my branch A. But then when I switched back to my branch by using git checkout A, everything reverted back. All I want is to copy all the content of B to A.

答:
With these to commands:

```<code>git checkout B
git pull origin B
</code>```

you:

switched to branch B

synchronized the local state of branch B with it's remote state

When you run git checkout A you changed the working copy - A and B have different history - thus different files.

What you need to is to merge branch B into A or rebase it. If you are a git beginner better option is merge:

```<code>git checkout A
git merge --no-ff B
</code>```

--no-ff will add a merge commit even if the merge is a fast-forward.

Title: How to copy one branch to other in Git

Body:
I have a branch with name A on which I have my running project. I have a friend who is working on branch B. Recently we did the major version changes in our source code, so the branch B is now up to date. I need to copy all the source code and files/folders to my branch so that branch A is sync with B and is also up to date. As I do not have much idea about git commands I simply thought of pulling the branch by using commands:

git checkout B
git pull origin B

Now after these two commands, all the changes of B was in my branch A. But then when I switched back to my branch by using git checkout A, everything reverted back. All I want is to copy all the content of B to A.

Body:
With these to commands:

git checkout B
git pull origin B

you:

switched to branch B

synchronized the local state of branch B with it's remote state

When you run git checkout A you changed the working copy - A and B have different history - thus different files.

What you need to is to merge branch B into A or rebase it. If you are a git beginner better option is merge:

git checkout A
git merge --no-ff B

--no-ff will add a merge commit even if the merge is a fast-forward.


问:
PosixFilePermission causing UnsupportedOperationException in java
I have a java code deployed in windows as well as unix system.I have to add file permission for moving the file to a specific directory(in unix).I am using PosixFilePermission for this.

```<code>                file1 = new File( expFilePath+ "/" + creationDate);
                file1.mkdir();
                Set<PosixFilePermission> perms = new HashSet<>();
                perms.add(PosixFilePermission.OWNER_READ);
                perms.add(PosixFilePermission.OWNER_WRITE);
                perms.add(PosixFilePermission.OWNER_EXECUTE);
                perms.add(PosixFilePermission.OTHERS_READ);
                perms.add(PosixFilePermission.OTHERS_WRITE);
                perms.add(PosixFilePermission.OTHERS_EXECUTE);
                perms.add(PosixFilePermission.GROUP_READ);
                perms.add(PosixFilePermission.GROUP_WRITE);
                perms.add(PosixFilePermission.GROUP_EXECUTE);
                try {
                    Files.setPosixFilePermissions(file1.toPath(), perms);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
</code>```

The above code is running correctly in unix but causing a UnsupportedOperationException in windows m/c.I have to manually comment this piece of code while running the code in windows m/c.

Is there any way by which I can detect the underlying os type in java and execute this block of code conditionally?

答: If you have a Path object, you can use the Path.getFileSystem() method to obtain the underlying file system object. It has a FileSystem.supportedFileAttributeViews() method. If the file system supports POSIX file attributes (and permissions), the returned set will contain the string "posix".

Body:
I have a java code deployed in windows as well as unix system.I have to add file permission for moving the file to a specific directory(in unix).I am using PosixFilePermission for this.

                file1 = new File( expFilePath+ "/" + creationDate);
                file1.mkdir();
                Set<PosixFilePermission> perms = new HashSet<>();
                perms.add(PosixFilePermission.OWNER_READ);
                perms.add(PosixFilePermission.OWNER_WRITE);
                perms.add(PosixFilePermission.OWNER_EXECUTE);
                perms.add(PosixFilePermission.OTHERS_READ);
                perms.add(PosixFilePermission.OTHERS_WRITE);
                perms.add(PosixFilePermission.OTHERS_EXECUTE);
                perms.add(PosixFilePermission.GROUP_READ);
                perms.add(PosixFilePermission.GROUP_WRITE);
                perms.add(PosixFilePermission.GROUP_EXECUTE);
                try {
                    Files.setPosixFilePermissions(file1.toPath(), perms);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

The above code is running correctly in unix but causing a UnsupportedOperationException in windows m/c.I have to manually comment this piece of code while running the code in windows m/c.

Is there any way by which I can detect the underlying os type in java and execute this block of code conditionally?


问:
Inconsistency while inserting documents in MongoDB, with MongoJS
I am building a site with ExpressJS and MongoDB. I am using MongoJS for establishing the connection with the DB.

Problem:
Inconsistencies while try to insert documents in to the MongoDB. Roughly 1/3rd of insert requests fail.

Code:

```<code>function insertWorkouts(callback,new_workout){
  var workout_date = new_workout['date'];
  db.latest_workout.insert(new_workout,{continueOnError: true, safe: true}, function(err, result) {
   console.log("DBconn insert!!");
   if(err) { console.log(err);
     throw(err);
   }
   else {
     console.log(" DBConn Inserted workout");
     // function invocation to insert workout dates
   }
  });
}
</code>```

Please suggest how I can ensure that all my inserts go through succesfully.

Edit:
MongoDb Connection:

```<code>var db = mongojs('mongodb://{username}:{password}@ds025xxx.mlab.com:25973/{DB name}', ['users','trainer','client','athlete','workout','client_feedback','IntermediateWorkout_Template','latest_workout','workout_dates','response_dates','sent_dates','diet','payment']);
</code>```

PS: This is my first question here. Please ignore my mistake(s).

答:
Try to use Mongoose, it's a great ODM(Object Document Mapping), it means Mongoose translate data in the database to JavaScript objects for use in your application.

```<code>var mongoose = require('mongoose');
// create connection.
mongoose.connect('mongodb://localhost/test');
</code>```

Declare its Schema :

```<code>var testSchema = mongoose.Schema({
 name: String
});
</code>```

We've got a schema with one property, name, which will be a String. The next step is compiling our schema into a Model.

```<code>var Test = mongoose.model('Test', testSchema);
</code>```

Each document can be saved to the database by calling its save method. The first argument to the callback will be an error if any occured.

```<code>var test = new Test({name:"Thor"});
test.save(function (err, doc) {
    if (err) return console.error(err);
    console.log(doc);
    // Doc will contain record saved in db.
});
</code>```

Body:
I am building a site with ExpressJS and MongoDB. I am using MongoJS for establishing the connection with the DB.

Problem:
Inconsistencies while try to insert documents in to the MongoDB. Roughly 1/3rd of insert requests fail.

Code:

function insertWorkouts(callback,new_workout){
  var workout_date = new_workout['date'];
  db.latest_workout.insert(new_workout,{continueOnError: true, safe: true}, function(err, result) {
   console.log("DBconn insert!!");
   if(err) { console.log(err);
     throw(err);
   }
   else {
     console.log(" DBConn Inserted workout");
     // function invocation to insert workout dates
   }
  });
}

Please suggest how I can ensure that all my inserts go through succesfully.

Edit:
MongoDb Connection:

var db = mongojs('mongodb://{username}:{password}@ds025xxx.mlab.com:25973/{DB name}', ['users','trainer','client','athlete','workout','client_feedback','IntermediateWorkout_Template','latest_workout','workout_dates','response_dates','sent_dates','diet','payment']);

PS: This is my first question here. Please ignore my mistake(s).

Body:
Try to use Mongoose, it's a great ODM(Object Document Mapping), it means Mongoose translate data in the database to JavaScript objects for use in your application.

var mongoose = require('mongoose');
// create connection.
mongoose.connect('mongodb://localhost/test');

Declare its Schema :

var testSchema = mongoose.Schema({
 name: String
});

We've got a schema with one property, name, which will be a String. The next step is compiling our schema into a Model.

var Test = mongoose.model('Test', testSchema);

Each document can be saved to the database by calling its save method. The first argument to the callback will be an error if any occured.

var test = new Test({name:"Thor"});
test.save(function (err, doc) {
    if (err) return console.error(err);
    console.log(doc);
    // Doc will contain record saved in db.
});


问:
Not able to add DATA-tire to my application AWS (Configuration error while adding with snapshot)
i am trying to add DATA-tire to my application in AWS using snapshot of my RDS instance
as follows shown in the below image

please check configuration

when it validates the following error is a rising

please check the error here

please help me with this i got stuck here since 3 days

答:
This may be a compatible issue between the DB Engine, Engine Version and Instance Class of your snapshot and the new instance you are trying to create from that snapshot.  Either you have to create new instance exactly same as your snapshot or make sure the the Instance Class supports DB Engine and Engine Version as mentioned in the below link  </p>

<p>http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html </p>

Body:
This may be a compatible issue between the DB Engine, Engine Version and Instance Class of your snapshot and the new instance you are trying to create from that snapshot.  Either you have to create new instance exactly same as your snapshot or make sure the the Instance Class supports DB Engine and Engine Version as mentioned in the below link

http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Oracle.html


问:
Stop Rabbit MQ consumer Event If the Queue is Empty
I have added a Received Event Handler of EventingBasicConsumer in RabbitMQ. I am trying to check if the Queue is consumed(processed and now empty), It should Close the consumer and connection. I am not able to find the condition which can tell if the Queue is processed.

Please help

```<code>    public void ProcessQueue(string queueName, Func<string, bool> ProcessMessage)
    {
        //lock (this.Model)
        {
            this.Model.BasicQos(0, 1, false);
            EventingBasicConsumer consumer = new EventingBasicConsumer(this.Model);

            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                bool processed = ProcessMessage.Invoke(message);
                if (processed)
                    this.SendAcknowledgement(ea.DeliveryTag);
                else
                    this.StopProcessingQueue(consumer.ConsumerTag);

                // Check if no message for next 2 minutes,
                //      Stop Consumer and close connection

            };

            this.Model.BasicConsume(queue: queueName,
                             autoAck: false,
                             consumer: consumer);
        }
    }
</code>```

答:
As I have not found any way to stop Rabbit MQ consumer Event if the queue is Empty, I have implemented below method to process messages by passing the message count from API

"localhost:/api/queues"

Below is the function to process messages till queue is empty

```<code>/// <summary>
/// (Recommanded) Processes the queue till the number of messages provided.
/// Added to manage the load (process batches by batches)
/// </summary>
/// <param name="queueName">Name of the queue.</param>
/// <param name="ProcessMessage">The process message.</param>
/// <param name="count">The count.</param>
public uint ProcessQueueByMessageCount(string queueName, Func<string, bool> HowToProcessMessage, uint messageCount)
{
    uint messagesToProcess = messageCount;
    using (var connect = this)
    {
        while (messageCount > 0)
        {
            BasicGetResult result = connect.Model.BasicGet(queueName, false);
            bool processed = HowToProcessMessage.Invoke(System.Text.Encoding.UTF8.GetString(result.Body));
            if (processed)
            {
                this.SendAcknowledgement(result.DeliveryTag);
                messageCount--;
            }
            else
            {
                connect.Model.BasicNack(result.DeliveryTag, false, true);
                break;
            }
        }
    }
    return messagesToProcess - messageCount;
}
</code>```

Body:
I have added a Received Event Handler of EventingBasicConsumer in RabbitMQ. I am trying to check if the Queue is consumed(processed and now empty), It should Close the consumer and connection. I am not able to find the condition which can tell if the Queue is processed.

Please help

    public void ProcessQueue(string queueName, Func<string, bool> ProcessMessage)
    {
        //lock (this.Model)
        {
            this.Model.BasicQos(0, 1, false);
            EventingBasicConsumer consumer = new EventingBasicConsumer(this.Model);

            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                bool processed = ProcessMessage.Invoke(message);
                if (processed)
                    this.SendAcknowledgement(ea.DeliveryTag);
                else
                    this.StopProcessingQueue(consumer.ConsumerTag);

                // Check if no message for next 2 minutes,
                //      Stop Consumer and close connection

            };

            this.Model.BasicConsume(queue: queueName,
                             autoAck: false,
                             consumer: consumer);
        }
    }

Body:
As I have not found any way to stop Rabbit MQ consumer Event if the queue is Empty, I have implemented below method to process messages by passing the message count from API

"localhost:/api/queues"

Below is the function to process messages till queue is empty

/// <summary>
/// (Recommanded) Processes the queue till the number of messages provided.
/// Added to manage the load (process batches by batches)
/// </summary>
/// <param name="queueName">Name of the queue.</param>
/// <param name="ProcessMessage">The process message.</param>
/// <param name="count">The count.</param>
public uint ProcessQueueByMessageCount(string queueName, Func<string, bool> HowToProcessMessage, uint messageCount)
{
    uint messagesToProcess = messageCount;
    using (var connect = this)
    {
        while (messageCount > 0)
        {
            BasicGetResult result = connect.Model.BasicGet(queueName, false);
            bool processed = HowToProcessMessage.Invoke(System.Text.Encoding.UTF8.GetString(result.Body));
            if (processed)
            {
                this.SendAcknowledgement(result.DeliveryTag);
                messageCount--;
            }
            else
            {
                connect.Model.BasicNack(result.DeliveryTag, false, true);
                break;
            }
        }
    }
    return messagesToProcess - messageCount;
}


问:
How to face with emojicons in strings?
How to count emojicons as a single character?

I have the below record containing two emojicons and link propertries made by Telegram messageing app:

```<code>{ "text":"abc \ud83d\ude00\ud83e\udd23 www.google.com def", "entities": [{"offset":9,"length":14,"type":"url"}] }
</code>```

I need to find the link in string, but using substr() and mb_substr() don't work properly on emojicons.

```<code>substr(9, 14)
</code>```

returns

"إ¸ثœâ‚¬ www.google"

which reads each emojicon as 4 characters

and

```<code>mb_substr(9, 14)
</code>```

returns

"w.google.com d"

which reads each emojicon as 1 character

I need a function to read each emojicon as 2 characters.

Edit: I need to clarify that there are other entities other than links. So finding just the links is not the true solution.

答:
for fetching URLs from an string you can do like this:</p>

```<code><?php
    $string = 'abc \ud83d\ude00\ud83e\udd23 www.google.com def';
    $sections = explode(' ', $string);
    $urls = array();
    foreach($sections as $section){
        preg_match('{\b(?:http://)?(www\.)?([^\s]+)(\.com|\.org|\.net)\b}mi', $section, $matches, PREG_OFFSET_CAPTURE);
        if(isset($matches[0][0]) and $matches[0][0]!='')
            $urls[] = $matches[0][0];
    }

    print_r($urls);
?>
</code>```

Title: How to face with emojicons in strings?

Body:
How to count emojicons as a single character?

I have the below record containing two emojicons and link propertries made by Telegram messageing app:

{ "text":"abc \ud83d\ude00\ud83e\udd23 www.google.com def", "entities": [{"offset":9,"length":14,"type":"url"}] }

I need to find the link in string, but using substr() and mb_substr() don't work properly on emojicons.

substr(9, 14)

returns

"إ¸ثœâ‚¬ www.google"

which reads each emojicon as 4 characters

and

mb_substr(9, 14)

returns

"w.google.com d"

which reads each emojicon as 1 character

I need a function to read each emojicon as 2 characters.

Edit: I need to clarify that there are other entities other than links. So finding just the links is not the true solution.

Body:
for fetching URLs from an string you can do like this:

<?php
    $string = 'abc \ud83d\ude00\ud83e\udd23 www.google.com def';
    $sections = explode(' ', $string);
    $urls = array();
    foreach($sections as $section){
        preg_match('{\b(?:http://)?(www\.)?([^\s]+)(\.com|\.org|\.net)\b}mi', $section, $matches, PREG_OFFSET_CAPTURE);
        if(isset($matches[0][0]) and $matches[0][0]!='')
            $urls[] = $matches[0][0];
    }

    print_r($urls);
?>


问:
How to implement login and logout with Facebook Login and ReactJS?
I'm trying to use Facebook Login for users to log in and out of my web app using React and React-Router. I made a component which redirects a user on successful login, but I am not able to render the log out button on the new view. I am also new to React-Router so I'm not entirely sure if the problem is with my routes.

Here's my code so far:

login.js

```<code>class Login extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            loggedStatus: false,
            id : ''
        }
    }

    componentDidMount() {
        window.fbAsyncInit = function() {
            window.FB.init({
                appId      : '',
                cookie     : true,
                xfbml      : true,
                version    : 'v2.11'
            });

            window.FB.getLoginStatus(function(response) {
                this.statusChangeCallback(response);
            }.bind(this));
        }.bind(this);

        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11&appId=''";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'))
    }

    loggedIn(response) {
        this.setState({
            loggedStatus : true,
            id: response.authResponse.userID
        });
    }

    loggedOut() {
        this.setState({
            loggedStatus: false,
        })
    }

    statusChangeCallback(response) {
      console.log('statusChangeCallback');
      console.log(response);
      if (response.status === 'connected') {
        this.loggedIn(response)
        console.log(this.state);
      } else if (response.status === 'not_authorized') {
        this.loggedOut()
        console.log(this.state.loggedStatus);
      } else {
        this.loggedOut()
         console.log(this.state.loggedStatus);
      }
    }

    checkLoginState() {
      window.FB.getLoginStatus(function(response) {
        this.statusChangeCallback(response);
      }.bind(this));
    }

    handleClick() {
      window.FB.login(this.checkLoginState());
    }

    render () {
        if (!this.state.loggedStatus) {
        return (
            <div className="fb-login-button"
                 data-max-rows="1"
                 data-size="large"
                 data-button-type="continue_with"
                 data-show-faces="false"
                 data-auto-logout-link="true"
                 data-use-continue-as="true">
            </div>   );
        } else {
            return (
                <Redirect to = {{
                    pathname : '/loggedin',
                    state : {
                        id: this.state.id
                    }
                }} />
            )
        }
    }

}

export default Login;
</code>```

loggedin.js

```<code>class UserLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state =  {
            id: this.props.location.state.id
        }
    }
   render(){
      return (
    <div>Hey {this.state.id}!</div>
    </div>)

    }
}

export default UserLogin
</code>```

And here is my main app, App.js

```<code>class App extends React.Component {
   render() {
      return (
        <Router>
            <Switch path = '/'>
                <Route path = '/login' component = {Login} />
                <Route path = '/loggedin' component = {UserLogin} />
            </Switch>
        </Router>
     );
   }
};

export default App;
</code>```

答:
Then I guess you have problem with router setup.

//Solution suppose you are using creat-react-app
//At index.js of you app put this.
//other import.

//install history package from npm

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

ReactDOM.render(
       <Router history ={history}>
            <App/>
        </Router>,
 document.getElementById('root'));
registerServiceWorker();```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//at app.js file
//other required import
import { BrowserRouter, Route } from "react-router-dom";

//import your two component here

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Route exact path="/login" component={Login} />
          <Route exact path="/loggedin" component={Loggedin} />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;</code>```

// Inside Login component
// Use componentDidMount life cycle hook to redirect.

componentDidMount(){
  //other logic and at last...
  if(this.state.id !== null){
  const {history} = this.props;
  history.push('/loggedin') //redirection link if user is already logged in.
  }

}  ```

Body:
I'm trying to use Facebook Login for users to log in and out of my web app using React and React-Router. I made a component which redirects a user on successful login, but I am not able to render the log out button on the new view. I am also new to React-Router so I'm not entirely sure if the problem is with my routes.

Here's my code so far:

login.js

class Login extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            loggedStatus: false,
            id : ''
        }
    }

    componentDidMount() {
        window.fbAsyncInit = function() {
            window.FB.init({
                appId      : '',
                cookie     : true,
                xfbml      : true,
                version    : 'v2.11'
            });

            window.FB.getLoginStatus(function(response) {
                this.statusChangeCallback(response);
            }.bind(this));
        }.bind(this);

        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11&appId=''";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'))
    }

    loggedIn(response) {
        this.setState({
            loggedStatus : true,
            id: response.authResponse.userID
        });
    }

    loggedOut() {
        this.setState({
            loggedStatus: false,
        })
    }

    statusChangeCallback(response) {
      console.log('statusChangeCallback');
      console.log(response);
      if (response.status === 'connected') {
        this.loggedIn(response)
        console.log(this.state);
      } else if (response.status === 'not_authorized') {
        this.loggedOut()
        console.log(this.state.loggedStatus);
      } else {
        this.loggedOut()
         console.log(this.state.loggedStatus);
      }
    }

    checkLoginState() {
      window.FB.getLoginStatus(function(response) {
        this.statusChangeCallback(response);
      }.bind(this));
    }

    handleClick() {
      window.FB.login(this.checkLoginState());
    }

    render () {
        if (!this.state.loggedStatus) {
        return (

   );
        } else {
            return (
                <Redirect to = {{
                    pathname : '/loggedin',
                    state : {
                        id: this.state.id
                    }
                }} />
            )
        }
    }

}

export default Login;

loggedin.js

class UserLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state =  {
            id: this.props.location.state.id
        }
    }
   render(){
      return (

Hey {this.state.id}!

)

    }
}

export default UserLogin

And here is my main app, App.js

class App extends React.Component {
   render() {
      return (
        <Router>
            <Switch path = '/'>
                <Route path = '/login' component = {Login} />
                <Route path = '/loggedin' component = {UserLogin} />
            </Switch>
        </Router>
     );
   }
};

export default App;

Body:
Then I guess you have problem with router setup.

//Solution suppose you are using creat-react-app
//At index.js of you app put this.
//other import.

//install history package from npm

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

ReactDOM.render(
       <Router history ={history}>
            <App/>
        </Router>,
 document.getElementById('root'));
registerServiceWorker();

//at app.js file
//other required import
import { BrowserRouter, Route } from "react-router-dom";

//import your two component here

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Route exact path="/login" component={Login} />
          <Route exact path="/loggedin" component={Loggedin} />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

// Inside Login component
// Use componentDidMount life cycle hook to redirect.

componentDidMount(){
  //other logic and at last...
  if(this.state.id !== null){
  const {history} = this.props;
  history.push('/loggedin') //redirection link if user is already logged in.
  }

}


答:
use target="_self" instead of target="_blank"

angular.module("test",[]).controller("testCont",function($scope)
{
$scope.data={};
$scope.data.links="http://www.google.com/";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="test" ng-controller="testCont">
  {{data.links}}

</div></code>```

Title: URL link not redirecting properly in Angularjs

Body:
I have a link in my announce.obj. But when I clicked it, it's giving me the wrong url (http://www./) in the browser.

html

  {{data.links}}

data.links value

www.google.com

Should I add an https when saving my links in the db or something ?

Body:
use target="_self" instead of target="_blank"

angular.module("test",[]).controller("testCont",function($scope)
{
$scope.data={};
$scope.data.links="http://www.google.com/";
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="test" ng-controller="testCont">
  <a ng-href="{{data.links}}" target="_self">{{data.links}}</a>

</div>


问:
By returning a pointer that points to a node, is the rest of the list returned as well? c++
I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.

```<code>Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }
</code>```

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

答:
While that technically does return a pointer to the rest of the list, or at least its nodes, the "rest" of a Lisp list is itself a Lisp list – not a different type (like node).

A "Lisp list" doesn't have a head as such; it looks pretty much like this:

```<code>struct List
{
    ElementType data;
    List* next;
};
</code>```

and has the operations

```<code>ElementType first(List* l) { return l->data; } /* or "car" */
List* rest(List* l) { return l->next; }        /* or "cdr" */
</code>```

or, as members:

```<code>ElementType List::first() { return data; }
List* List::rest() { return next; }
</code>```

Note that every node in a Lisp list is the "head" of a sublist of the entire list.

Body:
I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.

Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

Body:
While that technically does return a pointer to the rest of the list, or at least its nodes, the "rest" of a Lisp list is itself a Lisp list – not a different type (like node).

A "Lisp list" doesn't have a head as such; it looks pretty much like this:

struct List
{
    ElementType data;
    List* next;
};

and has the operations

ElementType first(List* l) { return l->data; } /* or "car" */
List* rest(List* l) { return l->next; }        /* or "cdr" */

or, as members:

ElementType List::first() { return data; }
List* List::rest() { return next; }

Note that every node in a Lisp list is the "head" of a sublist of the entire list.


答:
You have to merge the branch B to branch A. The commands are:

git checkout A
git merge B

You can also rebase if the branch A is not pushed to the server.

I suggest you to learn how to manage branches on git. Here are two great tutorials that may help you https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow
https://guides.github.com/introduction/flow/

Title: How to copy one branch to other in Git


问:
How to add a CASE column to SQLAlchemy output?
So far I've got basically the following:

```<code>MyTable.query
    .join(…)
    .filter(…)
</code>```

The filter has a complicated case insensitive prefix check:

```<code>or_(*[MyTable.name.ilike("{}%".format(prefix)) for prefix in prefixes])
</code>```

Now I have to retrieve the matching prefix in the result. In pseudo-SQL:

```<code>SELECT CASE
           WHEN strpos(lower(my_table.foo), 'prefix1') = 0 THEN 'prefix1'
           WHEN …
       END AS prefix
 WHERE prefix IS NOT NULL;
</code>```

The SQLAlchemy documentation demonstrates how to use CASE within WHERE, which seems like a strange edge case, and not how to use it to get a new column based on an existing one.

The goal is to avoid duplicating the logic and prefix names anywhere.

答:
You know that case is an expression. You can use it in any place where SQL allows it, and link to docs you have provided show how to construct the case expression.</p>

```<code>from sqlalchemy import case, literal
from sqlalchemy.orm import Query

q = Query(case([
    (literal(1) == literal(1), True),
], else_ = False))

print(q)

SELECT CASE WHEN (:param_1 = :param_2) THEN :param_3 ELSE :param_4 END AS anon_1
</code>```

Body:
So far I've got basically the following:

MyTable.query
    .join(…)
    .filter(…)

The filter has a complicated case insensitive prefix check:

or_(*[MyTable.name.ilike("{}%".format(prefix)) for prefix in prefixes])

Now I have to retrieve the matching prefix in the result. In pseudo-SQL:

SELECT CASE
           WHEN strpos(lower(my_table.foo), 'prefix1') = 0 THEN 'prefix1'
           WHEN …
       END AS prefix
 WHERE prefix IS NOT NULL;

The SQLAlchemy documentation demonstrates how to use CASE within WHERE, which seems like a strange edge case, and not how to use it to get a new column based on an existing one.

The goal is to avoid duplicating the logic and prefix names anywhere.

Body:
You know that case is an expression. You can use it in any place where SQL allows it, and link to docs you have provided show how to construct the case expression.

from sqlalchemy import case, literal
from sqlalchemy.orm import Query

q = Query(case([
    (literal(1) == literal(1), True),
], else_ = False))

print(q)

SELECT CASE WHEN (:param_1 = :param_2) THEN :param_3 ELSE :param_4 END AS anon_1


问:
advanced printf explanation in bash
I just found this programming segment in my son's Bash file. I am quite a newbie and unable to understand the printf syntax. Can someone explain me the COMMENTED printf in the segment below??

```<code>#printf "\033[1;34m"
while [ -d /proc/$PROC ]; do
    printf '\033[s\033[u[/] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[—] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[\] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[|] %s\033[u' "$str"; sleep "$delay"
done
#printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "  # return to normal(It disappears.)
</code>```

答:
It's is nothing but a busy/wait spinner and the lines commented do nothing but set a blue foreground color and the last erases the line the spinner and text. \033 is just character 27 which is part of the ANSI escape followed by [. See here Spinner Animation and echo command The 's' saves the cursor position and the 'u' restores the cursor position to where it was last saved -- your fine, nothing nefarious... (I'm fairly sure that is exactly where that code came from)

In more detail:

```<code>#printf "\033[1;34m"   /* simply sets a blue foreground color */
</code>```

Then the final:

```<code>#printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "
</code>```

\033[s save cursor position,

\033[u restore to last saved,

'%*s' normal printf format specifier for a string with the * to note the field width will be specified by the 1st argument,

\033[u restore to last saved position,

\033[0m return the color to default.

The first argument is $((${#str}+6)) the length of the string your printing plus 6-chars for the spinner, e.g. '[ \ ] ' and the the 2nd argument, a space (e.g. " ") for the actual string to overwrite the line with empty-spaces.

It simply erases the line used with the spinner in it.

By commenting the lines, the color is left at the default (the 1st comment) and the final line with the string and the last spinner position is left on screen (2nd commented printf)

Here is an ANSI Escape sequences reference that explains the escapes further...

Title: advanced printf explanation in bash

Body:
I just found this programming segment in my son's Bash file. I am quite a newbie and unable to understand the printf syntax. Can someone explain me the COMMENTED printf in the segment below??

#printf "\033[1;34m"
while [ -d /proc/$PROC ]; do
    printf '\033[s\033[u[/] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[—] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[\] %s\033[u' "$str"; sleep "$delay"
    printf '\033[s\033[u[|] %s\033[u' "$str"; sleep "$delay"
done
#printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "  # return to normal(It disappears.)

Body:
It's is nothing but a busy/wait spinner and the lines commented do nothing but set a blue foreground color and the last erases the line the spinner and text. \033 is just character 27 which is part of the ANSI escape followed by [. See here Spinner Animation and echo command The 's' saves the cursor position and the 'u' restores the cursor position to where it was last saved -- your fine, nothing nefarious... (I'm fairly sure that is exactly where that code came from)

In more detail:

#printf "\033[1;34m"   /* simply sets a blue foreground color */

Then the final:

#printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "

\033[s save cursor position,

\033[u restore to last saved,

'%*s' normal printf format specifier for a string with the * to note the field width will be specified by the 1st argument,

\033[u restore to last saved position,

\033[0m return the color to default.

The first argument is $((${#str}+6)) the length of the string your printing plus 6-chars for the spinner, e.g. '[ \ ] ' and the the 2nd argument, a space (e.g. " ") for the actual string to overwrite the line with empty-spaces.

It simply erases the line used with the spinner in it.

By commenting the lines, the color is left at the default (the 1st comment) and the final line with the string and the last spinner position is left on screen (2nd commented printf)

Here is an ANSI Escape sequences reference that explains the escapes further...


问:
When to choose Javascript injection from code-behind over external js file
I'm working on a C# web app and I've to handle some javascript code.

I can do it both using javascript injection from my .cs file, which I'm doing now or choose to include my code into an external js file.

I would like to know when you would prefer to choose one way over the other.

According to me, it can be more clear to put code in external .js file and it can ease debugging.
Code injection from code-behind would however keep together all the necessary code for my component.

Can I please have your ideas ?

Thanks.

Pat.

答:
You nailed it Pat, look at it the same way that you can choose to have a code behind file or not.  ASP.NET is flexible enough to allow you to choose where you want to write your code, but ultimately do whats best FOR YOU.

Generally speaking, best practice is to have separation of code from the UI, separating into more manageable components.  Isolating your JS into a separate file affords you other benefits as well.  For example, local js files can be pulled into your page load via CompositeScript references in a ClientScriptManager, or even file compression via third party projects found on CodePlex and other websites.

If you can, separate the files, you'll be happy you did in the future.


问:
Insert and select data in sql server
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

```<code>Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test
</code>```

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

答:
you can use this.</p>

```<code>INSERT INTO sp_emp( empid, amount )
SELECT EmpID, Amount
FROM sp_test
</code>```

Title: Insert and select data in sql server

Body:
I want to insert data from table sp_test with two columns; (empid and amount) into another table sp_emp (regisno,empid,itemid,year,month,week,amount,paymentdate).

This is the query I used

Insert into sp_emp(regisno,empid,itemid,year,month,week,amount,paymentdate)
Select * from sp_test

and it returned as select list for insert statement has fewer items. How should I put the values for another column?

Body:
you can use this.

INSERT INTO sp_emp( empid, amount )
SELECT EmpID, Amount
FROM sp_test


问:
Can't update ionic cordova / ionic 2
```<code>npm update -g ionic cordova
</code>```

As title says it won't let update it. I even ran cmd as admin in case I didn't have access to all the files for cordova/node/ionic.
I'm stressing over this because I need to use ionic 2 for college and my ionic is version 2.1.1.

答:
Use Nodejs command prompt

Then use

npm update -g cordova ionic

Title: Can't update ionic cordova / ionic 2

Body:
npm update -g ionic cordova

As title says it won't let update it. I even ran cmd as admin in case I didn't have access to all the files for cordova/node/ionic.
I'm stressing over this because I need to use ionic 2 for college and my ionic is version 2.1.1.


问:
Automatically scroll on the table using link_to rails
How can I automatically scroll or focus on the table upon redirect using the class name when the button is clicked I used a link_to enclosed inside is a div

```<code> <%= link_to employees_path do %>
   <div>......
   </div>
 <% end %>

<tbody>
 <% @request.each do |s| %>
 <tr data-expanded="true">
     <td><%= s.date.strftime('%B %Y') %></td>
     <td><%= s.name %></td>
     <td><%= s.created_at %></td>
     <td><%= s.updated_at %></td>
 </tr>
 <% end %>
 </tbody>
</table>
</code>```

I tried using but it doesnt work on the table

```<code> autofocus: true
</code>```

and I also tried to mimic it going to the bottom of the page

```<code><script>
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
</script>
</code>```

What I want is when the user clicks the button the user will be automatically scrolled to the table or focused on table, but only when the button is clicked will it be focused.

答:
```<code>  <div id="scroll-to-table">
    <%= link_to employees_path do %>
       <div>......
       </div>
     <% end %>
   </div>

<div id="scroll_to_table">
  <tbody>
   <% @request.each do |s| %>
   <tr data-expanded="true">
       <td><%= s.date.strftime('%B %Y') %></td>
       <td><%= s.name %></td>
       <td><%= s.created_at %></td>
       <td><%= s.updated_at %></td>
   </tr>
   <% end %>
   </tbody>
  </table>
</div>

<script type="text/javascript">

  $("#scroll-to-table").click(function() {
    $('html,body').animate({
        scrollTop: $("#scroll_to_table").offset().top},
        'slow');
  });

</script>
</code>```

Body:
How can I automatically scroll or focus on the table upon redirect using the class name when the button is clicked I used a link_to enclosed inside is a div

 <%= link_to employees_path do %>

......

 <% end %>

 <% @request.each do |s| %>

     <%= s.date.strftime('%B %Y') %>
     <%= s.name %>
     <%= s.created_at %>
     <%= s.updated_at %>

 <% end %>

I tried using but it doesnt work on the table

 autofocus: true

and I also tried to mimic it going to the bottom of the page

What I want is when the user clicks the button the user will be automatically scrolled to the table or focused on table, but only when the button is clicked will it be focused.