问:
Swift: How to put often used code into a single place to reuse it?
I am still trying to grasp all these programming concepts and I have a simple UIView with a rgb color and I am using this on many different views.

Right now I am still hard coding the color in every view:

```<code>UIColor(red: 120/255, green: 51/255, blue: 2/255, alpha: 1.0
</code>```

But I'd love to create a single swift file (called Colors.swift for instance) and there I'd like to put all colors.

Now in every single view I'd like to just get the color from this file, so that I have only one place to change the colors if necessary.

I know how to create a function in a swift file and call it from another place. For example all animations I reuse I place into one file, but with those colors I'm having a blackout. I have no idea how to place them into another file and get them out of there. Perfect would be some kind of switch case with different named colors (blue, green,...) and their corresponding rgb values so that I can just call the name of the color to get it. This would be a swift file I create:

```<code>import UIKit

let myColors = UIColor()

switch myColors {
case .red:
    UIColor(red: 120/255, green: 51/255, blue: 2/255, alpha: 1.0)
case .gray:
    UIColor(red: 120/255, green: 120/255, blue: 120/255, alpha: 1.0)
default:
    UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
}
</code>```

But when I write a switch statement in a swift file I cannot get this to work. The error I get is "statements are not allowed on top level" and each case gets the error "Results of UIColor initializer is unused", but I do not see a way to place it inside something?

Maybe the whole approach is wrong?

答:
For Repeatedly Used Functions and Variables

Make one GlobalFunctions.swift class which have root class is NSObject and Declare your repeatedly used variables and Functions here

In Your case:-

```<code>import UIKit

class GlobalFunctions: NSObject {

    static let redColor = UIColor(red: 120/255, green: 51/255, blue: 2/255, alpha: 1.0
    static let greyColor = UIColor(red: 120/255, green: 120/255, blue: 120/255, alpha: 1.0)
    static let defaultColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
}
</code>```

You can use this color in your requiered View Controller like:

```<code>GlobalFunctions.redColor
GlobalFunctions.greyColor
GlobalFunctions.defaultColor
</code>```

There is no need to create object for GloablFunctions.swift. You can directly access the color object because we have declared it as static variables. You can add class functions also to use recursively in your project.

Body:
I am still trying to grasp all these programming concepts and I have a simple UIView with a rgb color and I am using this on many different views.

Right now I am still hard coding the color in every view:

UIColor(red: 120/255, green: 51/255, blue: 2/255, alpha: 1.0

But I'd love to create a single swift file (called Colors.swift for instance) and there I'd like to put all colors.

Now in every single view I'd like to just get the color from this file, so that I have only one place to change the colors if necessary.

I know how to create a function in a swift file and call it from another place. For example all animations I reuse I place into one file, but with those colors I'm having a blackout. I have no idea how to place them into another file and get them out of there. Perfect would be some kind of switch case with different named colors (blue, green,...) and their corresponding rgb values so that I can just call the name of the color to get it. This would be a swift file I create:

import UIKit

let myColors = UIColor()

switch myColors {
case .red:
    UIColor(red: 120/255, green: 51/255, blue: 2/255, alpha: 1.0)
case .gray:
    UIColor(red: 120/255, green: 120/255, blue: 120/255, alpha: 1.0)
default:
    UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
}

But when I write a switch statement in a swift file I cannot get this to work. The error I get is "statements are not allowed on top level" and each case gets the error "Results of UIColor initializer is unused", but I do not see a way to place it inside something?

Maybe the whole approach is wrong?

Body:
For Repeatedly Used Functions and Variables

Make one GlobalFunctions.swift class which have root class is NSObject and Declare your repeatedly used variables and Functions here

In Your case:-

import UIKit

class GlobalFunctions: NSObject {

    static let redColor = UIColor(red: 120/255, green: 51/255, blue: 2/255, alpha: 1.0
    static let greyColor = UIColor(red: 120/255, green: 120/255, blue: 120/255, alpha: 1.0)
    static let defaultColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
}

You can use this color in your requiered View Controller like:

GlobalFunctions.redColor
GlobalFunctions.greyColor
GlobalFunctions.defaultColor

There is no need to create object for GloablFunctions.swift. You can directly access the color object because we have declared it as static variables. You can add class functions also to use recursively in your project.


来源: stackexchange

问:
Remove null properties in Sesam DTL
Using Sesam I'm left with a bunch of null properties.

How would i proceed to skip properties that are null completely in DTL?
Any examples of DTL that does this would be great.

Example

From:

```<code>{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "column2": "null",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}
</code>```

To:

```<code>{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}
</code>```

答:
This can solved using a combination of the "key-values", "merge", and "apply" functions as shown here:

```<code>{
  "_id": "remove-null-values",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "foo",
      "bar": "baz",
      "foo": null
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["merge",
          ["apply", "drop-nulls",
            ["key-values", "_S."]
          ]
        ]
      ],
      "drop-nulls": [
        ["filter",
          ["is-not-null", "_S.value"]
        ],
        ["merge",
          ["dict", "_S.key", "_S.value"]
        ]
      ]
    }
  }
}
</code>```

The result will be:

```<code>[
  {
    "_id": "foo",
    "bar": "baz"
  }
]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Remove null properties in Sesam DTL

Body:
Using Sesam I'm left with a bunch of null properties.

How would i proceed to skip properties that are null completely in DTL?
Any examples of DTL that does this would be great.

Example

From:

{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "column2": "null",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}

To:

{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}

Body:
This can solved using a combination of the "key-values", "merge", and "apply" functions as shown here:

{
  "_id": "remove-null-values",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "foo",
      "bar": "baz",
      "foo": null
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["merge",
          ["apply", "drop-nulls",
            ["key-values", "_S."]
          ]
        ]
      ],
      "drop-nulls": [
        ["filter",
          ["is-not-null", "_S.value"]
        ],
        ["merge",
          ["dict", "_S.key", "_S.value"]
        ]
      ]
    }
  }
}

The result will be:

[
  {
    "_id": "foo",
    "bar": "baz"
  }
]


问:
MessageBox not shown when opened processing WM_CLOSE from taskbar thumbnail close button
Trying to put up a "Do you want to save"-dialog when trying to close window with close-button in taskbar thumbnail in windows 7(with aero peek active).

Using MessageBox() when processing WM_CLOSE does not work. MessageBox won't show until you move mouse cursor outside thumbnail so aero peek is disabled.

Lots of applications have this buggy behaviour so it's probably a design flaw in Windows 7, but for some programs it works (Word, Notepad, Visual Studio, ...), so I'm wondering what trick they are using(or what it takes to "exit" aero peek-mode programmatically).

The small "Sound Recorder" application that comes with Windows 7 has the same problem (if you have recorded something without saving and try to close it using thumbnail close-button)...

答:
I put together a small app to reproduce this problem.  I was able to successfully get the message box to appear by calling SetForegroundWindow before calling MessageBox.</p>

```<code>case WM_SYSCOMMAND:
    if (wParam == SC_CLOSE)
    {
        SetForegroundWindow(hWnd);
        MessageBox(hWnd, L"Are you sure you want to exit", L"Close Window", MB_OK);
    }
    else
    {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    break;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I put together a small app to reproduce this problem.  I was able to successfully get the message box to appear by calling SetForegroundWindow before calling MessageBox.

case WM_SYSCOMMAND:
    if (wParam == SC_CLOSE)
    {
        SetForegroundWindow(hWnd);
        MessageBox(hWnd, L"Are you sure you want to exit", L"Close Window", MB_OK);
    }
    else
    {
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    break;


问:
Converting string of "bytes" to numpy array of uint8
I'm using a API that returns RGB data as strings(*) (for instance I get 'ABC' for [65, 66, 67]. Is there a way to have this directly converted to a numpy unint8 array without an explicit comprehension with ord()? Since this is picture data, I could be processing several million bytes, so any shortcut can help.

Otherwise, any method faster than the comprehension is gladly accepted.

(*) API requires Python 2.7, for the time being

答:
You can use np.frombuffer:

```<code>np.frombuffer(b'ABC', dtype=np.uint8)
# array([65, 66, 67], dtype=uint8)
</code>```

Since you are on Python2 this will probably work directly on strings, on Python3 a string would have to be encoded first to yield a bytes object.

Body:
You can use np.frombuffer:

np.frombuffer(b'ABC', dtype=np.uint8)
# array([65, 66, 67], dtype=uint8)

Since you are on Python2 this will probably work directly on strings, on Python3 a string would have to be encoded first to yield a bytes object.


问:
Execute immediate within Oracle Procedure
I have two users: SASDBA and CDM.
There is a procedure in schema SASDBA which keeps objects into the buffer pool.
Part of a procedure:

```<code>BEGIN
              FOR TABLE_ENTRY IN
              (SELECT          *
              FROM dba_tables
              WHERE owner = t_owner
              AND TABLE_NAME    = t_name_obj
              )
              LOOP
EXECUTE immediate 'alter table '||TABLE_ENTRY.OWNER||'.'||TABLE_ENTRY.TABLE_NAME||' storage (buffer_pool keep)';
    END LOOP;
END;
</code>```

So, if I try to pass CDM.TABLE_TEST into the procedure I get an error:

ORA-01031: insufficient privileges

But, if user SASDBA alters it without procedure it works:

```<code>alter table CDM.TEST_TABLE  storage (buffer_pool keep)
</code>```

table CDM.TEST_TABLE altered.

答:
Inside PL/SQL blocks you have only privileges which are granted to you directly. Privileges which are granted through a role (e.g. DBA) do not apply inside a PL/SQL block, i.e. a procedure.

Grant privilege directly, for example GRANT ALTER ANY TABLE TO SASDBA;

Body:
I have two users: SASDBA and CDM.
There is a procedure in schema SASDBA which keeps objects into the buffer pool.
Part of a procedure:

BEGIN
              FOR TABLE_ENTRY IN
              (SELECT          *
              FROM dba_tables
              WHERE owner = t_owner
              AND TABLE_NAME    = t_name_obj
              )
              LOOP
EXECUTE immediate 'alter table '||TABLE_ENTRY.OWNER||'.'||TABLE_ENTRY.TABLE_NAME||' storage (buffer_pool keep)';
    END LOOP;
END;

So, if I try to pass CDM.TABLE_TEST into the procedure I get an error:

ORA-01031: insufficient privileges

But, if user SASDBA alters it without procedure it works:

alter table CDM.TEST_TABLE  storage (buffer_pool keep)

table CDM.TEST_TABLE altered.


问:
Javascript copy input value
Hello Guys I want to copy input value yeah on button click But nothing work. Please Help!!</p>

```<code><script>
  function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
  }
</script>

<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

<button class="btn btn-primary btn-block" onclick="copyToClipboard('#myvalue')">Copy myvalue</button>
</code>```

答:
Code if you want to copy input text to ClipBoard.</p>

```<code>//HTML
<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />
<button class="btn btn-primary btn-block" onclick="copyToClipboard();">Copy myvalue</button>

//SCRIPT For ClipBoard Copy
 <Script>
    function copyToClipboard() {
        var textBox = document.getElementById("myvalue");
        textBox.select();
        document.execCommand("copy");
    }
</Script>

//For local storage variable copy
<Script>
    function copyToStorage() {
        var textBox = document.getElementById("myvalue");
        if(typeof(Storage) !== "undefined") {

            var textBox_value=textBox.value;
            localStorage.setItem("textBox_value", textBox_value);
         } else {
               alert("Sorry your browser does not support this script");
           }
    }
</Script>

   // Also there one to use an element like hidden to store the value for same page life.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Javascript copy input value

Body:
Hello Guys I want to copy input value yeah on button click But nothing work. Please Help!!

<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

<button class="btn btn-primary btn-block" onclick="copyToClipboard('#myvalue')">Copy myvalue</button>

Body:
Code if you want to copy input text to ClipBoard.

//HTML
<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />
<button class="btn btn-primary btn-block" onclick="copyToClipboard();">Copy myvalue</button>

//SCRIPT For ClipBoard Copy
 <Script>
    function copyToClipboard() {
        var textBox = document.getElementById("myvalue");
        textBox.select();
        document.execCommand("copy");
    }
</Script>

//For local storage variable copy
<Script>
    function copyToStorage() {
        var textBox = document.getElementById("myvalue");
        if(typeof(Storage) !== "undefined") {

            var textBox_value=textBox.value;
            localStorage.setItem("textBox_value", textBox_value);
         } else {
               alert("Sorry your browser does not support this script");
           }
    }
</Script>

   // Also there one to use an element like hidden to store the value for same page life.


问:
Ionic 3 - ion-select(multiple) disable all options after selecting two items
I want to disable all options once two options checked. I have tried (ionChange) but this event fired after clicking the "Ok" button of the select model. Is there any other event which execute before "ionChange"?

```<code> <ion-item>
     <ion-label>Values</ion-label>
     <ion-select formControlName="Values" multiple="true">
          <ion-option value="1">1 value</ion-option>
          <ion-option value="2">2 value</ion-option>
          <ion-option value="3">3 value</ion-option>
          <ion-option value="4">4 value</ion-option>
         <ion-option value="5">5 value</ion-option>
    </ion-select>
 </ion-item>
</code>```

答: Use [disabled] property in on-change function You can perform disable action and other functionality using the selected value

Body:
I want to disable all options once two options checked. I have tried (ionChange) but this event fired after clicking the "Ok" button of the select model. Is there any other event which execute before "ionChange"?

 <ion-item>
     <ion-label>Values</ion-label>
     <ion-select formControlName="Values" multiple="true">
          <ion-option value="1">1 value</ion-option>
          <ion-option value="2">2 value</ion-option>
          <ion-option value="3">3 value</ion-option>
          <ion-option value="4">4 value</ion-option>
         <ion-option value="5">5 value</ion-option>
    </ion-select>
 </ion-item>


问:
How to set protocol using async java driver for ArangoDB?
I am trying to connect ArangoDB from my java program. I have used the official async java driver for arangodb. The document mentions that we can set the protocol using useProtocol() method. But, this method is not present in code and in javadoc as well. Can somebody tell me how can I set the protocol to HTTP?
The github document mentions this following code.

ArangoDBAsync arangoDB = new ArangoDBAsync.Builder().useProtocol(Protocol.VST).build();

But object returned by Builder() method do not have any useProtocol() method.

答: This was a mistake in the documentation. The async java driver only supports VelocyStream while the sync driver supports different network protocols.</p>


问:
iPhone: starting an NSThread from a C++ object
I'm writing a game for the iPhone. Almost all the code is written in C++. Now I'd like to create a new thread using NSThread (I want to use the runLoop).

It's possible to mix objective-C and C++ if the code is written in a .mm file, which I did.

The problem is, that for creating a NSThread

```<code>NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(workerThreadFunction:) object:nil];
[myThread start];
</code>```

I need to pass "self" which (as far as I understand it) an Objective-C "id" - and a c++ object is not an objective-c object.

So - is there a way to use NSThread in a c++ aplication or am I forced to use pthreads?

Thanks!

答:
You cannot derive C++ classes from Objective C classes and vice versa. Design a wrapper ObjC object that would instantiate and call (but not inherit from) the C++ one. This is generally called "containment and delegation".

Or you can use POSIX threads instead of NSThread.

Body:
I'm writing a game for the iPhone. Almost all the code is written in C++. Now I'd like to create a new thread using NSThread (I want to use the runLoop).

It's possible to mix objective-C and C++ if the code is written in a .mm file, which I did.

The problem is, that for creating a NSThread

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(workerThreadFunction:) object:nil];
[myThread start];

I need to pass "self" which (as far as I understand it) an Objective-C "id" - and a c++ object is not an objective-c object.

So - is there a way to use NSThread in a c++ aplication or am I forced to use pthreads?

Thanks!


问:
Converting a number to s string in JavaScript using the + operator?
I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.</p>

```<code>        var number = 134324;
        var num_str = number + "";
       console.log(num_str);
</code>```

答:
You can use toString() method.</p>

```<code>num_str = number.toString()
</code>```

Body:
I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.

        var number = 134324;
        var num_str = number + "";
       console.log(num_str);

Body:
You can use toString() method.

num_str = number.toString()


问:
For loop to determine if similar variables in case/control pairs
I am trying to write a simple for loop but I am not sure how to go about it.
I have a set of data which is grouped (4 controls to 1 case [500 cases overall]). I was to look at each group and see if they also have similar information on another variable and have the output "true/false" if more than two in the "group" have the same value for that variable.

this is an example of the dataset

the output I would expect from this would be
TRUE, FALSE, TRUE

This is what I have so far

```<code>num_rows=nrow(data)
for(i in 1:num_rows){
  if(Pair.ID=data[i,1]{
</code>```

and I have no idea how to finish it...Iknow it is very basic stuff but I am just not sure how to phrase it in the code

答:
As you want to evaluate properties by group, dplyr's group_by is very useful.

```<code>library(dplyr)

data <- data.frame(Pair.ID = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3),
                   Group = c("G2", "F2", "F6", "H1", "G2", "J2", "T1", "J7", "B2", "F3", "F3", "Y6", "F3", "W2"))
</code>```

I first use group_by(Pair.ID) to define the groups and then summarize the data frame with summarize and define the new column Same.Info which is TRUE if any information in the Group column is duplicated for this group and FALSE otherwise.

```<code>data %>%
  group_by(Pair.ID) %>%
  summarize(Same.Info = any(duplicated(Group)))

# # A tibble: 3 x 2
#   Pair.ID Same.Info
#     <dbl>     <lgl>
# 1       1      TRUE
# 2       2     FALSE
# 3       3      TRUE
</code>```

An approach without using dplyr and with a for-loop.

```<code>n_group <- 3

for (i in 1:n_group){
    cat(i, any(duplicated(data$Group[data$Pair.ID == i])), "\n")
}

# 1 TRUE
# 2 FALSE
# 3 TRUE
</code>```

Here the result for checking each group are simply printed to the console with cat, but ofcourse they could be stored in a vector, list, etc.

Body:
I am trying to write a simple for loop but I am not sure how to go about it.
I have a set of data which is grouped (4 controls to 1 case [500 cases overall]). I was to look at each group and see if they also have similar information on another variable and have the output "true/false" if more than two in the "group" have the same value for that variable.

this is an example of the dataset

the output I would expect from this would be
TRUE, FALSE, TRUE

This is what I have so far

num_rows=nrow(data)
for(i in 1:num_rows){
  if(Pair.ID=data[i,1]{

and I have no idea how to finish it...Iknow it is very basic stuff but I am just not sure how to phrase it in the code

Body:
As you want to evaluate properties by group, dplyr's group_by is very useful.

library(dplyr)

data <- data.frame(Pair.ID = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3),
                   Group = c("G2", "F2", "F6", "H1", "G2", "J2", "T1", "J7", "B2", "F3", "F3", "Y6", "F3", "W2"))

I first use group_by(Pair.ID) to define the groups and then summarize the data frame with summarize and define the new column Same.Info which is TRUE if any information in the Group column is duplicated for this group and FALSE otherwise.

data %>%
  group_by(Pair.ID) %>%
  summarize(Same.Info = any(duplicated(Group)))

# # A tibble: 3 x 2
#   Pair.ID Same.Info
#     <dbl>     <lgl>
# 1       1      TRUE
# 2       2     FALSE
# 3       3      TRUE

An approach without using dplyr and with a for-loop.

n_group <- 3

for (i in 1:n_group){
    cat(i, any(duplicated(data$Group[data$Pair.ID == i])), "\n")
}

# 1 TRUE
# 2 FALSE
# 3 TRUE

Here the result for checking each group are simply printed to the console with cat, but ofcourse they could be stored in a vector, list, etc.


问:
convert an encoding to just alphabetical expression
I have a city name string such as

```<code>a='A Coruña'
</code>```

How can I convert this into 'A Coruna'?

Best

答:
for python 3.x</p>

```<code>>>>import unicodedata
>>>a = 'A Coruña'
>>>search_string = ''.join((c for c in unicodedata.normalize('NFD', a)if unicodedata.category(c) != 'Mn'))
>>>print(search_string)
>>>A Coruna
</code>```

Body:
I have a city name string such as

a='A Coruña'

How can I convert this into 'A Coruna'?

Best

Body:
for python 3.x

>>>import unicodedata
>>>a = 'A Coruña'
>>>search_string = ''.join((c for c in unicodedata.normalize('NFD', a)if unicodedata.category(c) != 'Mn'))
>>>print(search_string)
>>>A Coruna


问:
how disable button if app not install in phone
I have button and i want disable this button if app by Package not installed and user can click if app install in phone ..

my code

```<code>    Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.check.application");
    if(isAppInstalled) {
        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}
</code>```

I use this code but the button is disabled at all times .. if app install the button disable and if not install the button disable

答:
```<code>     boolean isAppInstalled = appInstalledOrNot("com.check.application");
    btn.setEnabled(isAppInstalled)

        private boolean appInstalledOrNot(String uri) {
            PackageManager pm = getPackageManager();
            try {
                pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
                return true;
            } catch (PackageManager.NameNotFoundException e) {
                  return false;
            }
</code>```

Body:
I have button and i want disable this button if app by Package not installed and user can click if app install in phone ..

my code

    Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.check.application");
    if(isAppInstalled) {
        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

I use this code but the button is disabled at all times .. if app install the button disable and if not install the button disable


问:
Ajax JSON for each
Hello guys i  had a simple ajax request this also is working fine, but i had to loop trought the data and display all 10 names in the object allready searched it in stack but the object which i had is a bit to complicated. any suggestions how i can solve it?</p>

```<code>$( document ).ready(function() {
$.ajax({
   url: 'XXXXXXX',
   data: {
      format: 'json'
   },
   error: function() {
   alert('ERROR');
   },
   sasdataType: 'json',
   success: function(data) {
    /*var $hotelname = $('<h1>').text(data.result.hotel[0].displayname);
        $('#hotel-name').append($hotelname)*/
    console.log(data);
   },
   type: 'GET'
});
});
</code>```

答:
If I figured the structure OK, it should be something like:</p>

```<code>$.each(data.result.district, function(index, district) {
     $.each($(district), function(index, hotel) {
         console.log($(hotel).displayname);
     });
});
</code>```

Title: Ajax JSON for each

Body:
Hello guys i  had a simple ajax request this also is working fine, but i had to loop trought the data and display all 10 names in the object allready searched it in stack but the object which i had is a bit to complicated. any suggestions how i can solve it?

$( document ).ready(function() {
$.ajax({
   url: 'XXXXXXX',
   data: {
      format: 'json'
   },
   error: function() {
   alert('ERROR');
   },
   sasdataType: 'json',
   success: function(data) {
    /*var $hotelname = $('
').text(data.result.hotel[0].displayname);
        $('#hotel-name').append($hotelname)*/
    console.log(data);
   },
   type: 'GET'
});
});

Body:
If I figured the structure OK, it should be something like:

$.each(data.result.district, function(index, district) {
     $.each($(district), function(index, hotel) {
         console.log($(hotel).displayname);
     });
});


问:
How do you comment an MS-access Query?
How does one add a comment to an MS Access Query, to provide a description of what it does?

Once added, how can one retrieve such comments programmatically?

答:
You can add a comment to an MSAccess query as follows: Create a dummy field in the query.  Not elegant but is self-documentating and contained in the query, which makes cheking it into source code control alot more feasible!  Jere's an example.  Go into SQL view and add the dummy field (you can do from design view too):

```<code>SELECT  "2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" as qryHISTORY,  ...rest of query here...
</code>```

Run the query:

```<code>qryHISTORY                           FIELD01 FIELD02 ...
2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;"  0000001  ABCDEF ...
</code>```

Note the use of ";" as field delimiter in qryHISTORY field, and ";;" as an end of comment, and use of ISO date format and intials, as well as comment.  Have tested this with up to 646 characters in the qryHISTORY field.

OwnerDisplayName: Varun Mahajan

Title: How do you comment an MS-access Query?

LastEditorDisplayName: RoBorg

Body:
You can add a comment to an MSAccess query as follows: Create a dummy field in the query.  Not elegant but is self-documentating and contained in the query, which makes cheking it into source code control alot more feasible!  Jere's an example.  Go into SQL view and add the dummy field (you can do from design view too):

SELECT  "2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;" as qryHISTORY,  ...rest of query here...

Run the query:

qryHISTORY                           FIELD01 FIELD02 ...
2011-01-21;JTR;Added FIELD02;;2011-01-20;JTR;Added qryHISTORY;;"  0000001  ABCDEF ...

Note the use of ";" as field delimiter in qryHISTORY field, and ";;" as an end of comment, and use of ISO date format and intials, as well as comment.  Have tested this with up to 646 characters in the qryHISTORY field.


问:
How to remember last tab used with PHP form submit?
I have a form inside one of many tabs, but when it submits it goes back to the first one.

```<code><div class="panel panel-primary">
    <div class="panel-heading">
        <div class="panel-control">
            <ul class="nav nav-tabs">
                <li class="active"><a data-toggle="tab" href="#tab" aria-expanded="true">Tab1</a></li>
                <li class=""><a data-toggle="tab" href="#tab-2" aria-expanded="false">Tab2</a></li>
            </ul>
        </div>
        <h3 class="panel-title">Text</h3>
    </div>
    <div class="panel-body">
        <div class="tab-content">
            <div id="tab" class="tab-pane fade active in">
                <form class="form-group" method="post" action="#" enctype="multipart/form-data">
                    <input class="form-control description" name="description[]" placeholder="Description here">
                    <input class="btn btn-primary btn-lg" name="update" type="submit" value="Save">
                </form>
            </div>
            <div id="tab-2" class="tab-pane fade">

            </div>
        </div>
    </div>
</div>
</code>```

PHP fetches form and update database and redirects:

```<code>if(isset($_POST['update'])){
    //database update

    //current url + tab
    header("Location: {$url->getCurentUrl()}#tab3");
}
</code>```

The link is correct, but the tab won't update using the #tab in url, anyone have alternative methods to set active tab to last tab used?

答:
Use this below code ...might be helpful to you as it's for me so...    </p>

```<code>$('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
  localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
  $('#action-tab a[href="' + activeTab + '"]').tab('show');
}
</code>```

Body:
I have a form inside one of many tabs, but when it submits it goes back to the first one.

Tab1

Tab2

Text

                <form class="form-group" method="post" action="#" enctype="multipart/form-data">
                    <input class="form-control description" name="description[]" placeholder="Description here">
                    <input class="btn btn-primary btn-lg" name="update" type="submit" value="Save">
                </form>

PHP fetches form and update database and redirects:

if(isset($_POST['update'])){
    //database update

    //current url + tab
    header("Location: {$url->getCurentUrl()}#tab3");
}

The link is correct, but the tab won't update using the #tab in url, anyone have alternative methods to set active tab to last tab used?

Body:
Use this below code ...might be helpful to you as it's for me so...

$('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
  localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
  $('#action-tab a[href="' + activeTab + '"]').tab('show');
}


问:
Does C# have extension properties?
Does C# have extension properties?

For example, can I add an extension property to DateTimeFormatInfo called ShortDateLongTimeFormat which would return ShortDatePattern + " " + LongTimePattern?

答:
Update (thanks to @chaost for pointing this update out):

Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"

Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/

I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.

Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.

So instead of doing this...

```<code>public static class IntExtensions
{
   public static bool Even(this int value)
   {
        return value % 2 == 0;
   }
}
</code>```

We'll be finally able to do it like so...

```<code>public extension IntExtension extends int
{
    public bool Even => this % 2 == 0;
}
</code>```

Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/

OwnerDisplayName: Svish

Title: Does C# have extension properties?

Body:
Update (thanks to @chaost for pointing this update out):

Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"

Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/

I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.

Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.

So instead of doing this...

public static class IntExtensions
{
   public static bool Even(this int value)
   {
        return value % 2 == 0;
   }
}

We'll be finally able to do it like so...

public extension IntExtension extends int
{
    public bool Even => this % 2 == 0;
}

Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/


问:
Motorola barcode scanner
I have Motorola m55, barcode scanner is only active in when I run demo app for barcode scanner. Now I am planing to create remote desktop app for scanning, so is there a way to make barcode active all the time on this device.</p>

答:
Before planning, please ask the vendor whether it can do it or not.

Regarding WindowsCE / WindowsMobile and its remote desktop, it depends strongly on each products, and there is insufficient with the usual knowledge of Windows for PC.

Title: Motorola barcode scanner


问:
Share data using WCSession between apple Watch and iPhone
Trying to share data from iPhone to apple watch using updateApplicationContext, transferUserInfo of Watch connectivity (WCSession) working in simulator but when trying same on device but its not working.

Device : iPhone 6 plus(OS 11.1), apple watch-Series 2(Watch OS 4.1).

Working on defaultSession and implemented necessary delegate methods for watchConnectivity.

iPhone side :

step : 1

```<code>if ([WCSession isSupported])
{
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}
</code>```

step : 2

```<code>[[WCSession defaultSession] transferUserInfo:dataDict];
</code>```

Apple Watch side : Working on defaultSession
step : 1

```<code>if ([WCSession isSupported])
{
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}
</code>```

step : 2

```<code>   -(void)session:(WCSession *)session didReceiveUserInfo:(NSDictionary<NSString *,id> *)userInfo
    {
       // code for data parsing which get from userInfo dictionary.
    }
</code>```

答:
I have done this for my project

After setting session and creating data dictionary you use send message with this

```<code>[[WCSession defaultSession] sendMessage:dataDict replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {

        //You task on completion

    } errorHandler:^(NSError * _Nonnull error) {

        if (error)
        {
            //Handle the error
        }
    }];
</code>```

And in watch app code
You can set delegate method

```<code>- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
{
}
</code>```

And you are done

Body:
Trying to share data from iPhone to apple watch using updateApplicationContext, transferUserInfo of Watch connectivity (WCSession) working in simulator but when trying same on device but its not working.

Device : iPhone 6 plus(OS 11.1), apple watch-Series 2(Watch OS 4.1).

Working on defaultSession and implemented necessary delegate methods for watchConnectivity.

iPhone side :

step : 1

if ([WCSession isSupported])
{
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}

step : 2

[[WCSession defaultSession] transferUserInfo:dataDict];

Apple Watch side : Working on defaultSession
step : 1

if ([WCSession isSupported])
{
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}

step : 2

   -(void)session:(WCSession *)session didReceiveUserInfo:(NSDictionary<NSString *,id> *)userInfo
    {
       // code for data parsing which get from userInfo dictionary.
    }

Body:
I have done this for my project

After setting session and creating data dictionary you use send message with this

[[WCSession defaultSession] sendMessage:dataDict replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {

        //You task on completion

    } errorHandler:^(NSError * _Nonnull error) {

        if (error)
        {
            //Handle the error
        }
    }];

And in watch app code
You can set delegate method

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler
{
}

And you are done


问:
Local html file AJAX Call and jQuery Woes
I'm working on a offline version of a website using jQuery and some xml files. I'm running in to a problem in jQuery when I do a $.ajax call on a xml file jQuery throws a error.

When I look at the error I can tell its loading the XML file because its in the error's responceText property. It seams to work just fine in Firefox.

This is how my call looks

```<code>$.ajax({
    type: "GET",
    url: "Modules/" + ModuleID + "/ModuleContent.xml",
    dataType: "xml",
    success: function(x) { xml = x; ProcessXML(); },
    error: function(x) { alert(x.responceText); }
});
</code>```

When I run this on a web server it works just fine. Its only when I run it from the file its self when I have this problem.

Any ideas on how I can make this work in IE?

Edit: I found the answer to my problem. Here

答:
From the link that the OP posted with the answer:

When loading XML files locally, e.g. a
  CD-ROM etc., the data received by
  Internet Explorer is plain-text, not
  text/xml. In this case, use the
  dataType parameter to load the xml
  file as text, and parse the returned
  data within the succes function

```<code> $.ajax({
   url: "data.xml",
   dataType: ($.browser.msie) ? "text" : "xml",
   success: function(data){
     var xml;
     if (typeof data == "string") {
       xml = new ActiveXObject("Microsoft.XMLDOM");
       xml.async = false;
       xml.loadXML(data);
     } else {
       xml = data;
     }
     // Returned data available in object "xml"
   }
 });
</code>```

This worked for me as well.

OwnerDisplayName: Superdumbell

Body:
I'm working on a offline version of a website using jQuery and some xml files. I'm running in to a problem in jQuery when I do a $.ajax call on a xml file jQuery throws a error.

When I look at the error I can tell its loading the XML file because its in the error's responceText property. It seams to work just fine in Firefox.

This is how my call looks

$.ajax({
    type: "GET",
    url: "Modules/" + ModuleID + "/ModuleContent.xml",
    dataType: "xml",
    success: function(x) { xml = x; ProcessXML(); },
    error: function(x) { alert(x.responceText); }
});

When I run this on a web server it works just fine. Its only when I run it from the file its self when I have this problem.

Any ideas on how I can make this work in IE?

Edit: I found the answer to my problem. Here

LastEditorDisplayName: Superdumbell

Body:
From the link that the OP posted with the answer:

When loading XML files locally, e.g. a
  CD-ROM etc., the data received by
  Internet Explorer is plain-text, not
  text/xml. In this case, use the
  dataType parameter to load the xml
  file as text, and parse the returned
  data within the succes function

 $.ajax({
   url: "data.xml",
   dataType: ($.browser.msie) ? "text" : "xml",
   success: function(data){
     var xml;
     if (typeof data == "string") {
       xml = new ActiveXObject("Microsoft.XMLDOM");
       xml.async = false;
       xml.loadXML(data);
     } else {
       xml = data;
     }
     // Returned data available in object "xml"
   }
 });

This worked for me as well.

OwnerDisplayName: Mark A. Nicolosi


问:
Compute median of up to 5 in Scala
So, while answering some other question I stumbled upon the necessity of computing the median of 5. Now, there's a similar question in another language, but I want a Scala algorithm for it, and I'm not sure I'm happy with mine.</p>

答:
As suggested, here's my own algorithm:</p>

```<code>def medianUpTo5(arr: Array[Double]): Double = {
    def oneAndOrderedPair(a: Double, smaller: Double, bigger: Double): Double =
        if (bigger < a) bigger
        else if (a < smaller) smaller else a

    def partialOrder(a: Double, b: Double, c: Double, d: Double) = {
        val (s1, b1) = if (a < b) (a, b) else (b, a)
        val (s2, b2) = if (c < d) (c, d) else (d, c)
        (s1, b1, s2, b2)
    }

    def medianOf4(a: Double, b: Double, c: Double, d: Double): Double = {
        val (s1, b1, s2, b2) = partialOrder(a, b, c, d)
        if (b1 < b2) oneAndOrderedPair(s2, s1, b1)
        else oneAndOrderedPair(s1, s2, b2)
    }

    arr match {
        case Array(a)       => a
        case Array(a, b)    => a min b
        case Array(a, b, c) =>
            if (a < b) oneAndOrderedPair(c, a, b)
            else oneAndOrderedPair(c, b, a)
        case Array(a, b, c, d) => medianOf4(a, b, c, d)
        case Array(a, b, c, d, e) =>
            val (s1, b1, s2, b2) = partialOrder(a, b, c, d)
            if (s1 < s2) medianOf4(e, b1, s2, b2)
            else medianOf4(e, b2, s1, b1)
    }
}
</code>```

Title: Compute median of up to 5 in Scala

Body:
As suggested, here's my own algorithm:

def medianUpTo5(arr: Array[Double]): Double = {
    def oneAndOrderedPair(a: Double, smaller: Double, bigger: Double): Double =
        if (bigger < a) bigger
        else if (a < smaller) smaller else a

    def partialOrder(a: Double, b: Double, c: Double, d: Double) = {
        val (s1, b1) = if (a < b) (a, b) else (b, a)
        val (s2, b2) = if (c < d) (c, d) else (d, c)
        (s1, b1, s2, b2)
    }

    def medianOf4(a: Double, b: Double, c: Double, d: Double): Double = {
        val (s1, b1, s2, b2) = partialOrder(a, b, c, d)
        if (b1 < b2) oneAndOrderedPair(s2, s1, b1)
        else oneAndOrderedPair(s1, s2, b2)
    }

    arr match {
        case Array(a)       => a
        case Array(a, b)    => a min b
        case Array(a, b, c) =>
            if (a < b) oneAndOrderedPair(c, a, b)
            else oneAndOrderedPair(c, b, a)
        case Array(a, b, c, d) => medianOf4(a, b, c, d)
        case Array(a, b, c, d, e) =>
            val (s1, b1, s2, b2) = partialOrder(a, b, c, d)
            if (s1 < s2) medianOf4(e, b1, s2, b2)
            else medianOf4(e, b2, s1, b1)
    }
}


问:
Jmeter is not recording any script of any site and gives JAVA connection error

I want to do performance test of my website with the help of Jmeter. i have installed Jmeter version 3.3 and did all the set up with reference of below website. I have done all proxy setting of Jmeter and in browser.

Pdf step by step

But while recording the script, browser does not allow to run the website on Jmeter proxy and gives "java.net.ConnectException: Connection timed out" error.

Please guide.

答:
You most probably didn’t configure the enterprise proxy on JMeter:

http://jmeter.apache.org/usermanual/get-started.html#proxy_server


问:
number of substring which are whose anagrams are palindrome
Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

My attempt in Python:

```<code>def ispalin(s):
    if len(s)%2==0:
        for i in s:
            if s.count(i)%2!=0:
                return False
    else:
        sum =0
        for i in set(s):
            if s.count(i)%2==1:
                sum = sum+1
        if sum == 1:
            return True
        else:
            return False

    return True

def solution(S):
    # write your code in Python 3.6
    count=len(S)
    for i in range(len(S)):
        for j in range(i+1,len(S)):
            if ispalin(S[i:j+1]):
                count=count+1

    return count
</code>```

i/o format

```<code>For example, given:

    S = "02002"
the function should return 11.
these are 11 substrings whose anagrams are palindrome
"0", "2", "0", "0", "2", "00", "020", "200", "002", "2002", "02002"
</code>```

It is giving time limit exceeded for big strings. How can I optimize the above code?

 i bet there exists a better solution than this here is the proof
[image][1]

https://i.stack.imgur.com/7x3Jq.png

答:
There is an O(n) solution for this problem. The first thing to notice is, a substring is anagram of any palindrome if number of its including digits be even or at most one odd exist. e.g. "20020" is anagram of plaindrome because number of '2's is even and number of '0's is odd(at most one odd) while "200202" is not ok.

So the only thing we need to keep is parity of number of digits not sum of them. we can use a 10-bit number to show the parities of all digits. Starting from 0 each time we visit a digit in string, we can xor the parity number with (2^digit). following your example for "02002" here is the parity numbers generated by iterating through the string in binary format:

```<code>parity_array = {0000000000, 0000000001, 0000000101, 0000000100, 0000000101 0000000001}
</code>```

Now we need to count the number of anagrams in linear time. Iterating over the parity_array we use another array of size 1024 (let's call it memo) to keep the number of times we visit a specific number in parity_array. As I mentioned before the substring is ok if and only if the number of 1 bits in their binary parity representation be at most 1. So for each member of parity_array we need to check and add 11 elements in memo having xor with current parity_array value equal to: {0 or 1 or 2 or 4 or 8 ... or 1024} and sum up the results.
The total complexity is O(n).

Edit:
I added C++ code for what I explained above. I can also add python code, if you want:

```<code>string sample = "02002";
int parity = 0;
vector<int> parity_array;
parity_array.push_back(parity);
for(int i=0; i<sample.size(); ++i){
    parity ^= 1<<(sample[i]-'0');
    parity_array.push_back(parity);
}
int memo[1025] = {0};
int res=0;
for(int i=0;i<parity_array.size();++i){
    for(int j=-1;j<10;++j)
        res += memo[(1<<j)^parity_array[i]];
    memo[parity_array[i]]++;
}
cout<<res<<endl;
</code>```

Body:
Given a string of digits, count the number of subwords (consistent subsequences) that are anagrams of any palindrome.

My attempt in Python:

def ispalin(s):
    if len(s)%2==0:
        for i in s:
            if s.count(i)%2!=0:
                return False
    else:
        sum =0
        for i in set(s):
            if s.count(i)%2==1:
                sum = sum+1
        if sum == 1:
            return True
        else:
            return False

    return True

def solution(S):
    # write your code in Python 3.6
    count=len(S)
    for i in range(len(S)):
        for j in range(i+1,len(S)):
            if ispalin(S[i:j+1]):
                count=count+1

    return count

i/o format

For example, given:

    S = "02002"
the function should return 11.
these are 11 substrings whose anagrams are palindrome
"0", "2", "0", "0", "2", "00", "020", "200", "002", "2002", "02002"

It is giving time limit exceeded for big strings. How can I optimize the above code?

 i bet there exists a better solution than this here is the proof
[image][1]

https://i.stack.imgur.com/7x3Jq.png

Body:
There is an O(n) solution for this problem. The first thing to notice is, a substring is anagram of any palindrome if number of its including digits be even or at most one odd exist. e.g. "20020" is anagram of plaindrome because number of '2's is even and number of '0's is odd(at most one odd) while "200202" is not ok.

So the only thing we need to keep is parity of number of digits not sum of them. we can use a 10-bit number to show the parities of all digits. Starting from 0 each time we visit a digit in string, we can xor the parity number with (2^digit). following your example for "02002" here is the parity numbers generated by iterating through the string in binary format:

parity_array = {0000000000, 0000000001, 0000000101, 0000000100, 0000000101 0000000001}

Now we need to count the number of anagrams in linear time. Iterating over the parity_array we use another array of size 1024 (let's call it memo) to keep the number of times we visit a specific number in parity_array. As I mentioned before the substring is ok if and only if the number of 1 bits in their binary parity representation be at most 1. So for each member of parity_array we need to check and add 11 elements in memo having xor with current parity_array value equal to: {0 or 1 or 2 or 4 or 8 ... or 1024} and sum up the results.
The total complexity is O(n).

Edit:
I added C++ code for what I explained above. I can also add python code, if you want:

string sample = "02002";
int parity = 0;
vector<int> parity_array;
parity_array.push_back(parity);
for(int i=0; i<sample.size(); ++i){
    parity ^= 1<<(sample[i]-'0');
    parity_array.push_back(parity);
}
int memo[1025] = {0};
int res=0;
for(int i=0;i<parity_array.size();++i){
    for(int j=-1;j<10;++j)
        res += memo[(1<<j)^parity_array[i]];
    memo[parity_array[i]]++;
}
cout<<res<<endl;


问:
Looping Separator Data ORACLE 11g
I am new to Oracle and I am unaware about using for loop in Oracle SQL (not PL/SQL).

I  the query and execute the statements like this:

I have the following data

```<code>ID   NAME    DATE          SALARY
101  5A101   100411041204  12000
</code>```

I need the following result:

```<code>ID    NAME    DATE   SALARY
101   5A101   1004   12000
101   5A101   1104   12000
101   5A101   1204   12000
</code>```

How do I create a query for that result?

答:
You could use recursive CTE for instance:

SQLFiddle Demo

```<code>with cte (id, name, date_, salary, dt, rn) as (
  select id, name, date_, salary, substr(date_, 1, 4), 1 from t
  union all
  select id, name, date_, salary,
         substr(date_, rn * 4 + 1, 4), rn + 1
  from cte where substr(date_, rn * 4 + 1, 4) is not null )
select id, name, dt, salary from cte
  order by id, rn
</code>```

Title: Looping Separator Data ORACLE 11g

Body:
I am new to Oracle and I am unaware about using for loop in Oracle SQL (not PL/SQL).

I  the query and execute the statements like this:

I have the following data

ID   NAME    DATE          SALARY
101  5A101   100411041204  12000

I need the following result:

ID    NAME    DATE   SALARY
101   5A101   1004   12000
101   5A101   1104   12000
101   5A101   1204   12000

How do I create a query for that result?

Body:
You could use recursive CTE for instance:

SQLFiddle Demo

with cte (id, name, date_, salary, dt, rn) as (
  select id, name, date_, salary, substr(date_, 1, 4), 1 from t
  union all
  select id, name, date_, salary,
         substr(date_, rn * 4 + 1, 4), rn + 1
  from cte where substr(date_, rn * 4 + 1, 4) is not null )
select id, name, dt, salary from cte
  order by id, rn


问:
find all jpg and png at the same time
So I want to resize all jpg and png in 1 script

here is what is currently using, is there any way to run this for jpg and png at the same time?

```<code>  find file/path -type f -name '*.PNG' -exec sips -Z 800 -s formatOptions  60 {} \;
</code>```

答:
"How to make find find files based on two different patterns": the -o ("or") option.

```<code>find file/path -type f \( -name '*.PNG' -o -name '*.JPG' \) -exec ...
</code>```

Note that your question should have been phrased like that, as it has nothing to do with sips in particular.

Note that you can use -iname for case-insensitive matching, in case not all your file extensions are uppercase.

Title: find all jpg and png at the same time

Body:
So I want to resize all jpg and png in 1 script

here is what is currently using, is there any way to run this for jpg and png at the same time?

  find file/path -type f -name '*.PNG' -exec sips -Z 800 -s formatOptions  60 {} \;

Body:
"How to make find find files based on two different patterns": the -o ("or") option.

find file/path -type f \( -name '*.PNG' -o -name '*.JPG' \) -exec ...

Note that your question should have been phrased like that, as it has nothing to do with sips in particular.

Note that you can use -iname for case-insensitive matching, in case not all your file extensions are uppercase.


问:
SQL Table Locking
I have an SQL Server locking question regarding an application we have in house. The application takes submissions of data and persists them into an SQL Server table. Each submission is also assigned a special catalog number (unrelated to the identity field in the table) which is a sequential alpha numeric number. These numbers are pulled from another table and are not generated at run time. So the steps are

Insert Data into Submission Table

Grab next Unassigned Catalog
Number from Catalog Table

Assign the Catalog Number to the
Submission in the Submission table

All these steps happen sequentially in the same stored procedure.

Its, rate but sometimes we manage to get two submission at the same second and they both get assigned the same Catalog Number which causes a localized version of the Apocalypse in our company for a small while.

What can we do to limit the over assignment of the catalog numbers?

答:
You could use an identity field to produce the catalog numbers, that way you can safely create and get the number:

```<code>insert into Catalog () values ()
set @CatalogNumber = scope_identity()
</code>```

The scope_identity function will return the id of the last record created in the same session, so separate sessions can create records at the same time and still end up with the correct id.

If you can't use an identity field to create the catalog numbers, you have to use a transaction to make sure that you can determine the next number and create it without another session accessing the table.

Title: SQL Table Locking

Body:
You could use an identity field to produce the catalog numbers, that way you can safely create and get the number:

insert into Catalog () values ()
set @CatalogNumber = scope_identity()

The scope_identity function will return the id of the last record created in the same session, so separate sessions can create records at the same time and still end up with the correct id.

If you can't use an identity field to create the catalog numbers, you have to use a transaction to make sure that you can determine the next number and create it without another session accessing the table.


问:
Can't compile with Facebook Android SDK and Facebook Audience Network SDK
I have a react-native app and I'm trying to import the FB Android SDK and FB Audience Network SDK with the mediation adapter.

When I add these dependencies in my app/build.gradle, I get the following errors during build.

```<code>compile 'com.facebook.android:facebook-android-sdk:4.22.1'
compile 'com.facebook.android:audience-network-sdk:4.26.1'
compile 'com.google.ads.mediation:facebook:4.26.1.0'
</code>```

Errors:

```<code>C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:3: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:4: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:3: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:4: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
</code>```

The only way I could get my project to compile was to do this in android/build.gradle:

```<code>allprojects {
    ....
    configurations.all {
       resolutionStrategy {
         eachDependency { DependencyResolveDetails details ->
           if (details.requested.group == 'com.facebook.react' && details.requested.name == 'react-native') {
             details.useVersion "0.49.5" // Your real React Native version here
           }
         }
         force 'com.facebook.android:facebook-android-sdk:4.22.1' <---Add this line
         force 'com.facebook.android:audience-network-sdk:4.26.1' <---Add this line
       }
    }
}
</code>```

And comment out these two lines in android/app/build.gradle:

```<code>//compile 'com.facebook.android:facebook-android-sdk:4.22.1'
//compile 'com.facebook.android:audience-network-sdk:4.26.1'
compile 'com.google.ads.mediation:facebook:4.26.1.0'
</code>```

If I try any other version of FB Android SDK in android/build.gradle I get the same errors mentioned earlier. After some research, I tried changing the com.android.support:appcompat version but it will always give the same error as above if I do not use 23.

Is this an acceptable way to include these dependencies? It feels like a hack, I don't know why I could not just include the sdks in android/app/build.gradle, and I don't want to be stuck on FB android sdk version 4.22.1 forever.

Also, after testing it does not seem like ad mediation is working from Admob for Facebook Audience Network but I am unsure if it is due to the way I import the sdk like above or an unrelated issue.

If anybody can show me how to correctly include the sdks I would appreciate it. Thanks!

EDIT:
Full android/build.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.0.0'

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

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        mavenCentral()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.google.com' }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
    configurations.all {
       resolutionStrategy {
         eachDependency { DependencyResolveDetails details ->
           if (details.requested.group == 'com.facebook.react' && details.requested.name == 'react-native') {
             details.useVersion "0.49.5" // Your real React Native version here
           }
         }
         force 'com.facebook.android:facebook-android-sdk:4.22.1'
         force 'com.facebook.android:audience-network-sdk:4.26.1'
       }
    }
}
</code>```

And full android/app/build.gradle:

```<code>android {
    compileSdkVersion 23
    buildToolsVersion '25.0.2'

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 50
        versionName "1.11.11"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        multiDexEnabled true
    }
    dexOptions {
        jumboMode = true
        javaMaxHeapSize "4g"
    }
    signingConfigs {
        release {
            ....
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a": 1, "x86": 2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile 'com.android.support:appcompat-v7:23+'

    compile project(':react-native-fetch-blob')
    compile 'com.android.support:multidex:1.0.1'
    compile project(':react-native-billing')
    compile project(':bugsnag-react-native')
    compile project(':react-native-admob')
    compile fileTree(dir: "libs", include: ["*.jar"])

    compile project(':react-native-fbsdk')
    compile project(':react-native-code-push')
    compile project(':react-native-device-info')
    compile project(':react-native-config')
    compile project(':react-native-fast-image')
    compile project(':react-native-camera')
    compile project(':react-native-google-analytics-bridge')
    compile project(':react-native-vector-icons')

    compile(project(":react-native-google-signin")) {
        exclude group: "com.google.android.gms" // very important
    }

    compile 'com.google.android.gms:play-services-auth:11.6.0'
    compile 'com.google.firebase:firebase-appindexing:11.6.0'

    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile 'com.facebook.android:audience-network-sdk:4.26.1'
    compile 'com.google.ads.mediation:facebook:4.26.1.0'

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}
</code>```

答:
My solution was to update all these:

```<code>gradle to 3.01
gradle wrapper to 4.1
compilesdkversion to 26
buildtoolsversion to 26.02
com.android.support:appcompat-v7 to 26+
com.facebook.android:facebook-android-sdk:4.28.0
</code>```

and my app builds successfully

Body:
I have a react-native app and I'm trying to import the FB Android SDK and FB Audience Network SDK with the mediation adapter.

When I add these dependencies in my app/build.gradle, I get the following errors during build.

compile 'com.facebook.android:facebook-android-sdk:4.22.1'
compile 'com.facebook.android:audience-network-sdk:4.26.1'
compile 'com.google.ads.mediation:facebook:4.26.1.0'

Errors:

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:3: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:4: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:3: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

C:\ig3\android\app\build\intermediates\res\merged\debug\values-v24\values-v24.xml:4: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

The only way I could get my project to compile was to do this in android/build.gradle:

allprojects {
    ....
    configurations.all {
       resolutionStrategy {
         eachDependency { DependencyResolveDetails details ->
           if (details.requested.group == 'com.facebook.react' && details.requested.name == 'react-native') {
             details.useVersion "0.49.5" // Your real React Native version here
           }
         }
         force 'com.facebook.android:facebook-android-sdk:4.22.1' <---Add this line
         force 'com.facebook.android:audience-network-sdk:4.26.1' <---Add this line
       }
    }
}

And comment out these two lines in android/app/build.gradle:

//compile 'com.facebook.android:facebook-android-sdk:4.22.1'
//compile 'com.facebook.android:audience-network-sdk:4.26.1'
compile 'com.google.ads.mediation:facebook:4.26.1.0'

If I try any other version of FB Android SDK in android/build.gradle I get the same errors mentioned earlier. After some research, I tried changing the com.android.support:appcompat version but it will always give the same error as above if I do not use 23.

Is this an acceptable way to include these dependencies? It feels like a hack, I don't know why I could not just include the sdks in android/app/build.gradle, and I don't want to be stuck on FB android sdk version 4.22.1 forever.

Also, after testing it does not seem like ad mediation is working from Admob for Facebook Audience Network but I am unsure if it is due to the way I import the sdk like above or an unrelated issue.

If anybody can show me how to correctly include the sdks I would appreciate it. Thanks!

EDIT:
Full android/build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'com.google.gms:google-services:3.0.0'

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

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        mavenCentral()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.google.com' }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
    configurations.all {
       resolutionStrategy {
         eachDependency { DependencyResolveDetails details ->
           if (details.requested.group == 'com.facebook.react' && details.requested.name == 'react-native') {
             details.useVersion "0.49.5" // Your real React Native version here
           }
         }
         force 'com.facebook.android:facebook-android-sdk:4.22.1'
         force 'com.facebook.android:audience-network-sdk:4.26.1'
       }
    }
}

And full android/app/build.gradle:

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.2'

    defaultConfig {
        applicationId "com.myapp"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 50
        versionName "1.11.11"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
        multiDexEnabled true
    }
    dexOptions {
        jumboMode = true
        javaMaxHeapSize "4g"
    }
    signingConfigs {
        release {
            ....
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a": 1, "x86": 2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile 'com.android.support:appcompat-v7:23+'

    compile project(':react-native-fetch-blob')
    compile 'com.android.support:multidex:1.0.1'
    compile project(':react-native-billing')
    compile project(':bugsnag-react-native')
    compile project(':react-native-admob')
    compile fileTree(dir: "libs", include: ["*.jar"])

    compile project(':react-native-fbsdk')
    compile project(':react-native-code-push')
    compile project(':react-native-device-info')
    compile project(':react-native-config')
    compile project(':react-native-fast-image')
    compile project(':react-native-camera')
    compile project(':react-native-google-analytics-bridge')
    compile project(':react-native-vector-icons')

    compile(project(":react-native-google-signin")) {
        exclude group: "com.google.android.gms" // very important
    }

    compile 'com.google.android.gms:play-services-auth:11.6.0'
    compile 'com.google.firebase:firebase-appindexing:11.6.0'

    compile 'com.facebook.android:facebook-android-sdk:4.22.1'
    compile 'com.facebook.android:audience-network-sdk:4.26.1'
    compile 'com.google.ads.mediation:facebook:4.26.1.0'

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

Body:
My solution was to update all these:

gradle to 3.01
gradle wrapper to 4.1
compilesdkversion to 26
buildtoolsversion to 26.02
com.android.support:appcompat-v7 to 26+
com.facebook.android:facebook-android-sdk:4.28.0

and my app builds successfully


问:
How can I detect ScrollView is scrolling
I know that this question have been asked before and i have gone through them but they didnt solve my problem.

I have ScrollView with one LinearLayout with imageview. And i have used ontouchListner to imageview to give them click effect like this

```<code>switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            view.getBackground().setColorFilter(0xCCCDDC39, PorterDuff.Mode.SRC_ATOP);
            view.invalidate();
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            view.getBackground().clearColorFilter();
            view.invalidate();
            startActivity(view.getId());
            break;
}
</code>```

But the problem is whenever i scroll ontouchlistner is called of imageview and image gets clicked .I dont want this whenever i am scrolling , Because this does not allow me to scroll. Please help

答:
a sure short asnwer

```<code>scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                    int x = scrollY - oldScrollY;
                    if (x > 0) {
                        //scroll up
                    } else if (x < 0) {
                        //scroll down
                    } else {

                    }

        }
    });
</code>```

Body:
I know that this question have been asked before and i have gone through them but they didnt solve my problem.

I have ScrollView with one LinearLayout with imageview. And i have used ontouchListner to imageview to give them click effect like this

switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            view.getBackground().setColorFilter(0xCCCDDC39, PorterDuff.Mode.SRC_ATOP);
            view.invalidate();
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            view.getBackground().clearColorFilter();
            view.invalidate();
            startActivity(view.getId());
            break;
}

But the problem is whenever i scroll ontouchlistner is called of imageview and image gets clicked .I dont want this whenever i am scrolling , Because this does not allow me to scroll. Please help

Body:
a sure short asnwer

scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                    int x = scrollY - oldScrollY;
                    if (x > 0) {
                        //scroll up
                    } else if (x < 0) {
                        //scroll down
                    } else {

                    }

        }
    });


问:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the import line in main.js

I've got the following files:

assets/js/menu.module.js

```<code>'use strict';

export default class Menu
{ ... }
</code>```

assets/js/main.js

```<code>import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});
</code>```

index.html

```<code><script type="module" src="assets/js/menu.module.js"></script>
<script src="assets/js/main.js">
</code>```

Note that these are only the relevant lines of code.

Using the

答:
As @Bergi mentioned in the comment, adding type="module" to the main.js import line in the HTML solved the issue. All is working now. I.e.

```<code><script type="module" src="assets/js/main.js">
</code>```

Thanks to all of you who responded and tried to help.

Body:
For a personal project, I'm trying to use ES6 import to write cleaner code. As first test, I'm writing an object that should generate a menu. The whole code is working when I'm directly loading up the class, yet when using the import and export in ES6, it gives an "Uncaught SyntaxError: Unexpected identifier" error on the import line in main.js

I've got the following files:

assets/js/menu.module.js

'use strict';

export default class Menu
{ ... }

assets/js/main.js

import Menu from "./menu.module.js";

window.addEventListener('DOMContentLoaded', () => {
    const menu = new Menu();
});

index.html

Body:
As @Bergi mentioned in the comment, adding type="module" to the main.js import line in the HTML solved the issue. All is working now. I.e.

<script type="module" src="assets/js/main.js">

Thanks to all of you who responded and tried to help.


问:
How to use left join like right join in Doctrine
In Doctrine there is no right join. You can use a left join like a right join but I can't figure it out for my example.

I have an entity in Doctrine which has a one-to-one relationship with itself called "parent".
I am trying to get all entities and their children (if they exist) with no duplicates.

With a right join this is simple because I can say:

```<code>SELECT parent.*, child.*
FROM table child
RIGHT JOIN table parent ON parent.id = child.parent_id
WHERE parent.parent_id is null;
</code>```

But using a left join I am returned results that I cannot figure out how to filter with the where clause.

How can I use a left join to get a right join in Doctrine?

I can change the ordering of tables but I am using Doctrine so the relationship does child->parent.

My Entity:

```<code>/**
 * @Entity
 * @Table(name="entity")
 */
class Entity
{
...
/**
 * @OneToOne(
 *     targetEntity="Entity",
 *     fetch="EAGER"
 * )
 * @JoinColumn(name="parent_id", referencedColumnName="id")
 */
private $parent;
...
}
</code>```

My Doctrine select statement:

```<code>$em->createQueryBuilder()
->select(array('child', 'parent'))
->from('Entity', 'child')
->leftjoin('child.parent', 'parent')
->orderBy('parent.id','asc')
->getQuery()
->execute();
</code>```

I am not sure how and if I can switch the ordering of tables. I also tried creating another relationship from the entity to itself (like I did parent) but called it "child". But when I updated the database with the new schema Doctrine threw errors.

SQL left join and results:

```<code>SELECT child.id, child.changed_timestamp, child.parent_entity_id, parent.id,
  parent.changed_timestamp, parent.parent_entity_id
FROM content child
LEFT JOIN content parent ON child.parent_entity_id = parent.id
ORDER BY parent.id ASC

child_id    child_timestamp parent_entity_id    parent_id   parent_timestamp    parent_entity_id
1           8/16/12 20:29   NULL                NULL        NULL                NULL
7           9/20/12 16:07   NULL                NULL        NULL                NULL
8           8/17/12 16:08   NULL                NULL        NULL                NULL
9           8/17/12 20:44   NULL                NULL        NULL                NULL
10          8/17/12 21:03   NULL                NULL        NULL                NULL
11          8/17/12 21:17   NULL                NULL        NULL                NULL
194         9/19/12 9:58    NULL                NULL        NULL                NULL
195         9/20/12 10:38   NULL                NULL        NULL                NULL
196         9/19/12 11:58   NULL                NULL        NULL                NULL
197         NULL            196                 196         9/19/12 11:58       NULL
200         9/20/12 16:02   1                   1           8/16/12 20:29       NULL
202         9/20/12 16:35   NULL                NULL        NULL                NULL
204         9/21/12 8:41    NULL                NULL        NULL                NULL
206         NULL            204                 204         9/21/12 8:41        NULL
</code>```

SQL right join and results:

```<code>SELECT child.id, child.changed_timestamp, child.parent_entity_id, parent.id,
 parent.changed_timestamp, parent.parent_entity_id
FROM content child
RIGHT JOIN content parent ON child.parent_entity_id = parent.id
WHERE parent.parent_entity_id is null
ORDER BY parent.id ASC

child_id    child_timestamp parent_entity_id    parent_id   parent_timestamp    parent_entity_id
200         9/20/12 16:02   1                   1           8/16/12 20:29       NULL
NULL        NULL            NULL                7           9/20/12 16:07       NULL
NULL        NULL            NULL                8           8/17/12 16:08       NULL
NULL        NULL            NULL                9           8/17/12 20:44       NULL
NULL        NULL            NULL                10          8/17/12 21:03       NULL
NULL        NULL            NULL                11          8/17/12 21:17       NULL
NULL        NULL            NULL                194         9/19/12 9:58        NULL
NULL        NULL            NULL                195         9/20/12 10:38       NULL
197         NULL            196                 196         9/19/12 11:58       NULL
NULL        NULL            NULL                202         9/20/12 16:35       NULL
206         NULL            204                 204         9/21/12 8:41        NULL
</code>```

答:
These two statements are equivalent:

```<code>SELECT parent.*, child.*
FROM table child
RIGHT JOIN table parent ON parent.id = child.parent_id
WHERE parent.parent_id is null;

SELECT parent.*, child.*
FROM table parent
LEFT JOIN table child ON child.parent_id = parent.id
WHERE parent.parent_id is null;
</code>```

I never use RIGHT JOIN. I think it is only included in SQL for completeness.

Body:
In Doctrine there is no right join. You can use a left join like a right join but I can't figure it out for my example.

I have an entity in Doctrine which has a one-to-one relationship with itself called "parent".
I am trying to get all entities and their children (if they exist) with no duplicates.

With a right join this is simple because I can say:

SELECT parent.*, child.*
FROM table child
RIGHT JOIN table parent ON parent.id = child.parent_id
WHERE parent.parent_id is null;

But using a left join I am returned results that I cannot figure out how to filter with the where clause.

How can I use a left join to get a right join in Doctrine?

I can change the ordering of tables but I am using Doctrine so the relationship does child->parent.

My Entity:

/**
 * @Entity
 * @Table(name="entity")
 */
class Entity
{
...
/**
 * @OneToOne(
 *     targetEntity="Entity",
 *     fetch="EAGER"
 * )
 * @JoinColumn(name="parent_id", referencedColumnName="id")
 */
private $parent;
...
}

My Doctrine select statement:

$em->createQueryBuilder()
->select(array('child', 'parent'))
->from('Entity', 'child')
->leftjoin('child.parent', 'parent')
->orderBy('parent.id','asc')
->getQuery()
->execute();

I am not sure how and if I can switch the ordering of tables. I also tried creating another relationship from the entity to itself (like I did parent) but called it "child". But when I updated the database with the new schema Doctrine threw errors.

SQL left join and results:

SELECT child.id, child.changed_timestamp, child.parent_entity_id, parent.id,
  parent.changed_timestamp, parent.parent_entity_id
FROM content child
LEFT JOIN content parent ON child.parent_entity_id = parent.id
ORDER BY parent.id ASC

child_id    child_timestamp parent_entity_id    parent_id   parent_timestamp    parent_entity_id
1           8/16/12 20:29   NULL                NULL        NULL                NULL
7           9/20/12 16:07   NULL                NULL        NULL                NULL
8           8/17/12 16:08   NULL                NULL        NULL                NULL
9           8/17/12 20:44   NULL                NULL        NULL                NULL
10          8/17/12 21:03   NULL                NULL        NULL                NULL
11          8/17/12 21:17   NULL                NULL        NULL                NULL
194         9/19/12 9:58    NULL                NULL        NULL                NULL
195         9/20/12 10:38   NULL                NULL        NULL                NULL
196         9/19/12 11:58   NULL                NULL        NULL                NULL
197         NULL            196                 196         9/19/12 11:58       NULL
200         9/20/12 16:02   1                   1           8/16/12 20:29       NULL
202         9/20/12 16:35   NULL                NULL        NULL                NULL
204         9/21/12 8:41    NULL                NULL        NULL                NULL
206         NULL            204                 204         9/21/12 8:41        NULL

SQL right join and results:

SELECT child.id, child.changed_timestamp, child.parent_entity_id, parent.id,
 parent.changed_timestamp, parent.parent_entity_id
FROM content child
RIGHT JOIN content parent ON child.parent_entity_id = parent.id
WHERE parent.parent_entity_id is null
ORDER BY parent.id ASC

child_id    child_timestamp parent_entity_id    parent_id   parent_timestamp    parent_entity_id
200         9/20/12 16:02   1                   1           8/16/12 20:29       NULL
NULL        NULL            NULL                7           9/20/12 16:07       NULL
NULL        NULL            NULL                8           8/17/12 16:08       NULL
NULL        NULL            NULL                9           8/17/12 20:44       NULL
NULL        NULL            NULL                10          8/17/12 21:03       NULL
NULL        NULL            NULL                11          8/17/12 21:17       NULL
NULL        NULL            NULL                194         9/19/12 9:58        NULL
NULL        NULL            NULL                195         9/20/12 10:38       NULL
197         NULL            196                 196         9/19/12 11:58       NULL
NULL        NULL            NULL                202         9/20/12 16:35       NULL
206         NULL            204                 204         9/21/12 8:41        NULL

Body:
These two statements are equivalent:

SELECT parent.*, child.*
FROM table child
RIGHT JOIN table parent ON parent.id = child.parent_id
WHERE parent.parent_id is null;

SELECT parent.*, child.*
FROM table parent
LEFT JOIN table child ON child.parent_id = parent.id
WHERE parent.parent_id is null;

I never use RIGHT JOIN. I think it is only included in SQL for completeness.


问:
mongodb append to an existing object
here is my document, and I want to add a new field to it:

```<code>{
email_address: 'webmaster@example.com',
password: 'random_password',
first_name: 'John',
last_name: 'Doe',
website: {
    main_title: 'My Blog Website',
    main_url: 'http://www.example.com'
    }
}
</code>```

currently i am doing:

```<code>db.test.update({"email_address": "webmaster@example.com"},
{$set: {"website" : {"registrar": "namecheap"}}})
</code>```

this erases the other fields inside website and just adds this new registrar field. how can I append to it?

答:
You need to use dot-notation to set value to particular field of the sub-document, instead of setting the whole sub-document:</p>

```<code>db.test.update(
    { "email_address": "webmaster@example.com" },
    { $set: { "website.registrar" : "namecheap" } }
)
</code>```

Title: mongodb append to an existing object

Body:
here is my document, and I want to add a new field to it:

{
email_address: 'webmaster@example.com',
password: 'random_password',
first_name: 'John',
last_name: 'Doe',
website: {
    main_title: 'My Blog Website',
    main_url: 'http://www.example.com'
    }
}

currently i am doing:

db.test.update({"email_address": "webmaster@example.com"},
{$set: {"website" : {"registrar": "namecheap"}}})

this erases the other fields inside website and just adds this new registrar field. how can I append to it?

Body:
You need to use dot-notation to set value to particular field of the sub-document, instead of setting the whole sub-document:

db.test.update(
    { "email_address": "webmaster@example.com" },
    { $set: { "website.registrar" : "namecheap" } }
)


问:
MySQL - Error #1064 in LEFT JOIN
I am currently trying to get the data formatted using only MySQL query. I do not want to manipulate it using a programming language. All the operations are done only on one table.

Here is my query:

```<code>    SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_a FROM users a
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "good"

    LEFT JOIN (SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_b FROM users
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "bad") AS b
    ON b.date = a.date;
</code>```

The output should be like:

```
date           users_a           users_b
2017-12-01     17                20
2017-12-02     4                 9
```

The two queries give accurate results if they are executed separately, and I just want the data to be in one table. However, I get the following error:

```
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN (SELECT DATE(datetime) AS date, COUNT(`id`) AS users_b FROM ' at line 2
```

答:
Try this</p>

```<code>SELECT DATE(datetime_column) date, SUM(CASE WHEN rank = "good" THEN 1 END) users_a, SUM(CASE WHEN rank = "bad" THEN 1 END) users_b
FROM users
WHERE datetime_column>= '2017-12-01'
GROUP BY DATE(datetime_column)
</code>```

Title: MySQL - Error #1064 in LEFT JOIN

Body:
I am currently trying to get the data formatted using only MySQL query. I do not want to manipulate it using a programming language. All the operations are done only on one table.

Here is my query:

    SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_a FROM users a
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "good"

    LEFT JOIN (SELECT DATE(datetime_column) AS date, COUNT(`id`) AS users_b FROM users
    WHERE datetime_column >= '2017-12-01' GROUP BY DATE(datetime_column), rank HAVING rank = "bad") AS b
    ON b.date = a.date;

The output should be like:

date           users_a           users_b
2017-12-01     17                20
2017-12-02     4                 9

The two queries give accurate results if they are executed separately, and I just want the data to be in one table. However, I get the following error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN (SELECT DATE(datetime) AS date, COUNT(`id`) AS users_b FROM ' at line 2

Body:
Try this

SELECT DATE(datetime_column) date, SUM(CASE WHEN rank = "good" THEN 1 END) users_a, SUM(CASE WHEN rank = "bad" THEN 1 END) users_b
FROM users
WHERE datetime_column>= '2017-12-01'
GROUP BY DATE(datetime_column)


问:
SQL 2 HAVING syntax
My professor is teaching sql 2, and used an statement like the code below into a query:

```<code>HAVING SUM(column) > subselect
</code>```

Where subselect is something like SELECT AVG(column) FROM ...

This subselect returns only one value, but I could not understand how is it possible to compare a function (the sum) with a subselect. The subselect should return a table, right? Then how is it possible to compare a table with a value? That did not make sense to me.

Thanks in advance.

答:
SQL has a concept of scalar subqueries.  These are subqueries that return exactly one column and at most one row.  Scalar subqueries can be used in almost all cases where a single value ("scalar") can be used.

If the scalar subquery returns no rows, then the value is treated as NULL.

(I should add that some databases support tuples.  A tuple is a set of scalar values that is treated as a single value.  In such databases "scalar" subqueries can return more than one value, but these are converted to a tuple.  This is not relevant to the question being asked; tuples are just another example of a "single" value.)

Title: SQL 2 HAVING syntax

Body:
My professor is teaching sql 2, and used an statement like the code below into a query:

HAVING SUM(column) > subselect

Where subselect is something like SELECT AVG(column) FROM ...

This subselect returns only one value, but I could not understand how is it possible to compare a function (the sum) with a subselect. The subselect should return a table, right? Then how is it possible to compare a table with a value? That did not make sense to me.

Thanks in advance.


问:
How to computed and add a new column in SQL
I have two tables

[Table_1] - Amount of money in a specific currency.

```<code>Currency  | Amount
USD       |  243
USD       |  212
USD       |  432
EUR       |  578
EUR       |  112
EUR       |  578
GBP       |  965
GBP       |  309
</code>```

And [Table_2] - Exchange rate EUR and GBP to USD

```<code>Cur |   FX
GBP | 1.43
EUR | 1.18
USD | 1
</code>```

I need to permanently add a new column [Amount in USD] into [Table_1] which converts all currencies into USD. Basically I need the corresponding currencies to be multiplied by the exchange rates given in [Table_2]. The final result should look like this.

```<code>Currency  | Amount  |Amount in USD
USD       |   243   |   243
USD       |   212   |   212
USD       |   432   |   432
EUR       |   578   |   682
EUR       |   112   |   132
EUR       |   578   |   682
GBP       |   965   |   1380
GBP       |   309   |   442
</code>```

I would appreciate if someone could help out. Thanks in advance.

答:
Two solutions for you. One using a VIEW, the other a computed column (which is what you stated you wanted) by means of a scalar function:

```<code>--Create sample data
CREATE TABLE ExchangeRate (Currency char(3), FX decimal(8,2));
INSERT INTO ExchangeRate
VALUES ('GBP',1.43),
       ('EUR',1.18),
       ('USD',1);
GO

CREATE TABLE TransactionList (Currency char(3), Amount decimal(12,2));

INSERT INTO TransactionList
VALUES ('GBP',100),
       ('EUR', 100),
       ('USD',100);
GO
--View Solution
CREATE VIEW ValuesInUSD AS

    SELECT TL.Currency, TL.Amount, TL.Amount * ER.FX AS USDAmount
    FROM TransactionList TL
         JOIN ExchangeRate ER ON TL.Currency = ER.Currency;
GO
--Check results
SELECT *
FROM ValuesInUSD;

GO
--Function Solution
--Create Function
CREATE FUNCTION ExchangeToUSD (@Currency char(3), @Value decimal(12,2))
RETURNS DECIMAL(12,2)
AS BEGIN
    DECLARE @USD decimal(12,2);

    SELECT @USD =  @Value * FX
    FROM ExchangeRate
    WHERE Currency = @Currency;

    RETURN @USD;

END
GO
--Add Computed Column
ALTER TABLE TransactionList ADD ValueInUSD AS (dbo.ExchangeToUSD(Currency, Amount));
GO
--Check results
SELECT *
FROM TransactionList;
GO
--Clean up
DROP VIEW ValuesInUSD;
DROP TABLE TransactionList;
DROP FUNCTION ExchangeToUSD;
DROP TABLE ExchangeRate;
GO
</code>```

Body:
I have two tables

[Table_1] - Amount of money in a specific currency.

Currency  | Amount
USD       |  243
USD       |  212
USD       |  432
EUR       |  578
EUR       |  112
EUR       |  578
GBP       |  965
GBP       |  309

And [Table_2] - Exchange rate EUR and GBP to USD

Cur |   FX
GBP | 1.43
EUR | 1.18
USD | 1

I need to permanently add a new column [Amount in USD] into [Table_1] which converts all currencies into USD. Basically I need the corresponding currencies to be multiplied by the exchange rates given in [Table_2]. The final result should look like this.

Currency  | Amount  |Amount in USD
USD       |   243   |   243
USD       |   212   |   212
USD       |   432   |   432
EUR       |   578   |   682
EUR       |   112   |   132
EUR       |   578   |   682
GBP       |   965   |   1380
GBP       |   309   |   442

I would appreciate if someone could help out. Thanks in advance.

Body:
Two solutions for you. One using a VIEW, the other a computed column (which is what you stated you wanted) by means of a scalar function:

--Create sample data
CREATE TABLE ExchangeRate (Currency char(3), FX decimal(8,2));
INSERT INTO ExchangeRate
VALUES ('GBP',1.43),
       ('EUR',1.18),
       ('USD',1);
GO

CREATE TABLE TransactionList (Currency char(3), Amount decimal(12,2));

INSERT INTO TransactionList
VALUES ('GBP',100),
       ('EUR', 100),
       ('USD',100);
GO
--View Solution
CREATE VIEW ValuesInUSD AS

    SELECT TL.Currency, TL.Amount, TL.Amount * ER.FX AS USDAmount
    FROM TransactionList TL
         JOIN ExchangeRate ER ON TL.Currency = ER.Currency;
GO
--Check results
SELECT *
FROM ValuesInUSD;

GO
--Function Solution
--Create Function
CREATE FUNCTION ExchangeToUSD (@Currency char(3), @Value decimal(12,2))
RETURNS DECIMAL(12,2)
AS BEGIN
    DECLARE @USD decimal(12,2);

    SELECT @USD =  @Value * FX
    FROM ExchangeRate
    WHERE Currency = @Currency;

    RETURN @USD;

END
GO
--Add Computed Column
ALTER TABLE TransactionList ADD ValueInUSD AS (dbo.ExchangeToUSD(Currency, Amount));
GO
--Check results
SELECT *
FROM TransactionList;
GO
--Clean up
DROP VIEW ValuesInUSD;
DROP TABLE TransactionList;
DROP FUNCTION ExchangeToUSD;
DROP TABLE ExchangeRate;
GO


问:
Where can I find discussion board newform.aspx page to modify?
I have to modify text in discussion board new post page. Now it is showing "Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval."

I have to append some text to this message. I am trying to find discussion board newform.aspx page to modify. Please let me know where can I get that?

答:
On the file system it will be here:

$sphome / "Name of your discussion board" (this will be a folder) / Forms / newform.aspx