问:
Automation support for Visual Basic 6 ListView
I need to get value/text of control via automation interface (coding with C++/C#). I tried with UI Automation API and this is some result captured by the Inspect:

UI Automation recognize these control as pane and I can't get list view text item or get/set slider value as normal.

Tried with other tool like MSAA, Automation Spy give the same result.

After researching, I found that control with class name like ListView20WndClass, Slider20WndClass, ... belong to Visual Basic 6 control.

So, Is there any API can support these type of control as well?

Remark 1:
There is a tool named Ranorex can support these control (sadly, it is €3490 commercial license), and I don't know which underlying API was used:

Remark 2
There are some other control type used in the application under test that UI Automation still can get value:

ThunderRT6FormDC: recognize as window

ThunderRT6CommandButton: recognize as button

ThunderRT6CheckBox: recognize as checkbox

etc...

sadly, they embed ListView20WndClass and Slider20WndClass but both recognize as pane

Update 1
I create a simple program to get text but still not working (compile as Unicode Character Set):

```<code>#include <iostream>
using namespace std;

#include <UIAutomation.h>
#include <atlstr.h>
#include <Commctrl.h>

CString getListViewItemText(HWND hwnd, int nItem, int nSubItem) {
    LVITEM item;
    memset(&item, 0, sizeof(LVITEM));
    item.iSubItem = nSubItem;
    CString string;
    int Length = 64; //initial reasonable string length
    int ReturnCode;

    do {
        Length *= 2; //resize the string buffer
        item.cchTextMax = Length;
        item.pszText = string.GetBufferSetLength(Length);

        ReturnCode = (int)::SendMessage(hwnd, LVM_GETITEMTEXT,
            (WPARAM)nItem, (LPARAM)&item);
        printf("len = %d \n", ReturnCode);

    } while (ReturnCode == Length - 1); //if could not get all chars, try again

    string.ReleaseBuffer();
    return string;
}

void UI_Spy() {

    // Init COM
    CoInitialize(NULL);

    // Init UIAutomation instance
    IUIAutomation *pAuto;
    CoCreateInstance(CLSID_CUIAutomation, NULL,
        CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<void**>(&pAuto));

    if (pAuto) {

        IUIAutomationElement *pElm;
        POINT p;

        for (int i = 0; i < 10; i++) {
            for (int j = 5; j > 0; j--) {
                Sleep(1000);
                printf("%d ", j);
            }
            GetCursorPos(&p);
            if (pAuto->ElementFromPoint(p, &pElm) == S_OK) {
                wprintf(L"\nPOSITION x = %d, y = %d\n", p.x, p.y);

                BSTR str;
                pElm->get_CurrentName(&str);
                wprintf(L"-Name = %s\n", str);
                SysFreeString(str);

                pElm->get_CurrentLocalizedControlType(&str);
                wprintf(L"-Type = %s\n", str);
                SysFreeString(str);

                CONTROLTYPEID typeId;
                pElm->get_CurrentControlType(&typeId);

                switch (typeId) {

                    // Process checkbox
                case UIA_CheckBoxControlTypeId:
                    IUIAutomationTogglePattern  *toggle;
                    pElm->GetCurrentPattern(UIA_TogglePatternId, (IUnknown**)&toggle);
                    ToggleState state;
                    toggle->get_CurrentToggleState(&state);
                    printf("-Checkbox = %s\n", state == ToggleState::ToggleState_On ? "TRUE"
                        : (state == ToggleState::ToggleState_Off ? "FALSE" : "INTER"));
                    break;

                    // Process VB6 listview
                case UIA_PaneControlTypeId:
                    pElm->get_CurrentClassName(&str);
                    if (str != nullptr && wcscmp(str, L"ListView20WndClass") == 0) {
                        HWND hwnd;
                        pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                        printf("-VB6 Listview: %p\n", hwnd);

                        CString txt = getListViewItemText(hwnd, 0, 0);
                        //txt = "Test";
                        printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    }
                    SysFreeString(str);
                    break;

                    // Process normal listview
                case UIA_ListControlTypeId:
                    HWND hwnd;
                    pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                    printf("-Normal Listview: %p\n", hwnd);

                    CString txt = getListViewItemText(hwnd, 0, 0);
                    //txt = "Test";
                    printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    break;
                }

                wprintf(L"\n");
                pElm->Release();
            }
            printf("\n");
        }

        // Release UIAutomation instance
        pAuto->Release();
    }

    // Release COM
    CoUninitialize();
}

int main()
{
    UI_Spy();

    cin.get();
    return 0;
}
</code>```

When it count 5..4..3..2..1 just mouse over some element on the screen to check.

But when I mouse over the list view:

VB6 list view (ListView20WndClass): it return an empty string (expected is 101 as my example)

MFC/Winform list view (SysListView32): the application under mouse stopped working (the console application still running)

答:
You can use pywinauto which can automate VB6 apps using Win32 API under the hood (all details are hidden including LVM_GETITEM message etc.). Most of the controls can be recognized as buttons, check boxes and even list views! See supported class names for list views. Your cases are here.

And Win32 API should work faster than with UI Automation if using flexible waits. Though UI Automation is also supported under the hood if any.

The Getting Started Guide will help you to do first steps and to learn the high level concept. Also feel free to ask questions with tag pywinauto. I'm the library maintainer.

Body:
I need to get value/text of control via automation interface (coding with C++/C#). I tried with UI Automation API and this is some result captured by the Inspect:

UI Automation recognize these control as pane and I can't get list view text item or get/set slider value as normal.

Tried with other tool like MSAA, Automation Spy give the same result.

After researching, I found that control with class name like ListView20WndClass, Slider20WndClass, ... belong to Visual Basic 6 control.

So, Is there any API can support these type of control as well?

Remark 1:
There is a tool named Ranorex can support these control (sadly, it is €3490 commercial license), and I don't know which underlying API was used:

Remark 2
There are some other control type used in the application under test that UI Automation still can get value:

ThunderRT6FormDC: recognize as window

ThunderRT6CommandButton: recognize as button

ThunderRT6CheckBox: recognize as checkbox

etc...

sadly, they embed ListView20WndClass and Slider20WndClass but both recognize as pane

Update 1
I create a simple program to get text but still not working (compile as Unicode Character Set):

#include <iostream>
using namespace std;

#include <UIAutomation.h>
#include <atlstr.h>
#include <Commctrl.h>

CString getListViewItemText(HWND hwnd, int nItem, int nSubItem) {
    LVITEM item;
    memset(&item, 0, sizeof(LVITEM));
    item.iSubItem = nSubItem;
    CString string;
    int Length = 64; //initial reasonable string length
    int ReturnCode;

    do {
        Length *= 2; //resize the string buffer
        item.cchTextMax = Length;
        item.pszText = string.GetBufferSetLength(Length);

        ReturnCode = (int)::SendMessage(hwnd, LVM_GETITEMTEXT,
            (WPARAM)nItem, (LPARAM)&item);
        printf("len = %d \n", ReturnCode);

    } while (ReturnCode == Length - 1); //if could not get all chars, try again

    string.ReleaseBuffer();
    return string;
}

void UI_Spy() {

    // Init COM
    CoInitialize(NULL);

    // Init UIAutomation instance
    IUIAutomation *pAuto;
    CoCreateInstance(CLSID_CUIAutomation, NULL,
        CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<void**>(&pAuto));

    if (pAuto) {

        IUIAutomationElement *pElm;
        POINT p;

        for (int i = 0; i < 10; i++) {
            for (int j = 5; j > 0; j--) {
                Sleep(1000);
                printf("%d ", j);
            }
            GetCursorPos(&p);
            if (pAuto->ElementFromPoint(p, &pElm) == S_OK) {
                wprintf(L"\nPOSITION x = %d, y = %d\n", p.x, p.y);

                BSTR str;
                pElm->get_CurrentName(&str);
                wprintf(L"-Name = %s\n", str);
                SysFreeString(str);

                pElm->get_CurrentLocalizedControlType(&str);
                wprintf(L"-Type = %s\n", str);
                SysFreeString(str);

                CONTROLTYPEID typeId;
                pElm->get_CurrentControlType(&typeId);

                switch (typeId) {

                    // Process checkbox
                case UIA_CheckBoxControlTypeId:
                    IUIAutomationTogglePattern  *toggle;
                    pElm->GetCurrentPattern(UIA_TogglePatternId, (IUnknown**)&toggle);
                    ToggleState state;
                    toggle->get_CurrentToggleState(&state);
                    printf("-Checkbox = %s\n", state == ToggleState::ToggleState_On ? "TRUE"
                        : (state == ToggleState::ToggleState_Off ? "FALSE" : "INTER"));
                    break;

                    // Process VB6 listview
                case UIA_PaneControlTypeId:
                    pElm->get_CurrentClassName(&str);
                    if (str != nullptr && wcscmp(str, L"ListView20WndClass") == 0) {
                        HWND hwnd;
                        pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                        printf("-VB6 Listview: %p\n", hwnd);

                        CString txt = getListViewItemText(hwnd, 0, 0);
                        //txt = "Test";
                        printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    }
                    SysFreeString(str);
                    break;

                    // Process normal listview
                case UIA_ListControlTypeId:
                    HWND hwnd;
                    pElm->get_CurrentNativeWindowHandle((UIA_HWND*)&hwnd);
                    printf("-Normal Listview: %p\n", hwnd);

                    CString txt = getListViewItemText(hwnd, 0, 0);
                    //txt = "Test";
                    printf("-[0,0] = %S\n", (const wchar_t*)txt);
                    break;
                }

                wprintf(L"\n");
                pElm->Release();
            }
            printf("\n");
        }

        // Release UIAutomation instance
        pAuto->Release();
    }

    // Release COM
    CoUninitialize();
}

int main()
{
    UI_Spy();

    cin.get();
    return 0;
}

When it count 5..4..3..2..1 just mouse over some element on the screen to check.

But when I mouse over the list view:

VB6 list view (ListView20WndClass): it return an empty string (expected is 101 as my example)

MFC/Winform list view (SysListView32): the application under mouse stopped working (the console application still running)


来源: stackexchange

问:
PHP values from select into array for json
Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

```<code>include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`";

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}
</code>```

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

Thanks :)

答:
You have to use whole the code in object oriented way like this:

```<code>$result = $mysqli->query($sql);
$data = array();
if($result->num_rows > 0) {
   while ($row = $result->fetch_assoc()) {
      $data[] = $row;
   }
}
echo json_encode($data);
</code>```

If it doesn't work, then there will be some other issue. try printing $row in the loop start.

ContentLicense: CC BY-SA 3.0

Body:
Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`";

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

Thanks :)

Body:
You have to use whole the code in object oriented way like this:

$result = $mysqli->query($sql);
$data = array();
if($result->num_rows > 0) {
   while ($row = $result->fetch_assoc()) {
      $data[] = $row;
   }
}
echo json_encode($data);

If it doesn't work, then there will be some other issue. try printing $row in the loop start.


问:
How to comment multiple lines in PhpStorm IDE?
I use PhpStorm to edit PHP files and configuration files for Apache. How to comment on the selected block and set the symbol comment?
I want,for example,

```<code>   <Directory />
        Options FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
    </Directory>
</code>```

to

```<code>   #<Directory />
   #    Options FollowSymLinks
   #    AllowOverride None
   #    Order deny,allow
   #    Deny from all
   #</Directory>
</code>```

答:
in mac :</p>

```<code>block some lines of codes
command + /
</code>```

Body:
I use PhpStorm to edit PHP files and configuration files for Apache. How to comment on the selected block and set the symbol comment?
I want,for example,

   <Directory />
        Options FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
    </Directory>

to

   #<Directory />
   #    Options FollowSymLinks
   #    AllowOverride None
   #    Order deny,allow
   #    Deny from all
   #</Directory>

Body:
in mac :

block some lines of codes
command + /


问:
Understanding TypeScript and SystemJS WITHOUT Angular
I've been researching and doing simple "hello worlds" with TypeScript recently. There is something I think I can't wrap my head around and that is how to use System.js with TypeScript. Every single tutorial or demo out there on the internet is about Angular2 and I don't want to get involved with Angular 2 yet.

As an example, I have the following project structure:

```<code>RootFolder
|
| _lib
| ...... ts (where .ts files are)
|
| components (where compiled .js files are)
| libraries
| ......... systemjs (where system.js is)
|
| index.html
| tsconfig.json
</code>```

My tsconfig.json file is looking like:

```<code>{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "outDir": "./components"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ],
  "include": [
    "./_lib/ts/**/*"
  ]
}
</code>```

TypeScript compilation works as expected and there are no problems with that. I have created a simple class named "Alerter" contains the following code:

```<code>//alerter.ts
class Alerter {
    showMessage(): void {
        alert("Message displayed.");
    }
}

export default Alerter
</code>```

And an app.ts (which is my "main" application file) with the following code:

```<code>//app.ts
import Alerter from "./alerter";

console.log("app.js included & executed");

function test() {
    console.log("test called");
    const alt = new Alerter();
    alt.showMessage();
};
</code>```

And in my index.html I just want to import this app.js with System.js and simply want to call "test" function from the console. But it does not work. No matter what I did I simply can't access the function. I see the first console.log line being executed but when I try to call test() from chrome console it is undefined.

If I remove the "alerter" class dependency from my main.ts everything works. Because compiled app.js only contains console.log calls and the function definition.

Here is my System.js calls in index.html

```<code>System.config({
    packages: {
        "components": {
            defaultExtension: "js"
        }
    }
});

System.import("components/app");
</code>```

I'm really desperate now and think I should simply go back to Jquery days. This is so simple yet can't make it work.

Body:
I've been researching and doing simple "hello worlds" with TypeScript recently. There is something I think I can't wrap my head around and that is how to use System.js with TypeScript. Every single tutorial or demo out there on the internet is about Angular2 and I don't want to get involved with Angular 2 yet.

As an example, I have the following project structure:

RootFolder
|
| _lib
| ...... ts (where .ts files are)
|
| components (where compiled .js files are)
| libraries
| ......... systemjs (where system.js is)
|
| index.html
| tsconfig.json

My tsconfig.json file is looking like:

{
  "compileOnSave": true,
  "compilerOptions": {
    "noImplicitAny": true,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "outDir": "./components"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ],
  "include": [
    "./_lib/ts/**/*"
  ]
}

TypeScript compilation works as expected and there are no problems with that. I have created a simple class named "Alerter" contains the following code:

//alerter.ts
class Alerter {
    showMessage(): void {
        alert("Message displayed.");
    }
}

export default Alerter

And an app.ts (which is my "main" application file) with the following code:

//app.ts
import Alerter from "./alerter";

console.log("app.js included & executed");

function test() {
    console.log("test called");
    const alt = new Alerter();
    alt.showMessage();
};

And in my index.html I just want to import this app.js with System.js and simply want to call "test" function from the console. But it does not work. No matter what I did I simply can't access the function. I see the first console.log line being executed but when I try to call test() from chrome console it is undefined.

If I remove the "alerter" class dependency from my main.ts everything works. Because compiled app.js only contains console.log calls and the function definition.

Here is my System.js calls in index.html

System.config({
    packages: {
        "components": {
            defaultExtension: "js"
        }
    }
});

System.import("components/app");

I'm really desperate now and think I should simply go back to Jquery days. This is so simple yet can't make it work.

Body:
I see what's going on here. This is related to both proper usage of TypeScript export keyword and SystemJS.

From your description you basically want to use SystemJS to import a JavaScript file similarly to using just the <script> tag and then use its global defined functions.

But this means you need to be aware of how TypeScript compiles your files. The documentation at https://www.typescriptlang.org/docs/handbook/modules.html says:

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.

This is what you're doing. The app.ts file has one import and the alerter.ts file has one export statement so these both are going to be compiled as modules. Then from your tsconfig.json I see you're using the system format (however, it doesn't matter here).

One major benefit of modules is that they don't leak any global objects outside the of their scope. So when you call System.import("components/app") the test() function exists only within that module. But you can export the function and call it after the module is loaded:

This means you need to export the function first:

// app.ts
export function test() {
  ...
};

Then System.import() returns a Promise that is resolved with the module exports object so we can call the test() method there.

System.import("components/app").then(function(m) {
  m.test();
});

This really works as you expect.

However, it looks like you wanted to define the test() function globaly. In such case you need to define the function on the window global object yourself:

// app.ts
function test() {
  ...
}
declare const window;
window.test = test;

Now you can use it whenever you want after importing the package:

System.import("components/app").then(function(m) {
  test();
});

SystemJS has multiple ways to manipulate with global objects but I don't think there's any easier way to use them when your imported package has dependencies that need to be resolved as well (otherwise have a look at this but it's not your use-case https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md#exports).


问:
SQL adding a field that combines the id and an increment number based on customer
I would like to ask the question regarding the title matter.
My current table is look like below:

```<code>Customer ID    Product ID    Product Name
---------------------------------------------
111            6577          ProductA
111            6123          ProductB
111            2133          ProductC
111            1123          ProductD
222            6577          ProductA
222            6123          ProductB
222            1578          ProductL
333            9273          ProductX
</code>```

And the result should look like (with the additional field RefID):

```<code>Customer ID    Product ID    Product Name   RefID
--------------------------------------------------
111            6577          ProductA       111-1
111            6123          ProductB       111-2
111            2133          ProductC       111-3
111            1123          ProductD       111-4
222            6577          ProductA       222-1
222            6123          ProductB       222-2
222            1578          ProductL       222-3
333            9273          ProductX       333-1
</code>```

I am not very clear what should i do to achieve this?
Could you please help me?

Many thanks

答:
For SQL server

```<code>select MT.*,
       Customer_ID + '-' + row_number() over(partition by Customer_ID order by Product_Name) as RefID
from MyTable MT
</code>```

Oracle

```<code>select MT.*,
       to_char(Customer_ID, '99999') || '-' || to_char(row_number() over(partition by Customer_ID order by Product_Name) , '99999')  as RefID
from MyTable MT
</code>```

Body:
I would like to ask the question regarding the title matter.
My current table is look like below:

Customer ID    Product ID    Product Name
---------------------------------------------
111            6577          ProductA
111            6123          ProductB
111            2133          ProductC
111            1123          ProductD
222            6577          ProductA
222            6123          ProductB
222            1578          ProductL
333            9273          ProductX

And the result should look like (with the additional field RefID):

Customer ID    Product ID    Product Name   RefID
--------------------------------------------------
111            6577          ProductA       111-1
111            6123          ProductB       111-2
111            2133          ProductC       111-3
111            1123          ProductD       111-4
222            6577          ProductA       222-1
222            6123          ProductB       222-2
222            1578          ProductL       222-3
333            9273          ProductX       333-1

I am not very clear what should i do to achieve this?
Could you please help me?

Many thanks

Body:
For SQL server

select MT.*,
       Customer_ID + '-' + row_number() over(partition by Customer_ID order by Product_Name) as RefID
from MyTable MT

Oracle

select MT.*,
       to_char(Customer_ID, '99999') || '-' || to_char(row_number() over(partition by Customer_ID order by Product_Name) , '99999')  as RefID
from MyTable MT


问:
Get Date from a long var char milliseconds value stored in oracle Database
I have a date store in data base as a long value in varchar eg: 1230748200000.
I need to get the year out from it withing the oracle query..how can i please do it in oracle? is there a way that i can covert that in to a Date so that i can get the year? The problem is i cant use to_char(SYSTIMESTAMP,'yyyy')  or to_Date because i dont have the date in Timestamp or Date format...instead having it as long varchar

Thank You.

Edit:
Can you please give a solution for the following scenario. I have 1262284398000 in my table save as var char.so as i said i need to get year i use the following sql which return year as 2009

```<code>    select
to_char(
to_date('01-JAN-1970','DD-MM-YYYY HH24:MI SS') + ( 1262284398000 / (1000*60 * 60 * 24) ) ,'YYYY')
from dual ;
</code>```

But in java code same value returns date as 2010 so the year is get diferent,

```<code>Calendar c = Calendar.getInstance();
  c.setTimeInMillis(1262284398000l);
  System.out.println(c.getTime());
  System.out.println(c.get(Calendar.YEAR));
</code>```

Which date return as Fri Jan 01 00:03:18 IST2010                                                                                Why is the difference here please?

答:
@MikeyByCrikey posted a good starting point, but there are a couple questions you need to answer before you can convert your string value to a date:

A.  What date is represented by '0'?  That is, where does this millisecond count value start from?  In @Mikey's example the Unix 'beginning' date (also called the 'epoch date') of 01-Jan-1970 is used, but there isn't enough information in your post to know what the '0' date actually is.  Other systems use different epoch dates.  For example, on systems running the VMS operating system the epoch date is 17-Nov-1858 (happens to be Julian day 2,400,000); Windows (32 and 64 bit versions) uses 01-Jan-1601 (first year of the 400 year Gregorian calendar cycle which was current when this OS was designed); and other computer systems use different '0' dates.

B.  Converting a string to a number in Oracle is fairly easy.  I'd just use the TO_NUMBER function, as in:

```<code>  strMillisecs   VARCHAR2(100) := '1230748200000';
  nMilliseconds  NUMBER;

  nMilliseconds := TO_NUMBER(strMillisecs);
</code>```

C.  Once you've gotten to this point (the '0' date is known, and the string is converted to a number) the year can be extracted as follows:

```<code>  dtEpoch_date         DATE := TO_DATE('01-JAN-1970', 'DD-MON-YYYY');  -- for example
  strMillisecs         VARCHAR2(100) := '1230748200000';
  nMilliseconds        NUMBER;
  dtTarget_date        DATE;
  nYear                NUMBER;
  nMillisecs_in_a_day  NUMBER := 86400000;

  nMilliseconds := TO_NUMBER(strMillisecs);

  -- Note: there are

  dtTarget_date := dtEpoch_date + (nMilliseconds / nMillisecs_in_a_day);

  -- FINALLY!

  nYear := TO_NUMBER(TO_CHAR(dtTarget_date, 'YYYY'));
</code>```

Hopefully this is useful.

Share and enjoy.

ContentLicense: CC BY-SA 2.5

Body:
I have a date store in data base as a long value in varchar eg: 1230748200000.
I need to get the year out from it withing the oracle query..how can i please do it in oracle? is there a way that i can covert that in to a Date so that i can get the year? The problem is i cant use to_char(SYSTIMESTAMP,'yyyy')  or to_Date because i dont have the date in Timestamp or Date format...instead having it as long varchar

Thank You.

Edit:
Can you please give a solution for the following scenario. I have 1262284398000 in my table save as var char.so as i said i need to get year i use the following sql which return year as 2009

    select
to_char(
to_date('01-JAN-1970','DD-MM-YYYY HH24:MI SS') + ( 1262284398000 / (1000*60 * 60 * 24) ) ,'YYYY')
from dual ;

But in java code same value returns date as 2010 so the year is get diferent,

Calendar c = Calendar.getInstance();
  c.setTimeInMillis(1262284398000l);
  System.out.println(c.getTime());
  System.out.println(c.get(Calendar.YEAR));

Which date return as Fri Jan 01 00:03:18 IST2010                                                                                Why is the difference here please?

Body:
@MikeyByCrikey posted a good starting point, but there are a couple questions you need to answer before you can convert your string value to a date:

A.  What date is represented by '0'?  That is, where does this millisecond count value start from?  In @Mikey's example the Unix 'beginning' date (also called the 'epoch date') of 01-Jan-1970 is used, but there isn't enough information in your post to know what the '0' date actually is.  Other systems use different epoch dates.  For example, on systems running the VMS operating system the epoch date is 17-Nov-1858 (happens to be Julian day 2,400,000); Windows (32 and 64 bit versions) uses 01-Jan-1601 (first year of the 400 year Gregorian calendar cycle which was current when this OS was designed); and other computer systems use different '0' dates.

B.  Converting a string to a number in Oracle is fairly easy.  I'd just use the TO_NUMBER function, as in:

  strMillisecs   VARCHAR2(100) := '1230748200000';
  nMilliseconds  NUMBER;

  nMilliseconds := TO_NUMBER(strMillisecs);

C.  Once you've gotten to this point (the '0' date is known, and the string is converted to a number) the year can be extracted as follows:

  dtEpoch_date         DATE := TO_DATE('01-JAN-1970', 'DD-MON-YYYY');  -- for example
  strMillisecs         VARCHAR2(100) := '1230748200000';
  nMilliseconds        NUMBER;
  dtTarget_date        DATE;
  nYear                NUMBER;
  nMillisecs_in_a_day  NUMBER := 86400000;

  nMilliseconds := TO_NUMBER(strMillisecs);

  -- Note: there are

  dtTarget_date := dtEpoch_date + (nMilliseconds / nMillisecs_in_a_day);

  -- FINALLY!

  nYear := TO_NUMBER(TO_CHAR(dtTarget_date, 'YYYY'));

Hopefully this is useful.

Share and enjoy.


问:
Highlighter.net returns no matches
I am using lucene.net 2.9.4 and lucene.net contrib 2.9.4 my lucene query looks like:

```<code>+contents:umbraco*
</code>```

I get results for this query. My highlighter code to get fragments looks like:

```<code>public string GetHighlight(string value, string highlightField, IndexSearcher searcher, string luceneRawQuery)
    {
        var query = GetQueryParser(highlightField).Parse(luceneRawQuery);

        var scorer = new QueryScorer(searcher.Rewrite(query));

        var highlighter = new Highlighter(HighlightFormatter, scorer);

        var tokenStream = HighlightAnalyzer.TokenStream(highlightField, new StringReader(value));

        return highlighter.GetBestFragments(tokenStream, value, MaxNumHighlights, Separator);
    }
</code>```

In my scorer object the property termsToFind is 0 I would expect that to at least be one?  Anyone any ideas or suggestions on how to fix / debug?

Regards

Ismail

答: Ok figured this out I was passing in the wrong values to the highlighter function. I was passing the query search term and field name. What i needed to pass in was the content of the contents field for each document match and the query term.  All working now.</p>

Title: Highlighter.net returns no matches

Body:
I am using lucene.net 2.9.4 and lucene.net contrib 2.9.4 my lucene query looks like:

+contents:umbraco*

I get results for this query. My highlighter code to get fragments looks like:

public string GetHighlight(string value, string highlightField, IndexSearcher searcher, string luceneRawQuery)
    {
        var query = GetQueryParser(highlightField).Parse(luceneRawQuery);

        var scorer = new QueryScorer(searcher.Rewrite(query));

        var highlighter = new Highlighter(HighlightFormatter, scorer);

        var tokenStream = HighlightAnalyzer.TokenStream(highlightField, new StringReader(value));

        return highlighter.GetBestFragments(tokenStream, value, MaxNumHighlights, Separator);
    }

In my scorer object the property termsToFind is 0 I would expect that to at least be one?  Anyone any ideas or suggestions on how to fix / debug?

Regards

Ismail


问:
select the value from ul-li dropdown in protractor
elementi want to select a 3rd value from the drop down of 6 options and the code snippet for a single option as below: the div class is under the li class.

RELV-Indirect Tax

RELV-Indirect Tax

i dont want to select by id instead i want to pass the value as "RELV-Indirect Tax". how to do the same?

答:
Try the following code and let me know.
Clicking on the dropdown will work for you I guess.

```<code>var selectdropdown = element(by.xpath("//select[@id='TaxProcessMod']"));
selectdropdown.click();
selectdropdown.all(by.xpath("//option[@class='ng-scope ng-binding']")).get(1).click();
</code>```

OR

```<code>selectdropdown.all(by.className("ng-scope ng-binding")).get(1).click();
</code>```

Body:
Try the following code and let me know.
Clicking on the dropdown will work for you I guess.

var selectdropdown = element(by.xpath("//select[@id='TaxProcessMod']"));
selectdropdown.click();
selectdropdown.all(by.xpath("//option[@class='ng-scope ng-binding']")).get(1).click();

OR

selectdropdown.all(by.className("ng-scope ng-binding")).get(1).click();


问:
Are there any plans to implement further data types in ArangoDB with VelocityPack?
Currently numbers are stored as 64bit binary, both for floating points and integers: are there any plans to implement integers and other data (such as binary data) natively in ArangoDB?</p>

答:
Velocypack was invented with these future extending of datatypes in mind.

However, before adding more datatypes the following questions need to be answered first:

howto spread the implementation of the extension over all parser implementations

howto best make drivers understand it

howto manipulate (compare, etc.) them in AQL

howto index them

howto represent them in the web-UI which is talking json to the server

howto save them from the webui without destroying them in the original document

Once we have good answers to these questions, i.e. date types or higher precision float types may be introduced.


答:
try this</p>

```<code>select
exe.costumer_id,
exe.produkt_id,
exe.product_name,
exe.costumer_id || '-' || exe.num
from
(
    select
    costumer_id,
    produkt_id,
    product_name,
    row_number() over (partition by costumer_id order by costumer_id) as num
    from _table
) exe
</code>```

Title: SQL adding a field that combines the id and an increment number based on customer

Body:
try this

select
exe.costumer_id,
exe.produkt_id,
exe.product_name,
exe.costumer_id || '-' || exe.num
from
(
    select
    costumer_id,
    produkt_id,
    product_name,
    row_number() over (partition by costumer_id order by costumer_id) as num
    from _table
) exe


问:
Create Hive ORC table from ORC files of other server
we have 2 clusters one Map R and another our own. We want created new setup in our own hardware using the Map R data.

I have copied all the orc files from the Map R cluster and followed the same folder structure

Created a orc formatted table with location of #1

then executed this command "MSCK REPAIR TABLE <>"

above steps passed without error, but when i query the partitions then job fails with  below error

```<code>java.lang.IllegalArgumentException: Buffer size too small. size = 262144 needed = 4958903
    at org.apache.hadoop.hive.ql.io.orc.InStream$CompressedStream.readHeader(InStream.java:193)
    at org.apache.hadoop.hive.ql.io.orc.InStream$CompressedStream.read(InStream.java:238)
</code>```

Can some one tell me can we create HIVE ORC partition tables directly from the orc files?

My storage is Azure data lake.

答:
According to your description, based on my understanding, I think you want to copy all orc files from a cluster to another and load these orc files as a hive table.

For doing it, please just try to follow the command below to create external table for loading orcfile data.

```<code>CREATE EXTERNAL TABLE IF NOT EXSISTS <table name> (<column_name column_type>, ...)
    ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
    STORED AS ORC
    LOCATION '<orcfile path>'
</code>```

If not aware of the columns list of an orc file, you can refer to the Hive manual ORC File Dump Utility to print the ORC file metadata in JSON format via hive --orcfiledump -j -p <location-of-orc-file-or-directory>.

Body:
we have 2 clusters one Map R and another our own. We want created new setup in our own hardware using the Map R data.

I have copied all the orc files from the Map R cluster and followed the same folder structure

Created a orc formatted table with location of #1

then executed this command "MSCK REPAIR TABLE <>"

above steps passed without error, but when i query the partitions then job fails with  below error

java.lang.IllegalArgumentException: Buffer size too small. size = 262144 needed = 4958903
    at org.apache.hadoop.hive.ql.io.orc.InStream$CompressedStream.readHeader(InStream.java:193)
    at org.apache.hadoop.hive.ql.io.orc.InStream$CompressedStream.read(InStream.java:238)

Can some one tell me can we create HIVE ORC partition tables directly from the orc files?

My storage is Azure data lake.

Body:
According to your description, based on my understanding, I think you want to copy all orc files from a cluster to another and load these orc files as a hive table.

For doing it, please just try to follow the command below to create external table for loading orcfile data.

CREATE EXTERNAL TABLE IF NOT EXSISTS <table name> (<column_name column_type>, ...)
    ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
    STORED AS ORC
    LOCATION '<orcfile path>'

If not aware of the columns list of an orc file, you can refer to the Hive manual ORC File Dump Utility to print the ORC file metadata in JSON format via hive --orcfiledump -j -p <location-of-orc-file-or-directory>.


问:
Change label value in UICollectionView without reload data?
I'm using swift 2.2 and i have a collectionview inside cell ia hve a label.I want to change a label text value in UICollection view on a button click without using reloading whole uiCollection view.
I can't use collectionView.reloadData() for my scenario. I want a do it without using it. Just to update one label in a particular item in collectionview.
Any help??</p>

答:
If you pass the IndexPath you can access the cell, then from it you can change the label using this syntax</p>

```<code>let cell = self.collectionView.cellForItem(at: IndexPath) as? yourCollectionViewCellName
cell.label.text = "new text"
</code>```

Body:
If you pass the IndexPath you can access the cell, then from it you can change the label using this syntax

let cell = self.collectionView.cellForItem(at: IndexPath) as? yourCollectionViewCellName
cell.label.text = "new text"


问:
Reassign / Update Variables
I've tried searching all over the web but could only find how to reassign cell values.

A little background for my code:

The input sheet contains data in columns A through U, but columns R and S are purposefully empty. I need to set & sort the Data Range from columns A through Q ONLY, and the number of rows may change every time I run the code (so the row index needs to be dynamic). When I run my code, the variable does not update, and I don't get any errors. Why is the code not updating my variable for input data. Any help would be greatly appreciated!

Thanks!

```<code>function SortUpdate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);
  for(var i = 9; i<=(15);i++){
     inputData.sort({column: i, ascending: false});
  }
}
</code>```

答:
Instead of using the sheet.getDataRange() and sheet.getNumRows(), you can use the sheet.getLastRow() method, who will return the value of the last row use on the sheet. More about the getLastRow method : https://developers.google.com/apps-script/reference/spreadsheet/sheet#getLastRow()

For the sort method part, you can use the code write by Cooper which is working, or send us a exemple of what kind of sort method you want.

Title: Reassign / Update Variables

Body:
I've tried searching all over the web but could only find how to reassign cell values.

A little background for my code:

The input sheet contains data in columns A through U, but columns R and S are purposefully empty. I need to set & sort the Data Range from columns A through Q ONLY, and the number of rows may change every time I run the code (so the row index needs to be dynamic). When I run my code, the variable does not update, and I don't get any errors. Why is the code not updating my variable for input data. Any help would be greatly appreciated!

Thanks!

function SortUpdate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);
  for(var i = 9; i<=(15);i++){
     inputData.sort({column: i, ascending: false});
  }
}


问:
Python - Transform List to List of Lists with each entry containing unique combinations
I have a list of lists as follows:

```<code>mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]
</code>```

What I would like to do is iterate through mylist and produce a new list like this:

```<code>result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]
</code>```

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

答:
```<code>base_list = [['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
list_len = len(base_list)
list1 = []
list2 = []
new_list = []
if list_len%2 == 0:
    list1 = base_list[:list_len/2]
    list2 = base_list[list_len/2:]
    for i, j in zip(list1,list2):
        new_list.append(i)
        new_list.append(j)
    print "new list=",new_list
else:
    list1 = base_list[:list_len-1/2]
    list2 = base_list[list_len-1/2:]
    list3 = base_list[-1:]
    for i, j in zip(list1,list2):
        new_list.append(i)
        new_list.append(j)
    new_list.append(list3)
    print "new list=",new_list
</code>```

out:

```<code>new list= [['a', 'b'], ['c', 'd'], ['a', 'c'], ['d', 'e'], ['b', 'c'], ['e', 'c']]
</code>```

Body:
I have a list of lists as follows:

mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]

What I would like to do is iterate through mylist and produce a new list like this:

result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

Body:
base_list = [['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
list_len = len(base_list)
list1 = []
list2 = []
new_list = []
if list_len%2 == 0:
    list1 = base_list[:list_len/2]
    list2 = base_list[list_len/2:]
    for i, j in zip(list1,list2):
        new_list.append(i)
        new_list.append(j)
    print "new list=",new_list
else:
    list1 = base_list[:list_len-1/2]
    list2 = base_list[list_len-1/2:]
    list3 = base_list[-1:]
    for i, j in zip(list1,list2):
        new_list.append(i)
        new_list.append(j)
    new_list.append(list3)
    print "new list=",new_list

out:

new list= [['a', 'b'], ['c', 'd'], ['a', 'c'], ['d', 'e'], ['b', 'c'], ['e', 'c']]


问:
Defining new post image (not post thumbnail) sizes in WordPress
I'm a total newbie to WordPress development and as far as it goes now, I understand that WP can create responsive images for me with a built in plugin since version 4.4.

In my project, I have two types of images. By types I mean their width.
First one, the widest one is 633px (which is double the size for Retina displays), and I set it as a "Large" in settings -> media -> Large size. So, whenever I upload this one, it works just fine, cause the medium size is also preset.

The problem occurs with the second type of images. They are much narrower, and I need a preset of width for them, which I have to implement in functions.php. The width for "Large" is 612px, and for "Medium" 306px.

What kind of filter should I add in function.php to implement those new sizes in my admin Dashboard, so WP will spit out those photos in appropriate size?

Thanks ahead everyone!

PS - solution is found!

```<code>    //Adding new img sizes
add_image_size( 'Portfolio-medium-wide', 633 );
add_image_size( 'Portfolio-large-wide', 1266 );
add_image_size( 'Portfolio-medium', 306 );
add_image_size( 'Portfolio-large', 612 );
add_image_size( 'Blog-medium', 469 );
add_image_size( 'Blog-large', 938 );

add_filter( 'image_size_names_choose','my_image_sizes' );

function my_image_sizes( $sizes ) {
    return array_merge ( $sizes, array(
        'Portfolio-medium-wide' => __('Portfolio Medium wide'),
        'Portfolio-large-wide' => __('Portfolio Large wide'),
        'Portfolio-medium' => __('Portfolio Medium'),
        'Portfolio-large' => __('Portfolio Large'),
        'Blog-medium' => __('Blog Medium'),
        'Blog-large' => __('Blog large'),
    ));
}
</code>```

答:
Please use add_image_size function, please find the example below :

```<code>   // defining size in functions.php
    add_image_size( 'your_image_size', 370, 223,true);

   //using the size in other pages
   the_post_thumbnail('your_image_size');
</code>```

Hope it helps

Body:
I'm a total newbie to WordPress development and as far as it goes now, I understand that WP can create responsive images for me with a built in plugin since version 4.4.

In my project, I have two types of images. By types I mean their width.
First one, the widest one is 633px (which is double the size for Retina displays), and I set it as a "Large" in settings -> media -> Large size. So, whenever I upload this one, it works just fine, cause the medium size is also preset.

The problem occurs with the second type of images. They are much narrower, and I need a preset of width for them, which I have to implement in functions.php. The width for "Large" is 612px, and for "Medium" 306px.

What kind of filter should I add in function.php to implement those new sizes in my admin Dashboard, so WP will spit out those photos in appropriate size?

Thanks ahead everyone!

PS - solution is found!

    //Adding new img sizes
add_image_size( 'Portfolio-medium-wide', 633 );
add_image_size( 'Portfolio-large-wide', 1266 );
add_image_size( 'Portfolio-medium', 306 );
add_image_size( 'Portfolio-large', 612 );
add_image_size( 'Blog-medium', 469 );
add_image_size( 'Blog-large', 938 );

add_filter( 'image_size_names_choose','my_image_sizes' );

function my_image_sizes( $sizes ) {
    return array_merge ( $sizes, array(
        'Portfolio-medium-wide' => __('Portfolio Medium wide'),
        'Portfolio-large-wide' => __('Portfolio Large wide'),
        'Portfolio-medium' => __('Portfolio Medium'),
        'Portfolio-large' => __('Portfolio Large'),
        'Blog-medium' => __('Blog Medium'),
        'Blog-large' => __('Blog large'),
    ));
}

Body:
Please use add_image_size function, please find the example below :

   // defining size in functions.php
    add_image_size( 'your_image_size', 370, 223,true);

   //using the size in other pages
   the_post_thumbnail('your_image_size');

Hope it helps


问:
Unresolved constraint in bundlecom.jira.test.MyProject requirement osgi.wiring.package
I have a problem. I search on the internet and countn't really find right answear. It started in my project for JIRA plugin. Then I make new project and add 1 by 1 dependecys to check where the problem is. I get the following error.

```<code>>  ___ FAILED PLUGIN REPORT _____________________
>
>  1 plugin failed to load during JIRA startup.
>
>
>        com.jira.test.MyProject' - 'MyProject'  failed to load.
>                Cannot start plugin: com.jira.test.MyProject
>                        Unresolved constraint in bundlecom.jira.test.MyProject [166]: Unable to resolve 166.0: missing
>
> requirement [166.0] osgi.wiring.package; (osgi.wiring.package=bsh)
</code>```

My POM.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jira.test</groupId>
    <artifactId>MyProject</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <organization>
        <name>Example Company</name>
        <url>http://www.example.com/</url>
    </organization>

    <name>MyProject</name>
    <description>This is the com.jira.test:MyProject plugin for Atlassian JIRA.</description>
    <packaging>atlassian-plugin</packaging>

    <dependencies>
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-api</artifactId>
            <version>${jira.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Add dependency on jira-core if you want access to JIRA implementation classes as well as the sanctioned API. -->
        <!-- This is not normally recommended, but may be required eg when migrating a plugin originally developed against JIRA 4.x -->
        <!--
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-core</artifactId>
            <version>${jira.version}</version>
            <scope>provided</scope>
        </dependency>
        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
            <scope>provided</scope>
        </dependency>

        <!-- WIRED TEST RUNNER DEPENDENCIES -->
        <dependency>
            <groupId>com.atlassian.plugins</groupId>
            <artifactId>atlassian-plugins-osgi-testrunner</artifactId>
            <version>${plugin.testrunner.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.2-atlassian-1</version>
        </dependency>

        <!-- Uncomment to use TestKit in your project. Details at https://bitbucket.org/atlassian/jira-testkit -->
        <!-- You can read more about TestKit at https://developer.atlassian.com/display/JIRADEV/Plugin+Tutorial+-+Smarter+integration+testing+with+TestKit -->
        <!--
        <dependency>
            <groupId>com.atlassian.jira.tests</groupId>
            <artifactId>jira-testkit-client</artifactId>
            <version>${testkit.version}</version>
            <scope>test</scope>
        </dependency>
        -->
        <dependency>
            <groupId>com.atlassian.plugin</groupId>
            <artifactId>atlassian-spring-scanner-annotation</artifactId>
            <version>${atlassian.spring.scanner.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.context</artifactId>
            <version>2.5.6.SEC01</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.atlassian.maven.plugins</groupId>
                <artifactId>maven-jira-plugin</artifactId>
                <version>${amps.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <productVersion>${jira.version}</productVersion>
                    <productDataVersion>${jira.version}</productDataVersion>
                    <!-- Uncomment to install TestKit backdoor in JIRA. -->
                    <!--
                    <pluginArtifacts>
                        <pluginArtifact>
                            <groupId>com.atlassian.jira.tests</groupId>
                            <artifactId>jira-testkit-plugin</artifactId>
                            <version>${testkit.version}</version>
                        </pluginArtifact>
                    </pluginArtifacts>
                    -->
                    <enableQuickReload>true</enableQuickReload>
                    <enableFastdev>false</enableFastdev>

                    <!-- See here for an explanation of default instructions: -->
                    <!-- https://developer.atlassian.com/docs/advanced-topics/configuration-of-instructions-in-atlassian-plugins -->
                    <instructions>
                        <Atlassian-Plugin-Key>${atlassian.plugin.key}</Atlassian-Plugin-Key>

                        <!-- Add package to export here -->
                        <Export-Package>
                            com.jira.test.api,
                        </Export-Package>

                        <!-- Add package import here -->
                        <Import-Package>
                            <!--org.springframework.osgi.*;resolution:="optional" org.eclipse.gemini.blueprint.*;resolution:="optional", *-->
                            org.springframework.osgi.*;resolution:=*, org.eclipse.gemini.blueprint.*;resolution:=*, *
                        </Import-Package>

                        <!-- Ensure plugin is spring powered -->
                        <Spring-Context>*</Spring-Context>
                    </instructions>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.atlassian.plugin</groupId>
                <artifactId>atlassian-spring-scanner-maven-plugin</artifactId>
                <version>${atlassian.spring.scanner.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>atlassian-spring-scanner</goal>
                        </goals>
                        <!-- process-classes seems to be skipped if you are using scala
                             so perhaps use prepare-package -->
                        <phase>process-classes</phase>
                    </execution>
                </executions>
                <configuration>
                    <!-- Enable this to get build-time logging of annotations atlassian-spring-scanner-maven-plugin has noticed -->
                    <verbose>false</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jira.version>7.2.2</jira.version>
        <amps.version>6.2.11</amps.version>
        <plugin.testrunner.version>1.2.3</plugin.testrunner.version>
        <atlassian.spring.scanner.version>1.2.13</atlassian.spring.scanner.version>
        <!-- This key is used to keep the consistency between the key in atlassian-plugin.xml and the key to generate bundle. -->
        <atlassian.plugin.key>${project.groupId}.${project.artifactId}</atlassian.plugin.key>
        <!-- TestKit version 6.x for JIRA 6.x -->
        <testkit.version>6.3.11</testkit.version>
    </properties>

</project>
</code>```

my java :

```<code>package com.jira.test;

import com.atlassian.plugin.spring.scanner.annotation.export.ExportAsService;
import org.springframework.stereotype.Component;

import javax.inject.Named;

@ExportAsService
@Component
@Named("IssueCreatedResolvedListener")
public class IssueCreatedResolvedListener {

}
</code>```

Ass soon as I add @Component and its dependency (org.springframework), faild to load plugin. Can anyone tell me how could I fix this problem ?

答:
Well find answer by myself finally. Looked into dependency documentation and I change version and add scope provided.

In case anyone else will have the same issue as me, here is what you need to do: change dependency with this one. It fixed problem for me.

```<code> <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.1.6.RELEASE</version>
     <scope>provided</scope>
  </dependency>
</code>```

Body:
I have a problem. I search on the internet and countn't really find right answear. It started in my project for JIRA plugin. Then I make new project and add 1 by 1 dependecys to check where the problem is. I get the following error.

>  ___ FAILED PLUGIN REPORT _____________________
>
>  1 plugin failed to load during JIRA startup.
>
>
>        com.jira.test.MyProject' - 'MyProject'  failed to load.
>                Cannot start plugin: com.jira.test.MyProject
>                        Unresolved constraint in bundlecom.jira.test.MyProject [166]: Unable to resolve 166.0: missing
>
> requirement [166.0] osgi.wiring.package; (osgi.wiring.package=bsh)

My POM.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jira.test</groupId>
    <artifactId>MyProject</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <organization>
        <name>Example Company</name>
        <url>http://www.example.com/</url>
    </organization>

    <name>MyProject</name>
    <description>This is the com.jira.test:MyProject plugin for Atlassian JIRA.</description>
    <packaging>atlassian-plugin</packaging>

    <dependencies>
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-api</artifactId>
            <version>${jira.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.atlassian.plugins</groupId>
            <artifactId>atlassian-plugins-osgi-testrunner</artifactId>
            <version>${plugin.testrunner.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.1.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.2-atlassian-1</version>
        </dependency>

        <dependency>
            <groupId>com.atlassian.plugin</groupId>
            <artifactId>atlassian-spring-scanner-annotation</artifactId>
            <version>${atlassian.spring.scanner.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.context</artifactId>
            <version>2.5.6.SEC01</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.atlassian.maven.plugins</groupId>
                <artifactId>maven-jira-plugin</artifactId>
                <version>${amps.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <productVersion>${jira.version}</productVersion>
                    <productDataVersion>${jira.version}</productDataVersion>

                    <enableQuickReload>true</enableQuickReload>
                    <enableFastdev>false</enableFastdev>

                    <instructions>
                        <Atlassian-Plugin-Key>${atlassian.plugin.key}</Atlassian-Plugin-Key>

                        <Export-Package>
                            com.jira.test.api,
                        </Export-Package>

                        <Import-Package>

                            org.springframework.osgi.*;resolution:=*, org.eclipse.gemini.blueprint.*;resolution:=*, *
                        </Import-Package>

                        <Spring-Context>*</Spring-Context>
                    </instructions>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.atlassian.plugin</groupId>
                <artifactId>atlassian-spring-scanner-maven-plugin</artifactId>
                <version>${atlassian.spring.scanner.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>atlassian-spring-scanner</goal>
                        </goals>

                        <phase>process-classes</phase>
                    </execution>
                </executions>
                <configuration>

                    <verbose>false</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jira.version>7.2.2</jira.version>
        <amps.version>6.2.11</amps.version>
        <plugin.testrunner.version>1.2.3</plugin.testrunner.version>
        <atlassian.spring.scanner.version>1.2.13</atlassian.spring.scanner.version>

        <atlassian.plugin.key>${project.groupId}.${project.artifactId}</atlassian.plugin.key>

        <testkit.version>6.3.11</testkit.version>
    </properties>

</project>

my java :

package com.jira.test;

import com.atlassian.plugin.spring.scanner.annotation.export.ExportAsService;
import org.springframework.stereotype.Component;

import javax.inject.Named;

@ExportAsService
@Component
@Named("IssueCreatedResolvedListener")
public class IssueCreatedResolvedListener {

}

Ass soon as I add @Component and its dependency (org.springframework), faild to load plugin. Can anyone tell me how could I fix this problem ?

Body:
Well find answer by myself finally. Looked into dependency documentation and I change version and add scope provided.

In case anyone else will have the same issue as me, here is what you need to do: change dependency with this one. It fixed problem for me.

 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.1.6.RELEASE</version>
     <scope>provided</scope>
  </dependency>

ContentLicense: CC BY-SA 4.0


问:
Two characters in a for loop not comparing properly
I narrowed down my problem to if($reqFnameArr[$i] == $fnameArr[$i]) I don't know why it's not comparing properly those two variables contain single characters from the split. Because when I try to output $finUsername is stays empty.

```<code>//fetch firstname in Database
$fname = User::select('first_name')->where('username', $request->username)
                  ->where('first_name', '!=', $request->first_name)->get();
$fnameArr = str_split($fname);
//request firstname
$reqFname = $request->first_name;
$reqFnameArr = str_split($reqFname);
//final username
$finUsername = '';
for($i = 0; $i < strlen($reqFname); $i++) {
  if($reqFnameArr[$i] == $fnameArr[$i]) {
  $finUsername .= $reqFnameArr[$i];
  }
}
</code>```

EDIT
I am saving finUsername to a database after comparing the arrays

```<code>  $user = User::create($request->all());

              $user->update(['role_id' => $request->role]);
              $user->save();
              $user->update(['username' => $finUsername]);
              $user->save();

              $roleName = $user->role()->name;

              return response()->json(['user' => $user, 'roleName' => $roleName,'manager_exists'=>'0']);
</code>```

答:
I suggest you should use strict comparison operator === instead of == when comparing two string.

```<code>if($reqFnameArr[$i] === $fnameArr[$i]) {
</code>```

Link: http://php.net/manual/en/language.operators.comparison.php

Body:
I narrowed down my problem to if($reqFnameArr[$i] == $fnameArr[$i]) I don't know why it's not comparing properly those two variables contain single characters from the split. Because when I try to output $finUsername is stays empty.

//fetch firstname in Database
$fname = User::select('first_name')->where('username', $request->username)
                  ->where('first_name', '!=', $request->first_name)->get();
$fnameArr = str_split($fname);
//request firstname
$reqFname = $request->first_name;
$reqFnameArr = str_split($reqFname);
//final username
$finUsername = '';
for($i = 0; $i < strlen($reqFname); $i++) {
  if($reqFnameArr[$i] == $fnameArr[$i]) {
  $finUsername .= $reqFnameArr[$i];
  }
}

EDIT
I am saving finUsername to a database after comparing the arrays

  $user = User::create($request->all());

              $user->update(['role_id' => $request->role]);
              $user->save();
              $user->update(['username' => $finUsername]);
              $user->save();

              $roleName = $user->role()->name;

              return response()->json(['user' => $user, 'roleName' => $roleName,'manager_exists'=>'0']);

Body:
I suggest you should use strict comparison operator === instead of == when comparing two string.

if($reqFnameArr[$i] === $fnameArr[$i]) {

Link: http://php.net/manual/en/language.operators.comparison.php


问:
Get facebook fans count using API 2.8
How to get Facebook fans count using http request in API 2.8

-- I test these requests but not working

This return an array but no Fans Count

```<code>https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&edges=fan_count
</code>```

Return

```<code>{
  "category": "Entertainment",
  "link": {APP LINK},
  "name": {NAME},
  "id": {ID}
}
</code>```

-- This throw an error array

```<code>https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&fields=likes
</code>```

Return

```<code>{
  "error": {
     "message": "(#100) Tried accessing nonexisting field (likes) on node type (Application)",
     "type": "OAuthException",
     "code": 100,
     "fbtrace_id": "FlkGoTOJ403"
  }
}
</code>```

答:
This is the correct one:

```<code>https://graph.facebook.com/v2.8/{PAGE_ID}?access_token={ACCESS_TOKEN}&fields=fan_count
</code>```

Not sure why you would use an App for this, Fans are for Pages.

Title: Get facebook fans count using API 2.8

Body:
How to get Facebook fans count using http request in API 2.8

-- I test these requests but not working

This return an array but no Fans Count

https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&edges=fan_count

Return

{
  "category": "Entertainment",
  "link": {APP LINK},
  "name": {NAME},
  "id": {ID}
}

-- This throw an error array

https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&fields=likes

Return

{
  "error": {
     "message": "(#100) Tried accessing nonexisting field (likes) on node type (Application)",
     "type": "OAuthException",
     "code": 100,
     "fbtrace_id": "FlkGoTOJ403"
  }
}

Body:
This is the correct one:

https://graph.facebook.com/v2.8/{PAGE_ID}?access_token={ACCESS_TOKEN}&fields=fan_count

Not sure why you would use an App for this, Fans are for Pages.


问:
Want to route one component to another component
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>
      </div>
    );
  }
}

export default App;
</code>```

code for index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

Respective i have also component class for Login.js and Register.js

答:
```<code>render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Welcome to React</h2>
    </div>
    <button href='#/login' onClick={this.gotoLogin} class="Button ">Login</button>
    <button href='#/register' onClick ={this.gotoRegister} class="Button">Register</button>
  </div>
);
</code>```

<p>}</p>

Body:
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (

Welcome to React

        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>

    );
  }
}

export default App;

code for index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Respective i have also component class for Login.js and Register.js

Body:
render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Welcome to React</h2>
    </div>
    <button href='#/login' onClick={this.gotoLogin} class="Button ">Login</button>
    <button href='#/register' onClick ={this.gotoRegister} class="Button">Register</button>
  </div>
);

}


问:
build.sbt Scoping does not work
Hello I'm trying to set a value depending on the running task in my build.sbt:

```<code>ngScalaModule in fastOptJS := "./plugintest2-fastopt.js"
ngScalaModule in fullOptJS := "./plugintest2-opt.js"
</code>```

Now when i run the task fastOptJS or fullOptJS the value ngScalaModule is not used when I try this without scoping:

```<code>ngScalaModule in fastOptJS := "./plugintest2-fastopt.js"
</code>```

The value is used.
My question is, weather I have done something totally wrong or does the plugin which provieds ngScalaModule has to explicit implement the scoping.

The value ngScalaModule is provided by an other sbt plugin as the two tasks, just in case it makes a difference.

Thanks

答:
In the definition of Angulate2Plugin, we can indeed see that the setting ngScalaModule is only ever read scoped only by the project (and not the configuration nor the task, which are the other two scope axes in sbt).

Therefore, the setting that you define ngScalaModule in fastOptJS is not used by anything. angulate2 will only read ngScalaModule (unscoped).

That means that angulate2 would have to be changed for you to be able to specify a different ngScalaModule in fastOptJS versus fullOptJS. Note that angulate2 itself depends on SJSXPlugin (by the same author) for its sjsxSnippets settings, which is also only scoped per project. So this might have some deep consequences.

Title: build.sbt Scoping does not work

Body:
Hello I'm trying to set a value depending on the running task in my build.sbt:

ngScalaModule in fastOptJS := "./plugintest2-fastopt.js"
ngScalaModule in fullOptJS := "./plugintest2-opt.js"

Now when i run the task fastOptJS or fullOptJS the value ngScalaModule is not used when I try this without scoping:

ngScalaModule in fastOptJS := "./plugintest2-fastopt.js"

The value is used.
My question is, weather I have done something totally wrong or does the plugin which provieds ngScalaModule has to explicit implement the scoping.

The value ngScalaModule is provided by an other sbt plugin as the two tasks, just in case it makes a difference.

Thanks


问:
error as "No such table" while inserting data in to table
Getting Error as NO such table,Table is not creating,Please help me with your answers.I think error is database.java file.So I uploaded it.In inserting values I am not changing fields of phone number into long...As I taken it as TEXT datatype in Database file.
           '

```<code>               public class MyDatabase extends SQLiteOpenHelper {

          Context c;

         // Database Name
           public static final String DATABASE_NAME = "BIRLA_ACCOUNTS";
        //Table Name
        public static final String TABLE_NAME = "MASTERACCOUNTS";
        //  Table Columns names
        public static final String CODE = "CODE";
        public static final String NAME = "NAME";
        public static final String TYPE = "TYPE";
        public static final String ADD1 = "ADD1";
        public static final String ADD2 = "ADD2";
        public static final String CITY = "CITY";
        public static final String COUNTRY = "COUNTRY";
        public static final String PHONENO = "PHONENO";
        public static final String CONTACTPERSON = "CONTACTPERSON";
         public static final String EMAILID = "EMAILID";
        public static final String FAX = "FAX";
         public static final String TNO = "TNO";
        public static final String CSTNO = "CSTNO";
        public static final String GSTNO = "GSTNO";
        public static final String SERVICENO = "SERVICENO";

        public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);
        c = context;

       }

         @Override
          public void onCreate(SQLiteDatabase db) {
          try {

            db.execSQL("CREATE TABLE "+TABLE_NAME+"("+CODE+" INTEGER
                     AUTOINCREMENT,"+NAME+" TEXT PRIMARY KEY ,"+TYPE+" TEXT,
                       "+ADD1+" TEXT,"+ADD2+" TEXT,"+CITY+" TEXT,"+COUNTRY+
                          " TEXT,"+PHONENO+" TEXT,"
                    +CONTACTPERSON+" TEXT,"+EMAILID +" VARCHAR(50),"+FAX+"
                        REAL,"+TNO+" REAL,"+CSTNO+" REAL,"+GSTNO+" REAL,"
            +SERVICENO +" REAL)");
              Toast.makeText(c, "Table Created", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                  Log.e("AccountsMaster creation", "" + e);
                       }

                  }

               @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion,
                   int  newVersion) {
            // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
             // Creating tables again
                 onCreate(db);
              }
</code>```

`

答:
Rectify Your Query . Aware from Blank Space and Single-Double Quote .

```<code> "CREATE TABLE " + TABLE_NAME + " ("
                    + CODE + " INTEGER AUTOINCREMENT ,"
                    + NAME + " TEXT PRIMARY KEY ,"
                    + TYPE + " TEXT ,"
                    + ADD1 + " TEXT ,"
                    + ADD2 + " TEXT ,"
                    + CITY + " TEXT ,"
                    + COUNTRY + " TEXT ,"
                    + PHONENO + " TEXT ,"
                    + CONTACTPERSON + " TEXT ,"
                    + EMAILID + " VARCHAR(50) ,"
                    + FAX + " REAL ,"
                    + TNO + " REAL ,"
                    + CSTNO + " REAL ,"
                    + GSTNO + " REAL ,"
                    + SERVICENO + " REAL" + ")";
</code>```

FYI

Use INTEGER PRIMARY KEY AUTOINCREMENT in CODE Field

```<code> + CODE + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
 + NAME + " TEXT ,"
</code>```

Body:
Getting Error as NO such table,Table is not creating,Please help me with your answers.I think error is database.java file.So I uploaded it.In inserting values I am not changing fields of phone number into long...As I taken it as TEXT datatype in Database file.
           '

               public class MyDatabase extends SQLiteOpenHelper {

          Context c;

         // Database Name
           public static final String DATABASE_NAME = "BIRLA_ACCOUNTS";
        //Table Name
        public static final String TABLE_NAME = "MASTERACCOUNTS";
        //  Table Columns names
        public static final String CODE = "CODE";
        public static final String NAME = "NAME";
        public static final String TYPE = "TYPE";
        public static final String ADD1 = "ADD1";
        public static final String ADD2 = "ADD2";
        public static final String CITY = "CITY";
        public static final String COUNTRY = "COUNTRY";
        public static final String PHONENO = "PHONENO";
        public static final String CONTACTPERSON = "CONTACTPERSON";
         public static final String EMAILID = "EMAILID";
        public static final String FAX = "FAX";
         public static final String TNO = "TNO";
        public static final String CSTNO = "CSTNO";
        public static final String GSTNO = "GSTNO";
        public static final String SERVICENO = "SERVICENO";

        public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);
        c = context;

       }

         @Override
          public void onCreate(SQLiteDatabase db) {
          try {

            db.execSQL("CREATE TABLE "+TABLE_NAME+"("+CODE+" INTEGER
                     AUTOINCREMENT,"+NAME+" TEXT PRIMARY KEY ,"+TYPE+" TEXT,
                       "+ADD1+" TEXT,"+ADD2+" TEXT,"+CITY+" TEXT,"+COUNTRY+
                          " TEXT,"+PHONENO+" TEXT,"
                    +CONTACTPERSON+" TEXT,"+EMAILID +" VARCHAR(50),"+FAX+"
                        REAL,"+TNO+" REAL,"+CSTNO+" REAL,"+GSTNO+" REAL,"
            +SERVICENO +" REAL)");
              Toast.makeText(c, "Table Created", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                  Log.e("AccountsMaster creation", "" + e);
                       }

                  }

               @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion,
                   int  newVersion) {
            // Drop older table if existed
                db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
             // Creating tables again
                 onCreate(db);
              }

`

Body:
Rectify Your Query . Aware from Blank Space and Single-Double Quote .

 "CREATE TABLE " + TABLE_NAME + " ("
                    + CODE + " INTEGER AUTOINCREMENT ,"
                    + NAME + " TEXT PRIMARY KEY ,"
                    + TYPE + " TEXT ,"
                    + ADD1 + " TEXT ,"
                    + ADD2 + " TEXT ,"
                    + CITY + " TEXT ,"
                    + COUNTRY + " TEXT ,"
                    + PHONENO + " TEXT ,"
                    + CONTACTPERSON + " TEXT ,"
                    + EMAILID + " VARCHAR(50) ,"
                    + FAX + " REAL ,"
                    + TNO + " REAL ,"
                    + CSTNO + " REAL ,"
                    + GSTNO + " REAL ,"
                    + SERVICENO + " REAL" + ")";

FYI

Use INTEGER PRIMARY KEY AUTOINCREMENT in CODE Field

 + CODE + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
 + NAME + " TEXT ,"


问:
How do I install gitlab on Ubuntu 16.10?
I would really like to give gitlab a try but I keep getting errors. I've followed the instructions on the site but I keep getting errors. Anyone have any experience with this?</p>

答:
I tried to use this documentation:

Gitlab installation 16.04

just don't use the xenial path, use the piped script. I had problems after installing it. This might solve your issues:

```<code>sudo gem install underscore-rails
sudo gem install gitlab
</code>```

After that I got permissions problems, which were fixed by:

```<code>chmod 777 /usr/share/gitlab/config/secrets.yml
sudo apt install gitlab
</code>```

With that gitlab got sucessfully installed on Ubuntu 16.10.

Body:
I tried to use this documentation:

Gitlab installation 16.04

just don't use the xenial path, use the piped script. I had problems after installing it. This might solve your issues:

sudo gem install underscore-rails
sudo gem install gitlab

After that I got permissions problems, which were fixed by:

chmod 777 /usr/share/gitlab/config/secrets.yml
sudo apt install gitlab

With that gitlab got sucessfully installed on Ubuntu 16.10.


问:
MongoDB - $sum in multiple collections
I have many collections. The view of these collections is the same as the JSON. What I want to do is to collect the collections according to their id and create a collection. How can I do it?

A.json

```<code>{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 515835.0
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 6621696.0
}
</code>```

B.json

```<code>{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 2118.0
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 1190.0
}
{
    "_id" : ObjectId("423232d2d506c1cab1c1232c"),
    "value" : 10.0
}
</code>```

Collect in A collection, id: 1, collection B id: 1 if it matches.

A in the collection, id: 2, if you are not in any collection, you are only showing that value.

In the last collection I have collected, I want to make a collection of objects and id in pairs.

Result.json

```<code>{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 517953.0 // A.value + B.value
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 6633596.0 // A.value + B.value
}
{
    "_id" : ObjectId("423232d2d506c1cab1c1232c"),
    "value" : 10.0 // B.value (A.value : null)
}
</code>```

i want this for multiple collections.

答:
For 1-0/1 relation given in the example you can use $lookup as following:

```<code>db.B.aggregate([
    {$lookup: {
        from: "A",
        localField: "_id",
        foreignField: "_id",
        as: "a"
    }},
    {$unwind: {path: "$a", preserveNullAndEmptyArrays: true}},
    {$project: {
        value: {$add: ["$value", {$ifNull: ["$a.value", 0 ]}]}
    }}
]);
</code>```

It does ignore any documents in A, which have no corresponding documents in B, i.e. result have the same number of documents as in collection B.

Title: MongoDB - $sum in multiple collections

Body:
I have many collections. The view of these collections is the same as the JSON. What I want to do is to collect the collections according to their id and create a collection. How can I do it?

A.json

{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 515835.0
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 6621696.0
}

B.json

{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 2118.0
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 1190.0
}
{
    "_id" : ObjectId("423232d2d506c1cab1c1232c"),
    "value" : 10.0
}

Collect in A collection, id: 1, collection B id: 1 if it matches.

A in the collection, id: 2, if you are not in any collection, you are only showing that value.

In the last collection I have collected, I want to make a collection of objects and id in pairs.

Result.json

{
    "_id" : ObjectId("58455d2d506c1cab1c82152c"),
    "value" : 517953.0 // A.value + B.value
}
{
    "_id" : ObjectId("58455d2d506c1cab1c82153c"),
    "value" : 6633596.0 // A.value + B.value
}
{
    "_id" : ObjectId("423232d2d506c1cab1c1232c"),
    "value" : 10.0 // B.value (A.value : null)
}

i want this for multiple collections.

Body:
For 1-0/1 relation given in the example you can use $lookup as following:

db.B.aggregate([
    {$lookup: {
        from: "A",
        localField: "_id",
        foreignField: "_id",
        as: "a"
    }},
    {$unwind: {path: "$a", preserveNullAndEmptyArrays: true}},
    {$project: {
        value: {$add: ["$value", {$ifNull: ["$a.value", 0 ]}]}
    }}
]);

It does ignore any documents in A, which have no corresponding documents in B, i.e. result have the same number of documents as in collection B.


问:
how to pass parameter on redirect in yii
I am using Yii framework for my project;

I am  redirecting page after success of insertion in  database to another controller using

$this->redirect($this->createUrl('controller/action'));

During the redirection is it possible to pass any parameters just like in render,

$this->render('selectRefiner', array('param' => $data)

答:
To redirect into same action with the all parameters that already have this works for me.</p>

```<code>$this->redirect($_PHP['SELF']);
</code>```

Body:
To redirect into same action with the all parameters that already have this works for me.

$this->redirect($_PHP['SELF']);


问:
Divide a column into 10 equal parts in R
I am trying to divide a dataframe col into 10 equal no of groups.

I have tried like this way:

Code:

```<code>data$test<-as.numeric(cut2(data$age_201512, g=10))
res_count_table_10<-aggregate(data$final_res~data$test,data,sum)
</code>```

Output is :

I have tried to count the test variable

```<code>table(data$test)
</code>```

<img src="https://i.stack.imgur.com/9bigr.png

How can divide into equal 10 groups??
I have tried the same with Excel VBA using (total no.of rows/10) as number of rows in a group..

Output
<img src="https://i.stack.imgur.com/Ul7sM.png

I can able to calculate information value in using above group in R.
But unable to group with equal no. of rows.

Can any one help me on this?
thanks in advance....

I might not be able to clear you..I need a extra column which hold the group number..like I did data$test.

答: You could try split_var() from the sjmisc-package, which splits a vector into equal sized groups (i.e. each group has approximately the same n). Or group_var() from the same package, which groups vectors into groups with equal range (1-5, 6-10, 11-15...).

Body:
I am trying to divide a dataframe col into 10 equal no of groups.

I have tried like this way:

Code:

data$test<-as.numeric(cut2(data$age_201512, g=10))
res_count_table_10<-aggregate(data$final_res~data$test,data,sum)

Output is :

I have tried to count the test variable

table(data$test)

<a href="https://i.stack.imgur.com/9bigr.png
<img src="https://i.stack.imgur.com/9bigr.png

How can divide into equal 10 groups??
I have tried the same with Excel VBA using (total no.of rows/10) as number of rows in a group..

Output
<a href="https://i.stack.imgur.com/Ul7sM.png
<img src="https://i.stack.imgur.com/Ul7sM.png

I can able to calculate information value in using above group in R.
But unable to group with equal no. of rows.

Can any one help me on this?
thanks in advance....

I might not be able to clear you..I need a extra column which hold the group number..like I did data$test.


问:
How to save Obj-C block in a C struct?
I want to call a C function from my ObjC. I am passing a C function reference (defined in ObjC) in a C struct so that C can call that function. I also want to pass the reference to a completion-block to C, so that when I get a callback, I can call that completion-block. But I do not know how to implement that. I get different errors based on the different typecasting I tried.</p>

```<code>//Abc.m

void myCallback(MyData *data)
{
  //I get the control here!
  //((__bridge void *)(data->completionBlock))([NSString stringWithCString:data->json]); //how to call the completion block?
}

- (void)myMethod:(NSString)input
             completion:(void (^)(NSString * _Nullable response))completionBlock
{
    MyData *data = malloc(sizeof(MyData));
    data->myCallback = myCallback;
    data->completionBlock = (__bridge void *)(completionBlock);//is this correct?
    cFunction(data);
}

//Xyz.c

typedef struct
{
  char *json;
  void (*myCallback)(void *response);
  void *completionBlock;
} MyData;

void cFunction(MyData *data)
{
  data->json = "some response";
  (data->myCallback)(data);
}
</code>```

答:
__bridge means to use c style pointer, its behaviour like assign or __unsafe_unretained.

You use it mean data->completionBlock just point to completionBlock without retain, so you may crash when completionBlock has been released.

If you wanna access block or objective-c object in struct with ARC, you have to declare these with __unsafe_unretained and manager their life by yourself.

```<code>typedef struct {
char *json;
__unsafe_unretained NSString *name;
__unsafe_unretained CompletionBlock block;
} SampleStruct;
</code>```

Title: How to save Obj-C block in a C struct?

Body:
I want to call a C function from my ObjC. I am passing a C function reference (defined in ObjC) in a C struct so that C can call that function. I also want to pass the reference to a completion-block to C, so that when I get a callback, I can call that completion-block. But I do not know how to implement that. I get different errors based on the different typecasting I tried.

//Abc.m

void myCallback(MyData *data)
{
  //I get the control here!
  //((__bridge void *)(data->completionBlock))([NSString stringWithCString:data->json]); //how to call the completion block?
}

- (void)myMethod:(NSString)input
             completion:(void (^)(NSString * _Nullable response))completionBlock
{
    MyData *data = malloc(sizeof(MyData));
    data->myCallback = myCallback;
    data->completionBlock = (__bridge void *)(completionBlock);//is this correct?
    cFunction(data);
}

//Xyz.c

typedef struct
{
  char *json;
  void (*myCallback)(void *response);
  void *completionBlock;
} MyData;

void cFunction(MyData *data)
{
  data->json = "some response";
  (data->myCallback)(data);
}

Body:
__bridge means to use c style pointer, its behaviour like assign or __unsafe_unretained.

You use it mean data->completionBlock just point to completionBlock without retain, so you may crash when completionBlock has been released.

If you wanna access block or objective-c object in struct with ARC, you have to declare these with __unsafe_unretained and manager their life by yourself.

typedef struct {
char *json;
__unsafe_unretained NSString *name;
__unsafe_unretained CompletionBlock block;
} SampleStruct;


问:
Is Scrapy compatible with Python 3 on Windows?
Is 'scrapy' compatible with Python 3(or later) on Windows?
If not, then is the only option to use it with Python 2.7?
I need this for a project I need to do.
Thank you.</p>

答:
Yes, it is, you can install it via

pip install scrapy

(You may want to activate your virtual environment first)


问:
How to find set difference in Mysql?
What is the 'except' equivalent command in mysql?

```<code>SELECT name FROM table1 except SELECT name FROM table2
</code>```

答:
Often easiest to use a LEFT OUTER JOIN, and then in the WHERE clause check that there is no matching field.</p>

```<code>SELECT name
FROM table1
LEFT OUTER JOIN table2 ON table1.name = table2.name
WHERE table2.name IS NULL
</code>```

Title: How to find set difference in Mysql?

Body:
What is the 'except' equivalent command in mysql?

SELECT name FROM table1 except SELECT name FROM table2

Body:
Often easiest to use a LEFT OUTER JOIN, and then in the WHERE clause check that there is no matching field.

SELECT name
FROM table1
LEFT OUTER JOIN table2 ON table1.name = table2.name
WHERE table2.name IS NULL


问:
trigger parameterized build with groovy variable
I have an Jenkins Freestyle job with an system groovy script in the Build area. After executing the script I want to trigger a pipeline job. The pipeline job needs a variable who gets defined inside my groovy scipt.

```<code>if(condition1){
    var = 'String1'
}else{
    var = 'String2'
}
</code>```

But I need to get acces to my variable var at the "post-build-action" step at the "Trigger parameterized build on other projects" option to trigger my pipeline with var as parameter. Is this possible?

答:
Yes, it is possible. You can simply write your variables as key-value pairs in a property file and load it in your post-build-action by specifying Parameters from properties file.

You can save your property file like this

```<code>def fw = new OutputStreamWriter(new FileOutputStream("params.properties",true), 'UTF-8')
def props = new Properties()
props.setProperty('TESTPARAM', var)
props.store(fileWriter, null)
fw.close()
</code>```

Body:
I have an Jenkins Freestyle job with an system groovy script in the Build area. After executing the script I want to trigger a pipeline job. The pipeline job needs a variable who gets defined inside my groovy scipt.

if(condition1){
    var = 'String1'
}else{
    var = 'String2'
}

But I need to get acces to my variable var at the "post-build-action" step at the "Trigger parameterized build on other projects" option to trigger my pipeline with var as parameter. Is this possible?

Body:
Yes, it is possible. You can simply write your variables as key-value pairs in a property file and load it in your post-build-action by specifying Parameters from properties file.

You can save your property file like this

def fw = new OutputStreamWriter(new FileOutputStream("params.properties",true), 'UTF-8')
def props = new Properties()
props.setProperty('TESTPARAM', var)
props.store(fileWriter, null)
fw.close()


问:
Saving data to a file vs. saving it to MySQL DB
Using a PHP script I need to update a number every 5 seconds while somebody is on my page. So let's say I have 300 visitors, each one spending about 1 minute on the page and every 5 seconds they stay on the page the number will be changed...which is a total of 3600 changes per minute. I would prefer to update the number in my MySQL database, except I'm not sure if it's not too inefficient to have so many MySQL connections (just for the one number change), when I could just change the number in a file.

P.S.: I have no idea weather 3600 connections/minute is a high number or not, but what about this case in general, considering an even higher number of visitors. What is the most efficient way to do this?

答:
Doing 3,600 reads and writes per minute against the same file is just out of question. It's complicate (you need to be extremely careful with file locking), it's going to have an awful performance and sooner or later your data will get corrupted.

DBMSs like MySQL are designed for concurrent access. If they can't cope with your load, a file won't do it better.