问:
array.pop() function weird behavior
Since documentation states that The pop method removes the last element from an array and returns that value to the caller. from here

But this statement below

```<code>arr=[1,2,3,4,5];
console.log(arr.pop());  //undefined
</code>```

prints undefined

Do i always need to store the popped values and use it?? or there is any workaround.

Update
I am just getting "undefined" even in chrome console and in code if i am comparing arr.pop()== its returning true, i have attached the image below.

答:
So, this is happening.

arr.pop() is popping 5 and 5 is getting printed. And then
undefined is returned by console.log().

Hope this answers your question.

UPDATE:

Make sure you check Info in the developers console

Title: array.pop() function weird behavior

Body:
Since documentation states that The pop method removes the last element from an array and returns that value to the caller. from here

But this statement below

arr=[1,2,3,4,5];
console.log(arr.pop());  //undefined

prints undefined

Do i always need to store the popped values and use it?? or there is any workaround.

Update
I am just getting "undefined" even in chrome console and in code if i am comparing arr.pop()== its returning true, i have attached the image below.


来源: stackexchange

问:
Latex .dtx file with a newcommand called \task
I have been trying to create a .dtx file for generating a .sty style file. Doing so I found something very strange I don't understand. In my .dtx file I want a macro called \task. If I create the macro with \newcommand{\task}[2]{Two arguments: #1 and #2}, then the documentation generation does not work, while if I use the TeX way of declaration ( \def\task#1#2{Two arguments: #1 and #2} ) then it works.
Below is the skeleton.dtx file.

```<code>% \iffalse
%<*driver>
\ProvidesFile{skeleton.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<package>\ProvidesPackage{skeleton}
%<*package>
    [2004/11/05 v1.0 .dtx skeleton file]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{skeleton}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{skeleton.dtx}
\end{document}
%</driver>
% \fi
% \CheckSum{0}
% \DescribeMacro{\task}
% \task{first}{second}
% \StopEventually{}
%    \begin{macrocode}
\newcommand{\task}[2]{Two arguments: #1 and #2}
%    \end{macrocode}
% \Finale
\endinput
</code>```

Here is the skeleton.ins file:

```<code>\input docstrip.tex
\keepsilent
\usedir{tex/latex/skeleton}
\generate{\file{skeleton.sty}{\from{skeleton.dtx}{package}}}
\endbatchfile
</code>```

To test, it simply run:

```<code>latex skeleton.ins
latex skeleton.dtx
</code>```

The first command creates the .sty file, and the second generates the documentation.

With the \newcommand version, the output is

```<code>! LaTeX Error: Command \task already defined.
               Or name \end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.26 ...ommand{\task}[2]{Two arguments: #1 and #2}
</code>```

When using the TeX version of the macro everything works fine. To make it work, just replace the \newcommand with \def\task#1#2{Two arguments: #1 and #2}

It is to be noted that using another name than "task" does not generate the issue, so it is related to the name of the macro. Dealing with the TeX works fine, but I would like to understand why this \task macro name is an issue.

Many thanks if can explain why.

Finally I found the issue. The class ltxdoc declares a macro \task which is empty. I found that this command is used in various base Latex packages (ltoutput, ltpage, ltfloat, ...), and serves as a todo command. In the official ltxdoc.cls package it simply removes what is inside, and I think the maintainers have another implementation to track some todo lists.

This answers my initial question.

答:
\newcommand{\foo} is a LaTeX command that conditions on whether or not the command to-be-defined - \foo - exists or not. If it already exists, an error is generated, otherwise it is created. \renewcommand{\foo} checks to see if \foo is already defined and subsequently redefines it, otherwise it generates an error.

The above-mentioned LaTeX macros have been made to perform some checks (about the existence of the macro/argument). However, if you revert back to the TeX definition of a macro, \def will always overwrite any definition, regardless of its existence. That's just the way this part of the LaTeX macro-layer was designed.

So, if you don't care about redefining any existing creations, you can use \def and they'll be overwritten. If you are concerned about overwriting existing things, you can either use \providecommand{\foo} (it only creates \foo if it doesn't exist) or use a "namespace" to separate your definitions from others (like \newcommand{\myPackagefoo} that would be specific to myPackage-type macros).

Reference:

What do \newcommand, \renewcommand, and \providecommand do, and how do they differ?

source2e.pdf (section 11.3 Command definitions)

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to create a .dtx file for generating a .sty style file. Doing so I found something very strange I don't understand. In my .dtx file I want a macro called \task. If I create the macro with \newcommand{\task}[2]{Two arguments: #1 and #2}, then the documentation generation does not work, while if I use the TeX way of declaration ( \def\task#1#2{Two arguments: #1 and #2} ) then it works.
Below is the skeleton.dtx file.

% \iffalse
%<*driver>
\ProvidesFile{skeleton.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<package>\ProvidesPackage{skeleton}
%<*package>
    [2004/11/05 v1.0 .dtx skeleton file]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{skeleton}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{skeleton.dtx}
\end{document}
%</driver>
% \fi
% \CheckSum{0}
% \DescribeMacro{\task}
% \task{first}{second}
% \StopEventually{}
%    \begin{macrocode}
\newcommand{\task}[2]{Two arguments: #1 and #2}
%    \end{macrocode}
% \Finale
\endinput

Here is the skeleton.ins file:

\input docstrip.tex
\keepsilent
\usedir{tex/latex/skeleton}
\generate{\file{skeleton.sty}{\from{skeleton.dtx}{package}}}
\endbatchfile

To test, it simply run:

latex skeleton.ins
latex skeleton.dtx

The first command creates the .sty file, and the second generates the documentation.

With the \newcommand version, the output is

! LaTeX Error: Command \task already defined.
               Or name \end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.26 ...ommand{\task}[2]{Two arguments: #1 and #2}

When using the TeX version of the macro everything works fine. To make it work, just replace the \newcommand with \def\task#1#2{Two arguments: #1 and #2}

It is to be noted that using another name than "task" does not generate the issue, so it is related to the name of the macro. Dealing with the TeX works fine, but I would like to understand why this \task macro name is an issue.

Many thanks if can explain why.

Finally I found the issue. The class ltxdoc declares a macro \task which is empty. I found that this command is used in various base Latex packages (ltoutput, ltpage, ltfloat, ...), and serves as a todo command. In the official ltxdoc.cls package it simply removes what is inside, and I think the maintainers have another implementation to track some todo lists.

This answers my initial question.


问:
How do you generate services etc. for a @nrwl/nx angular-cli app?
Normally when using @angular/cli to develop an application, you add a new service in the following manner:

ng generate service foo

This would generate "FooService".

My question is, when you have generated a library using @nrwl/nx, how do you add a service to it?

ng generate lib foo-lib

What I want to know, is the command to generate service "foo", so that it lives in the foo-lib library.

答:
It just works with the angular-cli command, but you have to add the --app flag

```<code>ng g service foo --app=foo-lib
</code>```

It is also mentioned in the docs of Nx under "Leverage the AngularCLI".

Body:
It just works with the angular-cli command, but you have to add the --app flag

ng g service foo --app=foo-lib

It is also mentioned in the docs of Nx under "Leverage the AngularCLI".


问:
warning in NSMutableArray
warning: (Messages without a matching method signature

warning: no '-eventListArray' method found

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [[[popularListArray objectAtIndex:section]eventListArray]count];

}
</code>```

@Thanks in advance

答: If you want to silence compiler you have to cast the object you retrieve by popularListArray because objectAtIndex return an (id) which is a (*void) equivalent.</p>

ContentLicense: CC BY-SA 2.5

Title: warning in NSMutableArray

Body:
warning: (Messages without a matching method signature

warning: no '-eventListArray' method found

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [[[popularListArray objectAtIndex:section]eventListArray]count];

}

@Thanks in advance


问:
Android Studio could not find method compile
When I try and build this happens can you please help?

答:
Please see the NOTE there:

```<code>//NOTE: Do not place your application dependencies here; they belong
//in the individual module build.gradle files
</code>```

Put it under the dependencies on the file build.gradle (Module: app).
You can see it on the left side panel.

ContentLicense: CC BY-SA 4.0

Body:
Please see the NOTE there:

//NOTE: Do not place your application dependencies here; they belong
//in the individual module build.gradle files

Put it under the dependencies on the file build.gradle (Module: app).
You can see it on the left side panel.


问:
How to perform case sensitive group by in MS Access
In MS Access database to find the mismatch (i.e. difference) records between two tables(Employee and Employee_PROD) I am using the UNION ALL. The query is as follows:

```<code>SELECT [COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY] FROM

(SELECT '[Employee]' AS TableName,[COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY] FROM [Employee]

UNION ALL

SELECT '[Employee_PROD]' AS TableName,[COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY] FROM [Employee_PROD] )

GROUP BY [COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY]
HAVING COUNT(*) = 1 AND MIN(TableName) = '[Employee]'
</code>```

The problem I am facing is that the GROUP BY is not considering the case sensitivity. For example "andrew" and "Andrew" is treated as same. I want to perform group by with case sensitive to find the difference records.

Is there any way to do the same in MS Access?

Is there any other approach to find the differences between two tables having same column names, data types and the number of records is 7,00, 000?

I have tried the following:

Load data to DataTable and then find the difference. Got out of memory exception due to huge amount of data.

Use NOT EXISTS to compare the rows. The query got hanged and the execution never completed.

The UNION ALL approach is working but the issue is that GROUP BY is not considering the case sensitivity.

答:
You could group by the byte value:

```<code>? StrToByte("Andrew")
416E64726577
? StrToByte("andrew")
616E64726577
</code>```

though it might be a bit slow with the large amount of data you have.

```<code>Public Function StrToByte(ByVal strChars As String) As String

  Dim abytChar()  As Byte
  Dim lngChar     As Long
  Dim strByte     As String

  abytChar() = StrConv(strChars, vbFromUnicode)

  strByte = Space(2 * (1 + UBound(abytChar) - LBound(abytChar)))
  For lngChar = LBound(abytChar) To UBound(abytChar)
    Mid(strByte, 1 + 2 * lngChar) = Hex(abytChar(lngChar))
  Next

  StrToByte = strByte

End Function
</code>```

For SQL only, and if you only about the first character, try:

```<code>GROUP BY [COMPANY],[DEPT],[DOJ],[EMP_ID],[Name], ASC([Name]),[SUB_COMPANY]
</code>```

Body:
In MS Access database to find the mismatch (i.e. difference) records between two tables(Employee and Employee_PROD) I am using the UNION ALL. The query is as follows:

SELECT [COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY] FROM

(SELECT '[Employee]' AS TableName,[COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY] FROM [Employee]

UNION ALL

SELECT '[Employee_PROD]' AS TableName,[COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY] FROM [Employee_PROD] )

GROUP BY [COMPANY],[DEPT],[DOJ],[EMP_ID],[Name],[SUB_COMPANY]
HAVING COUNT(*) = 1 AND MIN(TableName) = '[Employee]'

The problem I am facing is that the GROUP BY is not considering the case sensitivity. For example "andrew" and "Andrew" is treated as same. I want to perform group by with case sensitive to find the difference records.

Is there any way to do the same in MS Access?

Is there any other approach to find the differences between two tables having same column names, data types and the number of records is 7,00, 000?

I have tried the following:

Load data to DataTable and then find the difference. Got out of memory exception due to huge amount of data.

Use NOT EXISTS to compare the rows. The query got hanged and the execution never completed.

The UNION ALL approach is working but the issue is that GROUP BY is not considering the case sensitivity.

Body:
You could group by the byte value:

? StrToByte("Andrew")
416E64726577
? StrToByte("andrew")
616E64726577

though it might be a bit slow with the large amount of data you have.

Public Function StrToByte(ByVal strChars As String) As String

  Dim abytChar()  As Byte
  Dim lngChar     As Long
  Dim strByte     As String

  abytChar() = StrConv(strChars, vbFromUnicode)

  strByte = Space(2 * (1 + UBound(abytChar) - LBound(abytChar)))
  For lngChar = LBound(abytChar) To UBound(abytChar)
    Mid(strByte, 1 + 2 * lngChar) = Hex(abytChar(lngChar))
  Next

  StrToByte = strByte

End Function

For SQL only, and if you only about the first character, try:

GROUP BY [COMPANY],[DEPT],[DOJ],[EMP_ID],[Name], ASC([Name]),[SUB_COMPANY]


问:
Rails self and association
I have a car and user model.

```<code>User.rb
has_many :cars

Car.rb
belongs_to :user
</code>```

I would like to validate model field in the car model only if its user has mdk_id not nil.

This is how I create car model,

```<code>user = User.where(mdk_id: b["companyid"]).first

car = user.cars.build
</code>```

Then in Car.rb model, I would like to validate model field.

I tried;

```<code>  validates :model if self.user.mdk_id != nil
</code>```

But it gives error;

```<code>undefined method `user' for #<Class:0x007f973a321a58>
</code>```

How can I reference that ?

答:
Adding a validation like this:

```<code>validates :model if self.user.mdk_id != nil
</code>```

won't work as self here is the class Car but the validation would be on an instance of Car. Additionally, you need to specify what type of validation you want.

Say, you want the model field to have a value (mandatory) whenever a car has a user and user has mdk_id set, then you can do it as follows:

```<code># car.rb
validates :model, presence: true, if: -> { self.user && self.user.mdk_id.present? }
</code>```

Title: Rails self and association

Body:
I have a car and user model.

User.rb
has_many :cars

Car.rb
belongs_to :user

I would like to validate model field in the car model only if its user has mdk_id not nil.

This is how I create car model,

user = User.where(mdk_id: b["companyid"]).first

car = user.cars.build

Then in Car.rb model, I would like to validate model field.

I tried;

  validates :model if self.user.mdk_id != nil

But it gives error;

undefined method `user' for #<Class:0x007f973a321a58>

How can I reference that ?

Body:
Adding a validation like this:

validates :model if self.user.mdk_id != nil

won't work as self here is the class Car but the validation would be on an instance of Car. Additionally, you need to specify what type of validation you want.

Say, you want the model field to have a value (mandatory) whenever a car has a user and user has mdk_id set, then you can do it as follows:

# car.rb
validates :model, presence: true, if: -> { self.user && self.user.mdk_id.present? }


问:
how to place Interstitial Ad After If Statement?

I was Implemented interstitial Code to my App but I want interstitial Code in if-else statement ..so what to do ?
</p>

答:
Try this one. </p>

```<code>if (url.endsWith(".mp3")){
  // your ad view should be visible here. and load ad here.
}else{
 // your ad view should be gone here.
}
</code>```

Body:
Try this one.

if (url.endsWith(".mp3")){
  // your ad view should be visible here. and load ad here.
}else{
 // your ad view should be gone here.
}


问:
What is a spring service annotation?
I understand that @Service is used to mark a class as a business logic class. Why is it useful for spring? I can already use @Component to mark a class as a bean. I understand that @Service is more specific than @Component, but how?

答:
@Service, @Controller, @Repository = {@Component + some more special functionality}

Click the below link for more details

What's the difference between @Component, @Repository & @Service annotations in Spring?

The @Component annotation marks a java class as a bean so the
  component-scanning mechanism of spring can pick it up and pull it into
  the application context. The @Service annotation is also a
  specialization of the component annotation. It doesn’t currently
  provide any additional behavior over the @Component annotation, but
  it’s a good idea to use @Service over @Component in service-layer
  classes because it specifies intent better. Additionally, tool support
  and additional behavior might rely on it in the future.

Title: What is a spring service annotation?


问:
SQL Inner Join for calculated column
I would like to set sales year to date to automatically equal the sum of invoice headers where the account codes equal.

```<code>ALTER TABLE DEBTORS_MASTER
    ALTER COLUMN Sales_Year_To_Date AS
          (SELECT SUM (INVOICE_HEADER.Total_Sell_Amount_Excl_VAT)
           FROM DEBTORS_MASTER
           INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE);
</code>```

I get this error

Incorrect syntax near the keyword 'AS'

答:
You can use this code,</p>

```<code>UPDATE DM
SET Sales_Year_To_Date = IH.sumAmount
FROM DEBTORS_MASTER AS DM
INNER JOIN
    (
        SELECT Account_Code, SUM(Total_Sell_Amount_Excl_VAT) sumAmount
        FROM INVOICE_HEADER
        GROUP BY Account_Code
    ) IH
ON IH.Account_Code = DM.Account_Code
</code>```

Title: SQL Inner Join for calculated column

Body:
I would like to set sales year to date to automatically equal the sum of invoice headers where the account codes equal.

ALTER TABLE DEBTORS_MASTER
    ALTER COLUMN Sales_Year_To_Date AS
          (SELECT SUM (INVOICE_HEADER.Total_Sell_Amount_Excl_VAT)
           FROM DEBTORS_MASTER
           INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE);

I get this error

Incorrect syntax near the keyword 'AS'

Body:
You can use this code,

UPDATE DM
SET Sales_Year_To_Date = IH.sumAmount
FROM DEBTORS_MASTER AS DM
INNER JOIN
    (
        SELECT Account_Code, SUM(Total_Sell_Amount_Excl_VAT) sumAmount
        FROM INVOICE_HEADER
        GROUP BY Account_Code
    ) IH
ON IH.Account_Code = DM.Account_Code


问:
Select a row in elastic search
my mapping is as follows,

```<code>mapping = {
        "mappings":{
          "document": {
            "properties": {
               "title": {"type": "text"},
               "users": {
                "type": "nested",
                "properties": {
                    "user_id": {"type": "integer"},
                    "name": {"type": "text"},
                }
            }
        }
    }
}
</code>```

i can add data fine but when i search using

```<code>res = es.search(index="test", body={"query": {
    "nested": {
        "path": "users", "query": {
            "match": {'users.user_id': 1}
        }
    }
}
}
</code>```

it returns the whole document not the specific row.

More info:

i am feeding a table to elastic search:

user_id  |  name

1.............Joe

2 ............Mary

if i give 1 as user_id in search,  i need elastic search to return just {user_id:1, name:Joe}

答:
You should have a look at the Nested Query where they use bool > must when filtering by nested objects on the document.
Also, use term instead of match when you need to filter. Match is for full text search

Try it like this

```<code>res = es.search(index="test", body={"query": {
        "nested": {
            "path": "users",
            "query": {
                "bool": {
                    "must": [
                        {
                            term": {
                                'users.user_id': 1
                            }
                        }
                    ]
                }
            }
        }
    }
}
</code>```

Title: Select a row in elastic search

Body:
my mapping is as follows,

mapping = {
        "mappings":{
          "document": {
            "properties": {
               "title": {"type": "text"},
               "users": {
                "type": "nested",
                "properties": {
                    "user_id": {"type": "integer"},
                    "name": {"type": "text"},
                }
            }
        }
    }
}

i can add data fine but when i search using

res = es.search(index="test", body={"query": {
    "nested": {
        "path": "users", "query": {
            "match": {'users.user_id': 1}
        }
    }
}
}

it returns the whole document not the specific row.

More info:

i am feeding a table to elastic search:

user_id  |  name

1.............Joe

2 ............Mary

if i give 1 as user_id in search,  i need elastic search to return just {user_id:1, name:Joe}

Body:
You should have a look at the Nested Query where they use bool > must when filtering by nested objects on the document.
Also, use term instead of match when you need to filter. Match is for full text search

Try it like this

res = es.search(index="test", body={"query": {
        "nested": {
            "path": "users",
            "query": {
                "bool": {
                    "must": [
                        {
                            term": {
                                'users.user_id': 1
                            }
                        }
                    ]
                }
            }
        }
    }
}


问:
C# interface breakage, ABI
Suppose we have the class X in version 1 of the assembly A.dll:

```<code>class X {
    SomeType Property { set; get; }
}
</code>```

and then in version 2 of the assembly A.dll:

```<code>class X {
    SomeType Property { set; get; }
    SomeType OtherProperty { set; get; }
}
</code>```

Now suppose we have a second assembly B.dll that loads A.dll and uses X. Will the addition of the property OtherProperty break the ABI? Will B.dll fail to use A.dll/X? If not, would the order of the declarations make any difference? If the properties had been virtual, had it made any difference?

I guess I'm really asking: what are the general ABI rules? I know changing interfaces after they have been published is a bad thing, but I really would like to be able to add properties in some instances, without adding subclasses.

答:
Adding properties should be fine.

One case that will break is if you for example add something to the middle of an automatically numbered enum. For example if you have this code in your library:

```<code>enum Foo
{
   Bar,
   Qux
}
</code>```

and you change it to this:

```<code>enum Foo
{
   Bar,
   Baz,
   Qux
}
</code>```

Then you will also need to recompile any code like this:

```<code>if (foo == Foo.Qux)
{
    //  ...
}
</code>```

Title: C# interface breakage, ABI

Body:
Suppose we have the class X in version 1 of the assembly A.dll:

class X {
    SomeType Property { set; get; }
}

and then in version 2 of the assembly A.dll:

class X {
    SomeType Property { set; get; }
    SomeType OtherProperty { set; get; }
}

Now suppose we have a second assembly B.dll that loads A.dll and uses X. Will the addition of the property OtherProperty break the ABI? Will B.dll fail to use A.dll/X? If not, would the order of the declarations make any difference? If the properties had been virtual, had it made any difference?

I guess I'm really asking: what are the general ABI rules? I know changing interfaces after they have been published is a bad thing, but I really would like to be able to add properties in some instances, without adding subclasses.

Body:
Adding properties should be fine.

One case that will break is if you for example add something to the middle of an automatically numbered enum. For example if you have this code in your library:

enum Foo
{
   Bar,
   Qux
}

and you change it to this:

enum Foo
{
   Bar,
   Baz,
   Qux
}

Then you will also need to recompile any code like this:

if (foo == Foo.Qux)
{
    //  ...
}


问:
Accessing Wamp 2.5 phpmyadmin from another PC in a LAN Network
I have access wamp localhost from another pc but

when accessing phpmyadmin from this pc

i can't access like following figure

答:
```<code>Alias /phpmyadmin "D:/wamp/apps/phpmyadmin4.6.4/"

<Directory "D:/wamp/apps/phpmyadmin4.6.4/">
    Options Indexes FollowSymLinks MultiViews
  AllowOverride all
  <ifDefine APACHE24>
#       Require local
    Require all granted (changes)
    </ifDefine>
    <ifDefine !APACHE24>
        Order Deny,Allow
#Deny from all
    Allow from all
#    Allow from localhost ::1 127.0.0.1
    **Allow from localhost ::0 0.0.0.0** (changes)

    </ifDefine>

# To import big file you can increase values
  php_admin_value upload_max_filesize 128M
  php_admin_value post_max_size 128M
  php_admin_value max_execution_time 360
  php_admin_value max_input_time 360
</Directory>
</code>```


问:
Why arrow functions don't work when using import/export
This code shows "show not defined."

```<code>import {a} from './dis.js';
show = () =>{
  console.log(a);
}
show();
</code>```

But this works

```<code>import {a} from './dis.js';
const show = () =>{
    console.log(a);
}
show();
</code>```

why is that ?

答:
This is not related to the arrow functions. It's the nature of strict code. You can see an example when I work in the strict mode. What about ES6 modules, they are automatically in strict mode.

'use strict';

show = 4;```

You are trying to assign a reference of an arrow function to a variable show which is not defined. Defined means that you have defined it with keyword var, let or const for variables.

In the first code part you haven't declare it with these keywords, it tries to find the variable and doesn't find anything defined with that name. So it throws error.

In the second code part you have defined a variable with name show and then assign to it a reference to an arrow function. So everything is OK.

Body:
This code shows "show not defined."

import {a} from './dis.js';
show = () =>{
  console.log(a);
}
show();

But this works

import {a} from './dis.js';
const show = () =>{
    console.log(a);
}
show();

why is that ?

Body:
This is not related to the arrow functions. It's the nature of strict code. You can see an example when I work in the strict mode. What about ES6 modules, they are automatically in strict mode.

'use strict';

show = 4;

You are trying to assign a reference of an arrow function to a variable show which is not defined. Defined means that you have defined it with keyword var, let or const for variables.

In the first code part you haven't declare it with these keywords, it tries to find the variable and doesn't find anything defined with that name. So it throws error.

In the second code part you have defined a variable with name show and then assign to it a reference to an arrow function. So everything is OK.


问:
Get the indexpath from custom button in accessoryView of a UITableViewCell
I have a UISearchController with a separate UITableViewController as its searchResultsController.

```<code>class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}
</code>```

I need to show a custom button in cells that search results are shown. So I added a UIButton as the cells' accessoryView. And it looks and works fine.

Now I need to get the cell's indexPath when the user taps on this button.

I'm trying to get it like shown below.

```<code>@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}
</code>```

But it keeps returning nil for every cell.

Is there any other way to get the indexPath from a custom button tap? I added a demo project here as well.

答:
Create a custom class named SOButton and add variable of type IndexPath to it. Use this class for your add button initialisation.

```<code>//Your class will look like -

class SOButton: UIButton {
   var indexPath: IndexPath?
}

//Your action will look like -

@objc func addFruit(_ sender: SOButton) {
     print(sender?.indexPath.row)
}

//And in your cellForRow add

let addButton = SOButton(type: .custom)
addButton.indexPath = indexPath
</code>```

Hope this helps you :)

Body:
I have a UISearchController with a separate UITableViewController as its searchResultsController.

class SearchResultsViewController: UITableViewController {

    var fruits: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }

    @objc func addFruit(_ sender: UIButton) {
        let point = tableView.convert(sender.bounds.origin, to: sender)
        let indexPath = tableView.indexPathForRow(at: point)
        print(indexPath?.row)
    }

    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fruits.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = fruits[indexPath.row]
        cell.selectionStyle = .none

        let addButton = UIButton(type: .custom)
        addButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        addButton.setImage(UIImage(named: "add"), for: .normal)
        addButton.contentMode = .scaleAspectFit
        addButton.addTarget(self, action: #selector(addFruit(_:)), for: .touchUpInside)
        addButton.sizeToFit()
        cell.accessoryView =  addButton

        return cell
    }

}

I need to show a custom button in cells that search results are shown. So I added a UIButton as the cells' accessoryView. And it looks and works fine.

Now I need to get the cell's indexPath when the user taps on this button.

I'm trying to get it like shown below.

@objc func addFruit(_ sender: UIButton) {
    let point = tableView.convert(sender.bounds.origin, to: sender)
    let indexPath = tableView.indexPathForRow(at: point)
}

But it keeps returning nil for every cell.

Is there any other way to get the indexPath from a custom button tap? I added a demo project here as well.

Body:
Create a custom class named SOButton and add variable of type IndexPath to it. Use this class for your add button initialisation.

//Your class will look like -

class SOButton: UIButton {
   var indexPath: IndexPath?
}

//Your action will look like -

@objc func addFruit(_ sender: SOButton) {
     print(sender?.indexPath.row)
}

//And in your cellForRow add

let addButton = SOButton(type: .custom)
addButton.indexPath = indexPath

Hope this helps you :)


问:
how to stay in current page after Updating datatable DOM
I am working with data table , every thing is fine but now i need to stay on current page after updating and refresh page. Currently it comes in  first page after update. I am using Data-table DOM. </p>

```<code>      $("#dataTable").dataTable({
            "order": [],
            "columnDefs": [{
                "targets"  : 4,
                "orderable": false,

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

答:
Happy Coding :)

```<code>$(document).ready(function() {
    $('#example').DataTable( {
        stateSave: true
    } );
});
</code>```

Body:
I am working with data table , every thing is fine but now i need to stay on current page after updating and refresh page. Currently it comes in  first page after update. I am using Data-table DOM.

      $("#dataTable").dataTable({
            "order": [],
            "columnDefs": [{
                "targets"  : 4,
                "orderable": false,

            }]
        });

Body:
Happy Coding :)

$(document).ready(function() {
    $('#example').DataTable( {
        stateSave: true
    } );
});


问:
Adding Vnet to Azure SQLDB
I heard about the new update on Azure SQLDB that it can be connected to vnet but can't find any blogs on this new information.

Can someone throw some light on this information?

答:
Now, it is supported. Please refer to this blog.

Azure SQL Database will allow you to set firewall rules for specific
  public IPs, and will give you the option of allowing all Azure
  Services’ IPs to connect to your Servers. If you're looking for finer
  grained connectivity limitations, you would have to provision a Static
  Public IP, which can be hard to manage and costly when done at scale.
  Virtual Network service endpoints will allow you to limit connectivity
  to your Azure SQL Database Servers from given subnets within a Virtual
  Network.

You could do it on Azure Portal. Please refer to this link.

Title: Adding Vnet to Azure SQLDB


问:
how to use ref in multi-step registration in react es6?
I'm trying to develop multistep registration, referring this link : https://www.viget.com/articles/building-a-multi-step-registration-form-with-react

But I could not use refs and don't know how to fix this.

This is the error msg I get everytime I click on 'next' button
error msg

and this is my code

```<code>              <input type="text"
                     className='singleComponent'
                     name='AppName'
                     ref='AppName'
                     defaultValue={ this.props.fieldValues.AppName }
                     />

            <button>Cancel</button>
            <button onClick={this.SaveAndContinue}>Next</button>

  SaveAndContinue(e){
      e.preventDefault();

    var data={
        AppName : this.refs.AppName,
  }

    this.props.saveValues(data)
    this.props.nextStep()
  }

  }
</code>```

Dependencies :

```<code>"react": "^16.1.0",
"react-dev-utils": "^4.2.1",
"react-dom": "^16.1.0",
</code>```

can someone help?

Thanks,

答:
Problem solved by modifying button to :</p>

```<code>    <button onClick={this.SaveAndContinue.bind(this)}>Next</button>
</code>```

Body:
I'm trying to develop multistep registration, referring this link : https://www.viget.com/articles/building-a-multi-step-registration-form-with-react

But I could not use refs and don't know how to fix this.

This is the error msg I get everytime I click on 'next' button
error msg

and this is my code

              <input type="text"
                     className='singleComponent'
                     name='AppName'
                     ref='AppName'
                     defaultValue={ this.props.fieldValues.AppName }
                     />

            <button>Cancel</button>
            <button onClick={this.SaveAndContinue}>Next</button>

  SaveAndContinue(e){
      e.preventDefault();

    var data={
        AppName : this.refs.AppName,
  }

    this.props.saveValues(data)
    this.props.nextStep()
  }

  }

Dependencies :

"react": "^16.1.0",
"react-dev-utils": "^4.2.1",
"react-dom": "^16.1.0",

can someone help?

Thanks,

Body:
Problem solved by modifying button to :

    <button onClick={this.SaveAndContinue.bind(this)}>Next</button>


问:
array.pop() function weird behavior
Since documentation states that The pop method removes the last element from an array and returns that value to the caller. from here

But this statement below

```<code>arr=[1,2,3,4,5];
console.log(arr.pop());  //undefined
</code>```

prints undefined

Do i always need to store the popped values and use it?? or there is any workaround.

Update
I am just getting "undefined" even in chrome console and in code if i am comparing arr.pop()== its returning true, i have attached the image below.

答:
working fine.

arr = [1,2,3,4,5];

console.log(arr.pop());```

Title: array.pop() function weird behavior

Body:
Since documentation states that The pop method removes the last element from an array and returns that value to the caller. from here

But this statement below

arr=[1,2,3,4,5];
console.log(arr.pop());  //undefined

prints undefined

Do i always need to store the popped values and use it?? or there is any workaround.

Update
I am just getting "undefined" even in chrome console and in code if i am comparing arr.pop()== its returning true, i have attached the image below.


问:
How to Filter table by column in django
I was trying to filter my columns in my django project template
Currently I am able to search in the table and display the rows that have that that value
But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

```<code>def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q:
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 |
                 custom7 | custom8
</code>```

here name product l3 are my fields from my model that I would like to filter from

in my home.html

```<code> <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">
</code>```

my js.js

```<code>function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}
</code>```

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

答:
Add a dropdown with id as the column name and filter the objects by using that column value.</p>

```<code>Customer.objects.filter(**{columnName:columnValue})
</code>```

Title: How to Filter table by column in django

Body:
I was trying to filter my columns in my django project template
Currently I am able to search in the table and display the rows that have that that value
But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q:
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 |
                 custom7 | custom8

here name product l3 are my fields from my model that I would like to filter from

in my home.html

 <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">

my js.js

function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

Body:
Add a dropdown with id as the column name and filter the objects by using that column value.

Customer.objects.filter(**{columnName:columnValue})


问:
Does GWT have a widget which represent  HTML tag
I know that Flowpanel in GWT will be compiled into div and Horizontal/Vertical Panel will be compiled to table. Is there any widget available to represent span in GWT ?

Or

Is there a way to achieve it apart from GWT - HTML widget ?

答: InlineLabel or InlineHTML would be what you're looking for; or use HTML markup in UiBinder within a HTMLPanel.

Title: Does GWT have a widget which represent <span> HTML tag


问:
How to use a SplayTreeMap on Firebase snapshot dictionary in dart/Flutter?
I'm successfully getting data back through StreamBuilder and need to sort it.  How can I sort a Map of my snapshot data by keys?  Also, If you give an example of doing this my value that would help also.  I think I want to do a SplayTreeMap, but if there is a better way please provide.  Here is my dictionary...

```<code>{Vid2: {imageString: https://i.ytimg.com/vi/Amq-qlqbjYA/mqdefault.jpg, title: BLACKPINK - '마지막처럼 (AS IF IT'S YOUR LAST)' M/V, rank: 2, videoID: Amq-qlqbjYA}, Vid10: {imageString: https://i.ytimg.com/vi/KSH-FVVtTf0/mqdefault.jpg, title: EXO 엑소 'Monster' MV, rank: 10, videoID: KSH-FVVtTf0}, Vid6: {imageString: https://i.ytimg.com/vi/BVwAVbKYYeM/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ DOPE(쩔어), rank: 6, videoID: BVwAVbKYYeM}, Vid3: {imageString: https://i.ytimg.com/vi/m8MfJg68oCs/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ Boy In Luv(상남자), rank: 3, videoID: m8MfJg68oCs}, Vid4: {imageString: https://i.ytimg.com/vi/9pdj4iJD08s/mqdefault.jpg, title: BLACKPINK - '불장난 (PLAYING WITH FIRE)' M/V, rank: 4, videoID: 9pdj4iJD08s}, Vid1: {imageString: https://i.ytimg.com/vi/3s1jaFDrp5M/mqdefault.jpg, title: EPIK HIGH - 'BORN HATER' M/V, rank: 1, videoID: 3s1jaFDrp5M}, Vid8: {imageString: https://i.ytimg.com/vi/3QAcvc4Ysl0/mqdefault.jpg, title: LONNI - LA KPOP 2, rank: 8, videoID: 3QAcvc4Ysl0}, Vid5: {imageString: https://i.ytimg.com/vi/2ips2mM7Zqw/default.jpg, title: BIGBANG - 뱅뱅뱅 (BANG BANG BANG) M/V, rank: 5, videoID: 2ips2mM7Zqw}}
</code>```

I would like to display it either by keys...
Vid1, Vid2, Vid3...

or by values like rank ie...
Vid1:rank "1", Vid2: rank "2", Vid3: rank "3"...

答:
If the source is a map, this should do what you want:

```<code>final sorted = new SplayTreeMap<String,dynamic>.from(map, (a, b) => a.compareTo(b));
</code>```

DartPad example

Body:
I'm successfully getting data back through StreamBuilder and need to sort it.  How can I sort a Map of my snapshot data by keys?  Also, If you give an example of doing this my value that would help also.  I think I want to do a SplayTreeMap, but if there is a better way please provide.  Here is my dictionary...

{Vid2: {imageString: https://i.ytimg.com/vi/Amq-qlqbjYA/mqdefault.jpg, title: BLACKPINK - '마지막처럼 (AS IF IT'S YOUR LAST)' M/V, rank: 2, videoID: Amq-qlqbjYA}, Vid10: {imageString: https://i.ytimg.com/vi/KSH-FVVtTf0/mqdefault.jpg, title: EXO 엑소 'Monster' MV, rank: 10, videoID: KSH-FVVtTf0}, Vid6: {imageString: https://i.ytimg.com/vi/BVwAVbKYYeM/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ DOPE(쩔어), rank: 6, videoID: BVwAVbKYYeM}, Vid3: {imageString: https://i.ytimg.com/vi/m8MfJg68oCs/mqdefault.jpg, title: [MV] BTS(방탄소년단) _ Boy In Luv(상남자), rank: 3, videoID: m8MfJg68oCs}, Vid4: {imageString: https://i.ytimg.com/vi/9pdj4iJD08s/mqdefault.jpg, title: BLACKPINK - '불장난 (PLAYING WITH FIRE)' M/V, rank: 4, videoID: 9pdj4iJD08s}, Vid1: {imageString: https://i.ytimg.com/vi/3s1jaFDrp5M/mqdefault.jpg, title: EPIK HIGH - 'BORN HATER' M/V, rank: 1, videoID: 3s1jaFDrp5M}, Vid8: {imageString: https://i.ytimg.com/vi/3QAcvc4Ysl0/mqdefault.jpg, title: LONNI - LA KPOP 2, rank: 8, videoID: 3QAcvc4Ysl0}, Vid5: {imageString: https://i.ytimg.com/vi/2ips2mM7Zqw/default.jpg, title: BIGBANG - 뱅뱅뱅 (BANG BANG BANG) M/V, rank: 5, videoID: 2ips2mM7Zqw}}

I would like to display it either by keys...
Vid1, Vid2, Vid3...

or by values like rank ie...
Vid1:rank "1", Vid2: rank "2", Vid3: rank "3"...

Body:
If the source is a map, this should do what you want:

final sorted = new SplayTreeMap<String,dynamic>.from(map, (a, b) => a.compareTo(b));

DartPad example


问:
still getting angular not defined
this is html file

```<code><!DOCTYPE html>

<html ng-app="myApp">

    <head>

        <title>BlogIt!</title>
        <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>

    <body ng-controller="myCtrl">

        {{message}}

    </body>

</html>
</code>```

this is js file

```<code>var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope){

    $scope.message = "Welcome to BlogIt!";

})
</code>```

答:
Edit with this :</p>

```<code><head>
    <title>BlogIt!</title>
    <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
    {{message}}
</body>
</code>```

Title: still getting angular not defined

Body:
this is html file

<!DOCTYPE html>

        <title>BlogIt!</title>

        {{message}}

this is js file

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

app.controller('myCtrl', function($scope){

    $scope.message = "Welcome to BlogIt!";

})

Body:
Edit with this :

<head>
    <title>BlogIt!</title>
    <script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
    {{message}}
</body>


问:
I'm not typing something right
```<code>return Convert.ToInt32(myClass2.Digit(bmp, nX1, nY1)
                                 + myClass2.Digit(bmp, nX2, nY2)
                                 + myClass2.Digit(bmp, nX3, nY3)
                                 + myClass2.Digit(bmp, nX4, nY4)
                                 + myClass2.Digit(bmp, nX5, nY5));
</code>```

...finds this test method:

```<code>class Class2 {
    public string Digit(Bitmap bmp, int x, int y) {
//Please drop any logic using bmp, x, and y for the sake of this post.  Let's just...
        return "3";
    }
}
</code>```

and returns 33333 as an int.  As a preliminary to get something going so far, so good.

The problem comes when I want to return "0"; there's literally no output, not even an 0 much less an 00000.  Instead, a line isn't even written to the console.

Thanks for any help.

答:
If you want leading zeros use this:</p>

```<code>Console.WriteLine(String.Format("00000", someInteger));
</code>```

Title: I'm not typing something right

Body:
return Convert.ToInt32(myClass2.Digit(bmp, nX1, nY1)
                                 + myClass2.Digit(bmp, nX2, nY2)
                                 + myClass2.Digit(bmp, nX3, nY3)
                                 + myClass2.Digit(bmp, nX4, nY4)
                                 + myClass2.Digit(bmp, nX5, nY5));

...finds this test method:

class Class2 {
    public string Digit(Bitmap bmp, int x, int y) {
//Please drop any logic using bmp, x, and y for the sake of this post.  Let's just...
        return "3";
    }
}

and returns 33333 as an int.  As a preliminary to get something going so far, so good.

The problem comes when I want to return "0"; there's literally no output, not even an 0 much less an 00000.  Instead, a line isn't even written to the console.

Thanks for any help.

Body:
If you want leading zeros use this:

Console.WriteLine(String.Format("00000", someInteger));


问:
Access SPI by PeripheralManagerService on Hikey
I am trying to send data to a device which is connected to SPI of hikey960 platform. Hikey is running on normal mobile Android. Is it possible to run androidthings api on development platform like Hikey ?

```<code>PeripheralManagerService manager = new PeripheralManagerService();
List<String> deviceList = manager.getSpiBusList();
if (deviceList.isEmpty()) {
    Log.i(TAG, "No SPI bus available on this device.");
} else {
    Log.i(TAG, "List of available devices: " + deviceList);
}
</code>```

I build an apk with above code. and while installing missing library error is coming. obviously it is due missing android library in normal android sdk. Is ther any workaround or way to write data to spi devices on android platform.

Error-

Installation failed with message INSTALL_FAILED_MISSING_SHARED_LIBRARY: Package couldn't be installed in /data/app/com.example.androidthings.myproject-1: Package com.example.androidthings.myproject requires unavailable shared library com.google.android.things; failing!.

答: For now Android things only runs on the selected dev kits (nxp and raspberry pi) maybe once it's released -it's still on developer preview- they'll open it to more devices.</p>

Body:
I am trying to send data to a device which is connected to SPI of hikey960 platform. Hikey is running on normal mobile Android. Is it possible to run androidthings api on development platform like Hikey ?

PeripheralManagerService manager = new PeripheralManagerService();
List<String> deviceList = manager.getSpiBusList();
if (deviceList.isEmpty()) {
    Log.i(TAG, "No SPI bus available on this device.");
} else {
    Log.i(TAG, "List of available devices: " + deviceList);
}

I build an apk with above code. and while installing missing library error is coming. obviously it is due missing android library in normal android sdk. Is ther any workaround or way to write data to spi devices on android platform.

Error-

Installation failed with message INSTALL_FAILED_MISSING_SHARED_LIBRARY: Package couldn't be installed in /data/app/com.example.androidthings.myproject-1: Package com.example.androidthings.myproject requires unavailable shared library com.google.android.things; failing!.


问:
ActivityEventListener is not abstract and does not override abstract method onNewIntent(Intent)
i am getting this error when build this is the full source of the file........................ below
this is a plug in for react native

full error as below
local/Android/src/main/java/com/kmlidc/RNShareLocal/RNShareLocalManager.java:51: error: RNShareLocalManager.RNShareLocalActivityEventListener is not abstract and does not override abstract method onNewIntent(Intent) in ActivityEventListener
    private class RNShareLocalActivityEventListener implements ActivityEventListener {

            ^

its a simple social sharing plugin

```<code>public class RNShareLocalManager extends ReactContextBaseJavaModule implements ActivityEventListener{
private ReactApplicationContext reactContext;
private Callback callback;

final int SHARE_REQUEST = 500;

public RNShareLocalManager(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    this.reactContext.addActivityEventListener(new RNShareLocalActivityEventListener());
}

@Override
public String getName() {
    return "RNShareLocal";
}

private class RNShareLocalActivityEventListener implements ActivityEventListener {
    public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent intent) {
        if (requestCode == SHARE_REQUEST) {
            callback.invoke("success");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
}

public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

}

public void onNewIntent(Intent intent) {

}

@ReactMethod
public void message(String winTitle,String subject,String message,ReadableArray component, Callback callback) {
    this.callback = callback;

    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT,message);
    intent.setType("text/plain");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void link(String winTitle,String subject,String url,ReadableArray component, Callback callback) {
    this.callback = callback;
    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, url);
    intent.setType("text/html");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void pictures(String winTitle,String subject,String message,ReadableArray imagesFile,ReadableArray component, Callback callback) {
    this.callback = callback;
    ArrayList<Uri> uris = new ArrayList<Uri>();
    for(int i=0; i<imagesFile.size();i++){
        uris.add(Uri.parse(imagesFile.getString(i)));
    }
    Intent intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);
    intent.putExtra(Intent.EXTRA_STREAM, uris);
    intent.putExtra ("Kdescription", message);
    intent.setType("image/*");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void downloadImage(ReadableArray imagesUrl, Promise promise){
    List<String> paths = new ArrayList<String>();
    for(int i=0; i<imagesUrl.size();i++){
        String imageUrl = imagesUrl.getString(i);
        String fileName = i + ".jpg";
        String path = this.download(imageUrl,fileName);
        paths.add(path);
    }

    JSONArray array = new JSONArray(paths);
    promise.resolve(array.toString());
}

//下载图片并保存
public String download( String imageUrl, String fileName) {
    final String savePath = getReactApplicationContext().getExternalCacheDir() + "/" + fileName;
    try {
        File f = new File(savePath);
        File dir = f.getParentFile();
        if(!dir.exists())
            dir.mkdirs();
        FileOutputStream os = new FileOutputStream(f);
        byte[] data = getImage(imageUrl);
        os.write(data);
        os.close();
    } catch (Exception e) {
        e.getLocalizedMessage();
    }

    return "file://" + savePath;
}

/*
* 获取网络图片
*/
public byte[] getImage(String imageUrl) throws Exception{
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
        return readStream(inStream);
    }
    return null;
}

/*
获取图片流数据
 */
public static byte[] readStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=inStream.read(buffer)) != -1){
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inStream.close();
    return outStream.toByteArray();
}
</code>```

}

it will be great if some can help,

thanks advance

答:
You need to overrride the methods that are essential i.e onNewIntent i.e they are overriden methods of that class

Point on error that a small bulb will appear after clicking that you can implement methods needed.

Body:
i am getting this error when build this is the full source of the file........................ below
this is a plug in for react native

full error as below
local/Android/src/main/java/com/kmlidc/RNShareLocal/RNShareLocalManager.java:51: error: RNShareLocalManager.RNShareLocalActivityEventListener is not abstract and does not override abstract method onNewIntent(Intent) in ActivityEventListener
    private class RNShareLocalActivityEventListener implements ActivityEventListener {

            ^

its a simple social sharing plugin

public class RNShareLocalManager extends ReactContextBaseJavaModule implements ActivityEventListener{
private ReactApplicationContext reactContext;
private Callback callback;

final int SHARE_REQUEST = 500;

public RNShareLocalManager(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
    this.reactContext.addActivityEventListener(new RNShareLocalActivityEventListener());
}

@Override
public String getName() {
    return "RNShareLocal";
}

private class RNShareLocalActivityEventListener implements ActivityEventListener {
    public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent intent) {
        if (requestCode == SHARE_REQUEST) {
            callback.invoke("success");
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
}

public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {

}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

}

public void onNewIntent(Intent intent) {

}

@ReactMethod
public void message(String winTitle,String subject,String message,ReadableArray component, Callback callback) {
    this.callback = callback;

    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT,message);
    intent.setType("text/plain");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void link(String winTitle,String subject,String url,ReadableArray component, Callback callback) {
    this.callback = callback;
    Intent intent=new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, url);
    intent.setType("text/html");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void pictures(String winTitle,String subject,String message,ReadableArray imagesFile,ReadableArray component, Callback callback) {
    this.callback = callback;
    ArrayList<Uri> uris = new ArrayList<Uri>();
    for(int i=0; i<imagesFile.size();i++){
        uris.add(Uri.parse(imagesFile.getString(i)));
    }
    Intent intent=new Intent(Intent.ACTION_SEND_MULTIPLE);
    intent.putExtra(Intent.EXTRA_SUBJECT,subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);
    intent.putExtra(Intent.EXTRA_STREAM, uris);
    intent.putExtra ("Kdescription", message);
    intent.setType("image/*");

    Intent chooser = Intent.createChooser(intent, winTitle);
    chooser.addCategory(Intent.CATEGORY_DEFAULT);

    //是否指定App打开
    if(component != null && component.size() == 2) {
        intent.setComponent(new ComponentName(component.getString(0), component.getString(1)));
    }

    getCurrentActivity().startActivityForResult(chooser,SHARE_REQUEST);
}

@ReactMethod
public void downloadImage(ReadableArray imagesUrl, Promise promise){
    List<String> paths = new ArrayList<String>();
    for(int i=0; i<imagesUrl.size();i++){
        String imageUrl = imagesUrl.getString(i);
        String fileName = i + ".jpg";
        String path = this.download(imageUrl,fileName);
        paths.add(path);
    }

    JSONArray array = new JSONArray(paths);
    promise.resolve(array.toString());
}

//下载图片并保存
public String download( String imageUrl, String fileName) {
    final String savePath = getReactApplicationContext().getExternalCacheDir() + "/" + fileName;
    try {
        File f = new File(savePath);
        File dir = f.getParentFile();
        if(!dir.exists())
            dir.mkdirs();
        FileOutputStream os = new FileOutputStream(f);
        byte[] data = getImage(imageUrl);
        os.write(data);
        os.close();
    } catch (Exception e) {
        e.getLocalizedMessage();
    }

    return "file://" + savePath;
}

/*
* 获取网络图片
*/
public byte[] getImage(String imageUrl) throws Exception{
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
        return readStream(inStream);
    }
    return null;
}

/*
获取图片流数据
 */
public static byte[] readStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=inStream.read(buffer)) != -1){
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inStream.close();
    return outStream.toByteArray();
}

}

it will be great if some can help,

thanks advance


问:
how to insert file name into mysql database
I'm trying to figure out from a long time to print my file name in the MySQL database, file is uploading successfully into the path folder but unable to insert the file name into the database. below is my code</p>

```<code>Choose file: <span class="text-danger">Max size 1mb, doc, pdf, jpg, jpeg, png & gif only</span>
            <input type="file" name="fileToUpload" id="fileToUpload" required>
            <input type="hidden" value="Upload Image" name="submit">

     <?php
 $target_dir = "../online/upload_files/";
 $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
 $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($target_file)) {
    echo '<span style="color:#C0392B;text-align:center; size:45"> Sorry,
 file already exists.</span>';
  $uploadOk = 0;
}

 // Check file size
 if ($_FILES["fileToUpload"]["size"] > 1048576) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
 }

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
 && $imageFileType != "gif" && $imageFileType != "doc" && $imageFileType !=
"docx"
&& $imageFileType != "pdf"&& $imageFileType != "xlsx") {
   echo  '<span style="color:#C0392B;text-align:center;">Sorry, only JPG,
 JPEG, PNG, doc, pdf & GIF  files are allowed.</span>' ;
    $uploadOk = 0;
 }

 // Check if $uploadOk is set to 0 by an error
 if ($uploadOk == 0) {
     echo '<span style="color:#C0392B;text-align:center;">Sorry, your file
 was not uploaded.</span>';

 // if everything is ok, try to upload file
  } else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
 $target_file)) {
         echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has
 been uploaded. & <b>Proposal Submited Successfully.</b>";
     } else {
         echo '<span style="color:#C0392B;text-align:center;"> Sorry, there
 was an error uploading your file.</span>';
     }
 }

 ?>
</code>```

答:
Just Add Following Code</p>

```<code>$filename= $_FILES["fileToUpload"]["name"];
$query = INSERT INTO `table`(`image`) VALUES ("$filename");
</code>```

Body:
I'm trying to figure out from a long time to print my file name in the MySQL database, file is uploading successfully into the path folder but unable to insert the file name into the database. below is my code

Choose file: Max size 1mb, doc, pdf, jpg, jpeg, png & gif only
            <input type="file" name="fileToUpload" id="fileToUpload" required>
            <input type="hidden" value="Upload Image" name="submit">

     <?php
 $target_dir = "../online/upload_files/";
 $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
 $uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($target_file)) {
    echo ' Sorry,
 file already exists.';
  $uploadOk = 0;
}

 // Check file size
 if ($_FILES["fileToUpload"]["size"] > 1048576) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
 }

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
 && $imageFileType != "gif" && $imageFileType != "doc" && $imageFileType !=
"docx"
&& $imageFileType != "pdf"&& $imageFileType != "xlsx") {
   echo  'Sorry, only JPG,
 JPEG, PNG, doc, pdf & GIF  files are allowed.' ;
    $uploadOk = 0;
 }

 // Check if $uploadOk is set to 0 by an error
 if ($uploadOk == 0) {
     echo 'Sorry, your file
 was not uploaded.';

 // if everything is ok, try to upload file
  } else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
 $target_file)) {
         echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has
 been uploaded. & Proposal Submited Successfully.";
     } else {
         echo ' Sorry, there
 was an error uploading your file.';
     }
 }

 ?>

Body:
Just Add Following Code

$filename= $_FILES["fileToUpload"]["name"];
$query = INSERT INTO `table`(`image`) VALUES ("$filename");


问:
How to merge git branches in RStudio
I am a beginner to Git and GitHub. I came across tutorials on working with Git using RStudio. Instead of working from git bash RStudio offers a GUI type connection with Git and Github. Can someone tell me whether is it possible to merge git branches in RStudio? If so, how to do that?

Thank you :)

答:
I don't think that you can do that directly from the GUI of Rstudio.

You can (in Rstudio) go to GIT -> More -> Shell and perform the commands, but this is similar to just working from git bash.

(fatherly advice: learn git from the command line, it will benefit you in the long run, when you have to deal with more serious git-issues)

Title: How to merge git branches in RStudio


问:
In eclipse, "c:\ \", "c:", what is the difference between the two c disk representations?
When I use one of them when I switch different workspace I get a different result. Is there something wrong with my workspace Settings?

Code:

```<code>public static void function5() throws IOException {
    File file = new File("c:");
    String[] strArr = file.list();
    System.out.println(strArr.length);
    for (String str : strArr) {
        System.out.println(str);
    }
}
</code>```

答:
Try executing your program as below :

```<code> import java.io.File;
    import java.io.IOException;

    public class TP {

    public static void main(String[] args) throws IOException {
        function5();

    }

    public static void function5() throws IOException {

        File file = new File("c:\\");
        if(file.isDirectory()){
            System.out.println("It is a directory");
        }
        System.out.println("Absolute path is " + file.getAbsolutePath());
        System.out.println("Canonical path is " + file.getCanonicalPath());
        System.out.println("File path is " + file.getPath());
        String[] strArr = file.list();
        System.out.println(strArr.length);
        for(String str : strArr){ System.out.println(str);

        } }

    }
</code>```

you will find that

1) in case of "c:" (File file = new File("c:"); )

Absolute path is your current working directory, from where you are executing this java program.

This is because your workspace is in C: drive

2) in case of "C:\" (File file = new File("c:\");

Absolute path is your C: drive.

If your workspace is not in c: the output content will be same.

EDIT - Added Canonical path and abstract path as well as you can see in case of c: abstract path is c: only and not your java file location.

Body:
When I use one of them when I switch different workspace I get a different result. Is there something wrong with my workspace Settings?

Code:

public static void function5() throws IOException {
    File file = new File("c:");
    String[] strArr = file.list();
    System.out.println(strArr.length);
    for (String str : strArr) {
        System.out.println(str);
    }
}

Body:
Try executing your program as below :

 import java.io.File;
    import java.io.IOException;

    public class TP {

    public static void main(String[] args) throws IOException {
        function5();

    }

    public static void function5() throws IOException {

        File file = new File("c:\\");
        if(file.isDirectory()){
            System.out.println("It is a directory");
        }
        System.out.println("Absolute path is " + file.getAbsolutePath());
        System.out.println("Canonical path is " + file.getCanonicalPath());
        System.out.println("File path is " + file.getPath());
        String[] strArr = file.list();
        System.out.println(strArr.length);
        for(String str : strArr){ System.out.println(str);

        } }

    }

you will find that

1) in case of "c:" (File file = new File("c:"); )

Absolute path is your current working directory, from where you are executing this java program.

This is because your workspace is in C: drive

2) in case of "C:\" (File file = new File("c:\");

Absolute path is your C: drive.

If your workspace is not in c: the output content will be same.

EDIT - Added Canonical path and abstract path as well as you can see in case of c: abstract path is c: only and not your java file location.


问:
Is SQL the assembly for databases?
Talking about hibernate and others ORMs, the ORMs evangelists talk about SQL like the assembly language for Databases.

I think is soon to assert this, but I guess can be true on a near future, not sure.

UPDATE: The analogy I was referring means SQL is to assembly what ORM is to C/Java/C#. Of course, an exact analogy is not possible. The question is if in the future, with more powerful computers the developers are going to use only ORM (or ORM like) instead of SQL.

答:
Let's compare writing parallelized SQL with writing parallelized assembler.

This the way to write a parallelized sql statement in Oracle:

```<code>select /*+ parallel (e, 4)  */ deptno,count(*)
from employees e
group by deptno
</code>```

Now I wish I could tell you how to write parallelized assembler but I strongly doubt it is as easy as adding something like /+ parallel (e,4) /.

OwnerDisplayName: FerranB

Title: Is SQL the assembly for databases?

LastEditorDisplayName: FerranB

Body:
Let's compare writing parallelized SQL with writing parallelized assembler.

This the way to write a parallelized sql statement in Oracle:

select /*+ parallel (e, 4)  */ deptno,count(*)
from employees e
group by deptno

Now I wish I could tell you how to write parallelized assembler but I strongly doubt it is as easy as adding something like /+ parallel (e,4) /.

OwnerDisplayName: tuinstoel


问:
Oracle rownum = 1 to select topmost row from the set fails
I need to select from two tables,

RATING_TABLE

```<code>  RATING_TYPE       RATING_PRIORITY
  TITAN             1
  PLATINUM(+)       1
  PLATINUM          2
  DIAMOND(+)        3
  DIAMOND           3
  GOLD              4
  SILVER            4
</code>```

RATING_STORAGE

```<code>RATING           AMOUNT
SILVER           200
GOLD             510
DIAMOND          850
PLATINUM(+)      980
TITAN            5000
</code>```

I want to select the rating from RATING_STORAGE table based on RATING_PRIORITY from RATING_TABLE.
I want to select one row with lowest rating priority. If two rating priority are eqaul I want to choose the one with the lowest amount.
So I used the query,

```<code>select s.rating,s.amount
from RATING_TABLE r, RATING_STORAGE s
where        r.rating_type= s.rating_type
and rownum=1
order by  r.rating_priority asc , s.amount asc ;
</code>```

I am getting correct output when sorting the result but rownum=1 fails to give the topmost row.

Thanks in Advance.

答:
You need to select after sorting is done, in your case:</p>

```<code>     select *
  from (select s.rating
              ,s.amount
          from rating_table   r
              ,rating_storage s
         where r.rating_type = s.rating_type
           and rownum = 1
         order by r.rating_priority asc
                 ,s.amount          asc)
 where rownum = 1;
</code>```

Body:
I need to select from two tables,

RATING_TABLE

  RATING_TYPE       RATING_PRIORITY
  TITAN             1
  PLATINUM(+)       1
  PLATINUM          2
  DIAMOND(+)        3
  DIAMOND           3
  GOLD              4
  SILVER            4

RATING_STORAGE

RATING           AMOUNT
SILVER           200
GOLD             510
DIAMOND          850
PLATINUM(+)      980
TITAN            5000

I want to select the rating from RATING_STORAGE table based on RATING_PRIORITY from RATING_TABLE.
I want to select one row with lowest rating priority. If two rating priority are eqaul I want to choose the one with the lowest amount.
So I used the query,

select s.rating,s.amount
from RATING_TABLE r, RATING_STORAGE s
where        r.rating_type= s.rating_type
and rownum=1
order by  r.rating_priority asc , s.amount asc ;

I am getting correct output when sorting the result but rownum=1 fails to give the topmost row.

Thanks in Advance.

Body:
You need to select after sorting is done, in your case:

     select *
  from (select s.rating
              ,s.amount
          from rating_table   r
              ,rating_storage s
         where r.rating_type = s.rating_type
           and rownum = 1
         order by r.rating_priority asc
                 ,s.amount          asc)
 where rownum = 1;


答: this is when i use "c:" it can read my c disk </p>

Title: In eclipse, "c:\ \", "c:", what is the difference between the two c disk representations?


问:
Changing temporary directory in R
I'm using a Windows virtual machine and I have both R and RStudio installed on it and I'm trying to change the directory where R writes the temporary files.

When I start R, I try changing the temporary directory and then close R. When I restart R and try tempdir() it still shows the old directory, as if nothing has happened. However, if after attempting to change the temporary directory in R I start RStudio instead of restarting R, when I try tempdir() in RStudio it shows the new/updated directory I set in R. How is this possible? What is happening? Why does only RStudio respond to my changing of the temporary directory but not R, even though that's where I'm changing the directory?

答:
In windows, for me what worked is creating a file named Renviron.site and filling it with

```<code>TMPDIR=E:/rtemp
TMP=E:/rtemp
TEMP=E:/rtemp
</code>```

Where E:/rtemp was the path to the directory where I wanted the temporary files.
So you create a new text file, fill it with the above, and change its name (and extension) to Renviron.site.

Put it inside the R installation directory, in the directory etc (e.g. C:\Program Files\R\R-3.3.2\etc) and restart RStudio or R.

Title: Changing temporary directory in R

Body:
In windows, for me what worked is creating a file named Renviron.site and filling it with

TMPDIR=E:/rtemp
TMP=E:/rtemp
TEMP=E:/rtemp

Where E:/rtemp was the path to the directory where I wanted the temporary files.
So you create a new text file, fill it with the above, and change its name (and extension) to Renviron.site.

Put it inside the R installation directory, in the directory etc (e.g. C:\Program Files\R\R-3.3.2\etc) and restart RStudio or R.


问:
Why arrow functions don't work when using import/export
This code shows "show not defined."

```<code>import {a} from './dis.js';
show = () =>{
  console.log(a);
}
show();
</code>```

But this works

```<code>import {a} from './dis.js';
const show = () =>{
    console.log(a);
}
show();
</code>```

why is that ?

答:
This is not due to arrow function. You are trying to assign a value to show, but have not defined that variable anywhere. Define it using var, let or const

While assigning without defining works in JS, it is not recommended, and not allowed in strict mode.

Body:
This code shows "show not defined."

import {a} from './dis.js';
show = () =>{
  console.log(a);
}
show();

But this works

import {a} from './dis.js';
const show = () =>{
    console.log(a);
}
show();

why is that ?


问:
PostgreSQL how to use WHERE on a subquery output?
```<code>select starttime, (select count(trackid) c2 from playlistitem p1 where
p2.radiobroadcastid = p1.radiobroadcastid) from radiobroadcast p2
</code>```

OUTPUT:

```<code>Starttime               c2
2011-10-14 20:00:00.0   42
2011-10-20 20:00:00.0   43
2011-10-07 09:00:00.0   7
</code>```

I want to only show me the MAX of the c2 column ( thats 43 here ). How do I do that when c2 isn't defined as a column?

EDIT: should probably use a HAVING and GROUP BY clause

```<code>select starttime, count(trackid) from radiobroadcast inner join playlistitem
using(radiobroadcastid) GROUP by starttime HAVING count(*) > 100
</code>```

Anyway to only show MAX value as boolean for count in HAVING?

答:
You need to give the result of the sub-query an alias, then you can order by that alias and apply a limit:

```<code>select starttime,
        (select count(trackid)
         from playlistitem p1
         where p2.radiobroadcastid = p1.radiobroadcastid) as c2
from radiobroadcast p2
order by c2 desc
limit 1;
</code>```

Note that if you have two rows with the same count, you would still only see one using this approach.

To find the highest value using the JOIN statement, use the same approach:

```<code>select starttime,
       count(trackid) as cnt
from radiobroadcast
  join playlistitem using(radiobroadcastid)
GROUP by starttime
order by cnt desc
limit 1;
</code>```

If you have to consider multiple highest counts and what to see all of them, you can use a window function to obtain the highest count, but you need to wrap the query in a derived table in order to use the alias:

```<code>select starttime, cnt
from (
    select starttime,
           count(trackid) as cnt,
           max(count(trackid)) over () as max_cnt
    from radiobroadcast
      join playlistitem using(radiobroadcastid)
    GROUP by starttime
) t
where cnt = max_cnt;
</code>```

If you only need a single row, the LIMIT approach is typically faster then the one using a window function.

Body:
select starttime, (select count(trackid) c2 from playlistitem p1 where
p2.radiobroadcastid = p1.radiobroadcastid) from radiobroadcast p2

OUTPUT:

Starttime               c2
2011-10-14 20:00:00.0   42
2011-10-20 20:00:00.0   43
2011-10-07 09:00:00.0   7

I want to only show me the MAX of the c2 column ( thats 43 here ). How do I do that when c2 isn't defined as a column?

EDIT: should probably use a HAVING and GROUP BY clause

select starttime, count(trackid) from radiobroadcast inner join playlistitem
using(radiobroadcastid) GROUP by starttime HAVING count(*) > 100

Anyway to only show MAX value as boolean for count in HAVING?

Body:
You need to give the result of the sub-query an alias, then you can order by that alias and apply a limit:

select starttime,
        (select count(trackid)
         from playlistitem p1
         where p2.radiobroadcastid = p1.radiobroadcastid) as c2
from radiobroadcast p2
order by c2 desc
limit 1;

Note that if you have two rows with the same count, you would still only see one using this approach.

To find the highest value using the JOIN statement, use the same approach:

select starttime,
       count(trackid) as cnt
from radiobroadcast
  join playlistitem using(radiobroadcastid)
GROUP by starttime
order by cnt desc
limit 1;

If you have to consider multiple highest counts and what to see all of them, you can use a window function to obtain the highest count, but you need to wrap the query in a derived table in order to use the alias:

select starttime, cnt
from (
    select starttime,
           count(trackid) as cnt,
           max(count(trackid)) over () as max_cnt
    from radiobroadcast
      join playlistitem using(radiobroadcastid)
    GROUP by starttime
) t
where cnt = max_cnt;

If you only need a single row, the LIMIT approach is typically faster then the one using a window function.


问:
Why doesn't the website default to index.html by default?
I'm unable to put in the domain name to observe the landing page:

```<code>http://some_url.com
</code>```

Error:

Could not find file 'E:\index.html'.

However, the following works:

http://some_url.com/index.html

FYI:
This website was built with Elm, Giraffe, and .Net Core.

答:
I didn't specify the following:</p>

```<code>let webApp: HttpHandler =
    choose [
        GET >=>
            choose [
                route "/" >=> htmlFile "index.html"
</code>```

Body:
I'm unable to put in the domain name to observe the landing page:

http://some_url.com

Error:

Could not find file 'E:\index.html'.

However, the following works:

http://some_url.com/index.html

FYI:
This website was built with Elm, Giraffe, and .Net Core.

Body:
I didn't specify the following:

let webApp: HttpHandler =
    choose [
        GET >=>
            choose [
                route "/" >=> htmlFile "index.html"


问:
Any ideas how to setup geocoder with rails 5?
I am trying to get latitude and longitude from address but when I run rails db:seed latitude and longitude stay blank and the rest of the fields will be seeded

here is my model

```<code>    attr_accessor :lat, :lng
    geocoded_by :address, :latitude  => :lat, :longitude => :lng
    after_save :geocode, if: ->(building){ building.address.present? }
</code>```

and I have gem 'geocoder' in GemFile

```<code>    My Rails version 5.0.6
    and ruby version 2.4.1
</code>```

Note: I need to use only 'geocoder' gem
That's all I have, thanks in advance

答:
after_save means geocoding is done after the record is saved to the database and therefore the geocoding information itself is not saved into the database.

Furthermore attr_accessor :lat, :lng overrides the getter and setter methods provided by Rails for the lat and lng database columns.

Just change your code to:

```<code># remove this line: attr_accessor :lat, :lng
geocoded_by :address, :latitude  => :lat, :longitude => :lng
before_save :geocode, if: ->(building){ building.address.present? }
</code>```

Body:
I am trying to get latitude and longitude from address but when I run rails db:seed latitude and longitude stay blank and the rest of the fields will be seeded

here is my model

    attr_accessor :lat, :lng
    geocoded_by :address, :latitude  => :lat, :longitude => :lng
    after_save :geocode, if: ->(building){ building.address.present? }

and I have gem 'geocoder' in GemFile

    My Rails version 5.0.6
    and ruby version 2.4.1

Note: I need to use only 'geocoder' gem
That's all I have, thanks in advance

Body:
after_save means geocoding is done after the record is saved to the database and therefore the geocoding information itself is not saved into the database.

Furthermore attr_accessor :lat, :lng overrides the getter and setter methods provided by Rails for the lat and lng database columns.

Just change your code to:

# remove this line: attr_accessor :lat, :lng
geocoded_by :address, :latitude  => :lat, :longitude => :lng
before_save :geocode, if: ->(building){ building.address.present? }


问:
Overlapping data contour on a map
I have gone through few tutorials and answers here in stackoverflow such as:
Overlap image plot on a Google Map background in R or
Plotting contours on an irregular grid or Geographical heat map of a custom property in R with ggmap or How to overlay global map on filled contour in R language or https://blog.dominodatalab.com/geographic-visualization-with-rs-ggmaps/
They either don't serve my purpose or consider the density of the data to create the image.

I am looking for a way to plot contour on a map of a certain data, and would expect the image to look something like this:

or something like this taken from https://dsparks.wordpress.com/2012/07/18/mapping-public-opinion-a-tutorial/:

I have a data here that gives a contour plot like this in plot_ly but i want this over the map given by latitudes and longitudes.

Please guide me on how this can be done. Any links to potential answers or codes would be helpful.

答: Ok I did some digging and figured that to plot the data -which in this case are point values randomly distributed across the Latitude and Longitude, one has to make it continuous instead of the discreetly distributed one. To do this I interpolated the data to fill in the gaps, this method is given in Plotting contours on an irregular grid and then take it from there. Now the interpolation here is done using a linear regression, one can use other methods such as IDW, Kriging, Nearest Neighbourhood etc for which R-packages are easily available. These methods are widely used in climatology and topographic analysis. To read more about interpolation methods see this paper.</p>

Title: Overlapping data contour on a map


问:
Lint complains about not translated gcm_defaultSenderId string
I've followed the tutorial https://developers.google.com/cloud-messaging/android/client. It works - I'm able to send and receive notifications.

But when I try to build release app, Android Lint complains:

```<code>Error: "gcm_defaultSenderId" is not translated in ...
</code>```

So I can disable build failing when Lint complains with this in build.gradle:

```<code>lintOptions{
    abortOnError false
}
</code>```

But obviously this is not a solution. Hardcoding senderId in my app is also not good idea (we have valid gcm_defaultSenderId anyway in the google-services.json so doubling it is asking for problems in the future).

Is there any way around this obvious oversight from Google Play Services developers?

EDIT 02 December 2015
OMG! Today google actuallt started doing something on this issue, see here.

Disclaimer: this is not a duplicate of Can't generate APK Release because of GCM SenderId Android - the accepted answer is not acceptable for me.

答:
Try this

```<code>android {
 lintOptions {
    disable 'MissingTranslation'
}
</code>```

}

Body:
I've followed the tutorial https://developers.google.com/cloud-messaging/android/client. It works - I'm able to send and receive notifications.

But when I try to build release app, Android Lint complains:

Error: "gcm_defaultSenderId" is not translated in ...

So I can disable build failing when Lint complains with this in build.gradle:

lintOptions{
    abortOnError false
}

But obviously this is not a solution. Hardcoding senderId in my app is also not good idea (we have valid gcm_defaultSenderId anyway in the google-services.json so doubling it is asking for problems in the future).

Is there any way around this obvious oversight from Google Play Services developers?

EDIT 02 December 2015
OMG! Today google actuallt started doing something on this issue, see here.

Disclaimer: this is not a duplicate of Can't generate APK Release because of GCM SenderId Android - the accepted answer is not acceptable for me.

Body:
Try this

android {
 lintOptions {
    disable 'MissingTranslation'
}

}


问:
How to "exclude" a blank space from RegExp grouping?

Context

I am a front-end developer working on ExtJS framework, and for purpose of speed, I created a lot of Sublime Text 3's Snippets to agilize the work.

The models of a task, comes from the back-end at C# platform, containing the type of var and the name of it.

Then I got an idea to simply copy the model content and with its string produce a new string that equates to ExtJS model pattern.

Inside the Snippet code, I am not using any programming language (because its not possible), I am only producing output string with regex-only solution, that is the only one thing I can do due to Sublime Text snippet limitations.

Codes

A sample of one line of C# model code is:

         public string Email { get; set; }

All the lines of the model follow that pattern.

At the moment, my Sublime Text 3 Snippet has the code:

```<code><snippet>
    <content><![CDATA[
    { name: '${SELECTION/(        public )|(public )|({ get; set; })|(\w)|( \w+)|( )/(?5$5/\s/)/g}', type: '${SELECTION/(        public )|(public )|({ get; set; })|(\ \$w\ \w.)|( \w+)|( )/(?1)(?2)(?3)(?4\$5\$6\)($5)($6)/g}' },
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>
</code>```

PS: the ${SELECTION} var is a snippet var that gets the string that was selected when you triggered the snippet.
The string that results using my snippet with that sample string selected is:

     { type: 'string', name: ' Email' },

Problem

As you can see above, I got almost the perfect result, but my problem is that blank space before Email.

I have tried millions of different combinations and so, but I am beginner on regex and cant solve that.

I think that creating a group that match a space and excluding it from the main group target string solves the problem, but I don't know how to do that exactly, the truth is that regex that I've generated was on trail-and-error method, because I am a beginner at regex.

I'm asking a help to remove that space only, probably its a simple task to a RegExp expert.

答:
You could use:

```<code><snippet>
    <content><![CDATA[
    { ${SELECTION/\s*\bpublic\s+([\w<>]+)\s+(\w+).*/'name': '$2', 'type': '$1'/} },
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>
</code>```

which would output

```<code>    { 'name': 'Email', 'type': 'string' },
</code>```

for your given example

```<code>        public string Email { get; set; }
</code>```

How it works:

\s*\bpublic - match any number of whitespace characters, followed by a word boundary, followed by public

\s+ match at least one whitespace character

([\w<>]+) match at least one word character or angle bracket (to support generic types, in case it's useful) and store the result into capture group 1

\s+ match at least one whitespace character

(\w+) match at least one word character (the identifier) and store the result into capture group 2

.* match the rest of the selection

/ begin replacement

replace with 'name': '$2', 'type': '$1', where $1 will be filled from capture group 1, and $2 from capture group 2

/ end replacement

I didn't include the global flag because this regex only needs to match once per line/selection.

Actually, we could make it replace all such lines in your selection:

```<code><snippet>
    <content><![CDATA[
${SELECTION/\s*\bpublic\s+([\w<>]+)\s+(\w+).*?(\n|$)/    \{ 'name': '$2', 'type': '$1' \},\n/g}
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>
</code>```

Would convert

```<code>        public string Email { get; set; }
        public string Name { get; set; }
</code>```

to

```<code>    { 'name': 'Email', 'type': 'string' },
    { 'name': 'Name', 'type': 'string' },
</code>```

EDIT: based on feedback in the comments about mapping types, here is the new snippet content:

```<code><snippet>
    <content><![CDATA[
${SELECTION/\s*\bpublic\s+(?:(DateTime)|(bool)|(decimal)|([\w<>]+))\s+(?<name>\w+).*?(\n|$)/    \{ name: '$+{name}', type: '(?1date)(?2boolean)(?3float)(?4$4)' \},\n/g}
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>
</code>```

The string replacement format is documented at http://www.boost.org/doc/libs/1_51_0/libs/regex/doc/html/boost_regex/format/boost_format_syntax.html.

Here, I'm using a named capture group, called name, for simplicity.

Body:
Context

I am a front-end developer working on ExtJS framework, and for purpose of speed, I created a lot of Sublime Text 3's Snippets to agilize the work.

The models of a task, comes from the back-end at C# platform, containing the type of var and the name of it.

Then I got an idea to simply copy the model content and with its string produce a new string that equates to ExtJS model pattern.

Inside the Snippet code, I am not using any programming language (because its not possible), I am only producing output string with regex-only solution, that is the only one thing I can do due to Sublime Text snippet limitations.

Codes

A sample of one line of C# model code is:

         public string Email { get; set; }

All the lines of the model follow that pattern.

At the moment, my Sublime Text 3 Snippet has the code:

<snippet>
    <content><![CDATA[
    { name: '${SELECTION/(        public )|(public )|({ get; set; })|(\w)|( \w+)|( )/(?5$5/\s/)/g}', type: '${SELECTION/(        public )|(public )|({ get; set; })|(\ \$w\ \w.)|( \w+)|( )/(?1)(?2)(?3)(?4\$5\$6\)($5)($6)/g}' },
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>

PS: the ${SELECTION} var is a snippet var that gets the string that was selected when you triggered the snippet.
The string that results using my snippet with that sample string selected is:

     { type: 'string', name: ' Email' },

Problem

As you can see above, I got almost the perfect result, but my problem is that blank space before Email.

I have tried millions of different combinations and so, but I am beginner on regex and cant solve that.

I think that creating a group that match a space and excluding it from the main group target string solves the problem, but I don't know how to do that exactly, the truth is that regex that I've generated was on trail-and-error method, because I am a beginner at regex.

I'm asking a help to remove that space only, probably its a simple task to a RegExp expert.

Body:
You could use:

<snippet>
    <content><![CDATA[
    { ${SELECTION/\s*\bpublic\s+([\w<>]+)\s+(\w+).*/'name': '$2', 'type': '$1'/} },
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>

which would output

    { 'name': 'Email', 'type': 'string' },

for your given example

        public string Email { get; set; }

How it works:

\s*\bpublic - match any number of whitespace characters, followed by a word boundary, followed by public

\s+ match at least one whitespace character

([\w<>]+) match at least one word character or angle bracket (to support generic types, in case it's useful) and store the result into capture group 1

\s+ match at least one whitespace character

(\w+) match at least one word character (the identifier) and store the result into capture group 2

.* match the rest of the selection

/ begin replacement

replace with 'name': '$2', 'type': '$1', where $1 will be filled from capture group 1, and $2 from capture group 2

/ end replacement

I didn't include the global flag because this regex only needs to match once per line/selection.

Actually, we could make it replace all such lines in your selection:

<snippet>
    <content><![CDATA[
${SELECTION/\s*\bpublic\s+([\w<>]+)\s+(\w+).*?(\n|$)/    \{ 'name': '$2', 'type': '$1' \},\n/g}
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>

Would convert

        public string Email { get; set; }
        public string Name { get; set; }

to

    { 'name': 'Email', 'type': 'string' },
    { 'name': 'Name', 'type': 'string' },

EDIT: based on feedback in the comments about mapping types, here is the new snippet content:

<snippet>
    <content><![CDATA[
${SELECTION/\s*\bpublic\s+(?:(DateTime)|(bool)|(decimal)|([\w<>]+))\s+(?<name>\w+).*?(\n|$)/    \{ name: '$+{name}', type: '(?1date)(?2boolean)(?3float)(?4$4)' \},\n/g}
]]></content>
    <tabTrigger>modelnames</tabTrigger>
</snippet>

The string replacement format is documented at http://www.boost.org/doc/libs/1_51_0/libs/regex/doc/html/boost_regex/format/boost_format_syntax.html.

Here, I'm using a named capture group, called name, for simplicity.


问:
OracleMTSRecoveryService failed to start?
i am getting this error while starting OracleMTSRecoveryService :

```<code>Could not start the OracleMTSRecoveryService service on Local Computer.
Error 1: Incorrect function.*
</code>```

Also during installation of ODAC service start failed.

OracleXETNSListener is also not starting. i have reinstalled ODAC but problem remains.

any suggestions? Any service conflicts?

答:
I had the same problem and my issue was that the host name was wrong in my tnsnames and listener folders from C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN

This happened after a domain migration of my computer as it's name changed.

Body:
i am getting this error while starting OracleMTSRecoveryService :

Could not start the OracleMTSRecoveryService service on Local Computer.
Error 1: Incorrect function.*

Also during installation of ODAC service start failed.

OracleXETNSListener is also not starting. i have reinstalled ODAC but problem remains.

any suggestions? Any service conflicts?