问:
how to match statement that combine word,/,digits like /dev/home/hello-world
i want to match following statement in regex:

```<code>/
/dev/shm
/var/lib/snap/hello-world/27
</code>```

any idea?
and this is my last try:

```<code>\/((\w+)|(\/\w+-\w+))+
</code>```

but it seems that, dash-statements treat like a seperate part.

答:
You can use this regex using a negated character class:

```<code>^\/(?:[^/]*\/)*.*$
</code>```

RegEx Demo

RegEx Breakup:

^: Start

\/: Match literal /

(?:[^/]*\/)*: Match 0 or more groups of non-slash strings followed by a /

.*: Match anything after last/`

$: End

Body:
i want to match following statement in regex:

/
/dev/shm
/var/lib/snap/hello-world/27

any idea?
and this is my last try:

\/((\w+)|(\/\w+-\w+))+

but it seems that, dash-statements treat like a seperate part.

Body:
You can use this regex using a negated character class:

^\/(?:[^/]*\/)*.*$

RegEx Demo

RegEx Breakup:

^: Start

\/: Match literal /

(?:[^/]*\/)*: Match 0 or more groups of non-slash strings followed by a /

.*: Match anything after last/`

$: End


来源: stackexchange

问:
Hide navbar when scrolling, but do it so that it's not animated but naturally 'scrolled away'
so hiding the navbar when scrolling simply by adding a class with "top: -50px" for example is easy. However, it doesn't feel very natural. It would be so much nicer, if the navbar would be hiding through actual scrolling, so that the speed of the scrolling always fits. Instead of animating it away, I want to scroll the navbar away and back onscreen (instantly away and after a certain amount of pixels of scrolling up back onscreen again).

How would you approach this?

By the way, I don't really want to use any JQuery for this, I'm using Vue.

答:
Set the position of the navbar a fixed (or whatever you have currently) until a scroll event on the window passes a certain point, then make the navbar relative to the scrolling container.

See this example: https://jsfiddle.net/n97tu7nt/

The HTML

```<code><div id="main-container">
  <div class="nav" id="nav" style="position:fixed; height: 100px; background-color: blue; color: white; width:100%;">
    This is the Nav Bar <span id="pos"></span>
  </div>
  <div style="position:relative; top:130px;" id="container">
    <p>
      This is some text
    </p>
  ...
</code>```

The Javascript

```<code>var c = document.getElementById('nav');
var t = document.getElementById('container');
var p = document.getElementById('pos');

p.innerHTML = window.scrollY;

var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {

  p.innerHTML = scroll_pos;
  if (scroll_pos > 100) {
    c.style.position = 'relative';
    t.style.top = 0;
  }
}

// From https://developer.mozilla.org/en-US/docs/Web/Events/scroll
window.addEventListener('scroll', function(e) {

  last_known_scroll_position = window.scrollY;

  if (!ticking) {

    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });

    ticking = true;

  }

});
</code>```

It is very hacky, but shows the principle.

ContentLicense: CC BY-SA 3.0

Body:
Set the position of the navbar a fixed (or whatever you have currently) until a scroll event on the window passes a certain point, then make the navbar relative to the scrolling container.

See this example: https://jsfiddle.net/n97tu7nt/

The HTML

<div id="main-container">
  <div class="nav" id="nav" style="position:fixed; height: 100px; background-color: blue; color: white; width:100%;">
    This is the Nav Bar <span id="pos"></span>
  </div>
  <div style="position:relative; top:130px;" id="container">
    <p>
      This is some text
    </p>
  ...

The Javascript

var c = document.getElementById('nav');
var t = document.getElementById('container');
var p = document.getElementById('pos');

p.innerHTML = window.scrollY;

var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {

  p.innerHTML = scroll_pos;
  if (scroll_pos > 100) {
    c.style.position = 'relative';
    t.style.top = 0;
  }
}

// From https://developer.mozilla.org/en-US/docs/Web/Events/scroll
window.addEventListener('scroll', function(e) {

  last_known_scroll_position = window.scrollY;

  if (!ticking) {

    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });

    ticking = true;

  }

});

It is very hacky, but shows the principle.


问:
Is there are way to get rowIDs of first occurrences of value from codechunks?
Is there a way to get that realized?

example:(distribution is random)

```<code>ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x
</code>```

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to get that realized?

example:(distribution is random)

ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

Body:
Or a base R solution:

df <- read.table(text = "
ID    size
1      1
2      5
3      6
4      7
5      8
0      2
0      5
0      7
0      9
4      0
5      3
0      4
0      5
0      1
0      4
4      7
5      9
0      3
0      5
0      6
0      9
4      9
5      4", header = T)

ids <- which(df$ID == 0)

temp  <- c(TRUE, (diff(ids) != 1))

df$size[ids[temp]]
#[1] 2 4 3


问:
Returning Current URL from nested function - Chrome Extension
I'm trying to make a chrome extension that gets the URL of the currently selected tab, but I'm running into a problem where I can't get the variable that the URL is stored in to return.

I've tried several things already but this is the code that I'm expecting to work:

```<code>function getStream() {
    alert(getLinking());
}

function getLinking() {
    chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        },
        function getURL(tabs) {
            var URL = tabs[0].url;
            return URL;
        }
    );
    return getURL();
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('start').addEventListener('click', getStream);
});
</code>```

However it doesn't actually return anything so the alert doesn't show. Please note that it's very important for me to return the variable URL so I can use it back in the getStream function, just adding in the alert in the getURL function isn't what I'm looking for.

If anyone could help me that would be amazing, I'm not too familiar with javascript yet and I'm especially unfamiliar with chrome extension so every bit of advice could help.

答:
Method chrome.tabs.query is asynchronous, so it requires a callback to return results.

When you are working with async calls, you can handle results with any:

callbacks

Promises

async/await

Please check this question: How do I return the response from an asynchronous call?

According to your code, the simplest solution will be:

function getStream() {
    getLinking(function(URL) { // passing a callback
        alert(URL)
    });
}

function getLinking(callback) { // callback - is a function that will be called when async call finished
    chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        },function(tabs) {
            callback(tabs[0].url); // run callback with a result
        }
    );
    // do not need to return anything
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('start').addEventListener('click', getStream);
});
```

Body:
I'm trying to make a chrome extension that gets the URL of the currently selected tab, but I'm running into a problem where I can't get the variable that the URL is stored in to return.

I've tried several things already but this is the code that I'm expecting to work:

function getStream() {
    alert(getLinking());
}

function getLinking() {
    chrome.tabs.query({
            'active': true,
            'windowId': chrome.windows.WINDOW_ID_CURRENT
        },
        function getURL(tabs) {
            var URL = tabs[0].url;
            return URL;
        }
    );
    return getURL();
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('start').addEventListener('click', getStream);
});

However it doesn't actually return anything so the alert doesn't show. Please note that it's very important for me to return the variable URL so I can use it back in the getStream function, just adding in the alert in the getURL function isn't what I'm looking for.

If anyone could help me that would be amazing, I'm not too familiar with javascript yet and I'm especially unfamiliar with chrome extension so every bit of advice could help.


问:
How to split string using pattern matching?
I have a string like "123-#-#-abc-user-#-#-abcpassword-#-#-123456", i need to split this string with pattern "-#-#-" to create an array. I used the following code to do this

```<code>    char buf[5000];
    strcpy(buf, "123-#-#-abc-user-#-#-abcpassword-#-#-123456");
    int i = 0;
    char *p = strtok (buf, "-#-#-");
    char *array[5000];

    int items = 0;
    while (p != NULL)
    {
        items++;
        array[i++] = p;
        p = strtok (NULL, "-#-#-");
    }
</code>```

But the result isn't getting for "123-#-#-abc-user-#-#-abcpassword-#-#-123456" due to the hyphen in the "abc-user". What i am expecting is that array[0] has the 123, array[1] has abc-user, array[2] as abcpassword etc. Is there any other method to split to array with the exact pattern ?

答:
strtok() here will not produce the exact output you expect. Check the details, C11, chapter §7.24.5.8

A sequence of calls to the strtok function breaks the string pointed to by s1 into a
  sequence of tokens, each of which is delimited by a character from the string pointed to
  by s2. [...]

So, presence of any character of the whole delimiter string will cause tokenization.

You need to look for strstr() which searches for a sub string inside a bigger string. Once again, from C11, chapter 7.24.5.7

```<code>char *strstr(const char *s1, const char *s2);
</code>```

The strstr function locates the first occurrence in the string pointed to by s1 of the
  sequence of characters (excluding the terminating null character) in the string pointed to
  by s2.

and

The strstr function returns a pointer to the located string, or a null pointer if the string
  is not found. [...]

So you can

use the function call,

take the non-null returned pointer

perform pointer arithmetic to reach to the next token you want.

Body:
I have a string like "123-#-#-abc-user-#-#-abcpassword-#-#-123456", i need to split this string with pattern "-#-#-" to create an array. I used the following code to do this

    char buf[5000];
    strcpy(buf, "123-#-#-abc-user-#-#-abcpassword-#-#-123456");
    int i = 0;
    char *p = strtok (buf, "-#-#-");
    char *array[5000];

    int items = 0;
    while (p != NULL)
    {
        items++;
        array[i++] = p;
        p = strtok (NULL, "-#-#-");
    }

But the result isn't getting for "123-#-#-abc-user-#-#-abcpassword-#-#-123456" due to the hyphen in the "abc-user". What i am expecting is that array[0] has the 123, array[1] has abc-user, array[2] as abcpassword etc. Is there any other method to split to array with the exact pattern ?

Body:
strtok() here will not produce the exact output you expect. Check the details, C11, chapter §7.24.5.8

A sequence of calls to the strtok function breaks the string pointed to by s1 into a
  sequence of tokens, each of which is delimited by a character from the string pointed to
  by s2. [...]

So, presence of any character of the whole delimiter string will cause tokenization.

You need to look for strstr() which searches for a sub string inside a bigger string. Once again, from C11, chapter 7.24.5.7

char *strstr(const char *s1, const char *s2);

The strstr function locates the first occurrence in the string pointed to by s1 of the
  sequence of characters (excluding the terminating null character) in the string pointed to
  by s2.

and

The strstr function returns a pointer to the located string, or a null pointer if the string
  is not found. [...]

So you can

use the function call,

take the non-null returned pointer

perform pointer arithmetic to reach to the next token you want.


问:
NSTextView not responding in an app without dock icon
I have a menulet app with an NSTextView in it. I don't want the app to appear in the dock, so I wrote

```<code><key>LSUIElement</key>
<true/>
</code>```

in the Info.plist file.

But if this option is enabled, somehow an NSTextView in the menu stops responding at all.

How can I make it respond again? Maybe there are any other ways to hide the dock icon?

Thank you!

IMPORTANT UPDATE: This bug has been spotted only on Mac OS 10.6 and higher

答:
The documentation states that keyboard events are not supported in views that are attached to a menu item (see Application Menu and Pop-up List Programming Topics).

That said, I had no problem creating a minimal sample app without Dock icon and a text view embedded in a status item's menu, so your problem is likely somewhere else. You can download my sample app here.

ContentLicense: CC BY-SA 2.5

Body:
I have a menulet app with an NSTextView in it. I don't want the app to appear in the dock, so I wrote

<key>LSUIElement</key>
<true/>

in the Info.plist file.

But if this option is enabled, somehow an NSTextView in the menu stops responding at all.

How can I make it respond again? Maybe there are any other ways to hide the dock icon?

Thank you!

IMPORTANT UPDATE: This bug has been spotted only on Mac OS 10.6 and higher


问:
How to overcome app not installed error when building from Android Studio 3.0?
For giving build for a debug Android app from Android Studio 3.0, it’s not installing in Mobile having Marshmallow and up (in Lollipop not tested).

I have used many solutions from Stack overflow but it’s still not working.

It’s always showing App Not Installed on mobile phone.

答:
First try to generate the debug apk by below steps:

Goto Run

Edit Configurations

select + icon on the left side

Select Gradle

Click the Configuration tab if it is not selected in the right side

In Gradle project add your app as  a gradle project

From the tasks select/set "assemble"

Press ok

Now run that configuration.
you will have the debug apk ready in build/outputs/apk/app-debug.apk.
Now install that apk in any device. It should work.


问:
Apache POI error message displayed for RETURN_BLANK_AS_NULL
I have code for witting data in Excel file whenever cell founds empty. However when i type below code it gives error. :

```<code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import Config.Constants;

public class ExcelUtils {

 private static XSSFSheet ExcelWSheet;
 private static XSSFWorkbook ExcelWBook;
 private static XSSFCell Cell;
 private static XSSFRow Row, xRow;

 public static void setExcelFile(String Path, String SheetName) throws Exception {
  // TODO Auto-generated method stub
  FileInputStream ExcelFile = new FileInputStream(Path);
  ExcelWBook = new XSSFWorkbook(ExcelFile);
  // ExcelWSheet = ExcelWBook.getSheet(SheetName);
 }

 public static String getCellData(int RowNum, int ColNum, String SheetName) throws Exception {
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  try {

   Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
   String CellData = Cell.getStringCellValue();
   return CellData;
  } catch (Exception e) {
   return "";
  }
 }
 public static int getRowCount(String SheetName) {
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  int number = ExcelWSheet.getLastRowNum() + 1;
  return number;
 }

 //This method is to get the Row number of the test case
 //This methods takes three arguments(Test Case name , Column Number & Sheet name)
 public static int getRowContains(String sTestCaseName, int colNum, String SheetName) throws Exception {
  int i;
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  int rowCount = ExcelUtils.getRowCount(SheetName);
  for (i = 0; i < rowCount; i++) {
   if (ExcelUtils.getCellData(i, colNum, SheetName).equalsIgnoreCase(sTestCaseName)) {
    break;
   }
  }
  return i;
 }

 //This method is to get the count of the test steps of test case
 //This method takes three arguments (Sheet name, Test Case Id & Test case row number)
 public static int getTestStepsCount(String SheetName, String sTestCaseID, int iTestCaseStart) throws Exception {
  for (int i = iTestCaseStart; i <= ExcelUtils.getRowCount(SheetName); i++) {
   if (!sTestCaseID.equals(ExcelUtils.getCellData(i, Constants.Col_TestCaseID, SheetName))) {
    int number = i;
    return number;
   }
  }
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  int number = ExcelWSheet.getLastRowNum() + 1;
  return number;
 }

 @SuppressWarnings("static-access")
 public static void setCellData(String Result, int RowNum, int ColNum, String SheetName) throws Exception {
  try {

   ExcelWSheet = ExcelWBook.getSheet(SheetName);
   Row = ExcelWSheet.getRow(RowNum);
   xRow = ExcelWSheet.getRow(RowNum);
   // Row.RETURN_BLANK_AS_NULL;

   //  ExcelWBook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);
   //Cell = Row.getCell(ColNum, Blank);
   Cell = xRow.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

   if (Cell == null) {
    Cell = Row.createCell(ColNum);
    Cell.setCellValue(Result);
   } else {
    Cell.setCellValue(Result);
   }
   // Constant variables Test Data path and Test Data file name
   FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData);
   //ExcelWBook.write(fileOut);
   ExcelWBook.write(fileOut);
   //fileOut.flush();
   fileOut.close();
   ExcelWBook = new XSSFWorkbook(new FileInputStream(Constants.Path_TestData));
  } catch (Exception e) {
   DriverScript.bResult = false;
  }
 }
}
</code>```

Error message:

MissingCellPolicy cannot be resolved or is not a field

Whereas when i use "Row.RETURN_BLANK_AS_NULL" it says method is deprecated. Can i have some solution for this both problems to run my code succesfully?

答:
Cell has many types and you should get value according to its type, getStringCellValue() is not enough

I often use this code to get

```<code>switch (cell.getCellTypeEnum()) {
    case FORMULA:
        CellValue cellValue = evaluator.evaluate(cell);
        switch (cellValue.getCellTypeEnum()) {
            case BOOLEAN:
                value = Boolean.toString(cellValue.getBooleanValue());
                break;
            case NUMERIC:
                value = Double.toString(cellValue.getNumberValue());
                break;
            case STRING:
                value = cellValue.getStringValue();
                break;
        }
        break;
    case BOOLEAN:
        value = Boolean.toString(cell.getBooleanCellValue());
        break;
    case NUMERIC:
        value = Double.toString(cell.getNumericCellValue());
        break;
    default:
        value = cell.getStringCellValue();
        break;
}
</code>```

Body:
I have code for witting data in Excel file whenever cell founds empty. However when i type below code it gives error. :

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import Config.Constants;

public class ExcelUtils {

 private static XSSFSheet ExcelWSheet;
 private static XSSFWorkbook ExcelWBook;
 private static XSSFCell Cell;
 private static XSSFRow Row, xRow;

 public static void setExcelFile(String Path, String SheetName) throws Exception {
  // TODO Auto-generated method stub
  FileInputStream ExcelFile = new FileInputStream(Path);
  ExcelWBook = new XSSFWorkbook(ExcelFile);
  // ExcelWSheet = ExcelWBook.getSheet(SheetName);
 }

 public static String getCellData(int RowNum, int ColNum, String SheetName) throws Exception {
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  try {

   Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
   String CellData = Cell.getStringCellValue();
   return CellData;
  } catch (Exception e) {
   return "";
  }
 }
 public static int getRowCount(String SheetName) {
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  int number = ExcelWSheet.getLastRowNum() + 1;
  return number;
 }

 //This method is to get the Row number of the test case
 //This methods takes three arguments(Test Case name , Column Number & Sheet name)
 public static int getRowContains(String sTestCaseName, int colNum, String SheetName) throws Exception {
  int i;
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  int rowCount = ExcelUtils.getRowCount(SheetName);
  for (i = 0; i < rowCount; i++) {
   if (ExcelUtils.getCellData(i, colNum, SheetName).equalsIgnoreCase(sTestCaseName)) {
    break;
   }
  }
  return i;
 }

 //This method is to get the count of the test steps of test case
 //This method takes three arguments (Sheet name, Test Case Id & Test case row number)
 public static int getTestStepsCount(String SheetName, String sTestCaseID, int iTestCaseStart) throws Exception {
  for (int i = iTestCaseStart; i <= ExcelUtils.getRowCount(SheetName); i++) {
   if (!sTestCaseID.equals(ExcelUtils.getCellData(i, Constants.Col_TestCaseID, SheetName))) {
    int number = i;
    return number;
   }
  }
  ExcelWSheet = ExcelWBook.getSheet(SheetName);
  int number = ExcelWSheet.getLastRowNum() + 1;
  return number;
 }

 @SuppressWarnings("static-access")
 public static void setCellData(String Result, int RowNum, int ColNum, String SheetName) throws Exception {
  try {

   ExcelWSheet = ExcelWBook.getSheet(SheetName);
   Row = ExcelWSheet.getRow(RowNum);
   xRow = ExcelWSheet.getRow(RowNum);
   // Row.RETURN_BLANK_AS_NULL;

   //  ExcelWBook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);
   //Cell = Row.getCell(ColNum, Blank);
   Cell = xRow.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

   if (Cell == null) {
    Cell = Row.createCell(ColNum);
    Cell.setCellValue(Result);
   } else {
    Cell.setCellValue(Result);
   }
   // Constant variables Test Data path and Test Data file name
   FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData);
   //ExcelWBook.write(fileOut);
   ExcelWBook.write(fileOut);
   //fileOut.flush();
   fileOut.close();
   ExcelWBook = new XSSFWorkbook(new FileInputStream(Constants.Path_TestData));
  } catch (Exception e) {
   DriverScript.bResult = false;
  }
 }
}

Error message:

MissingCellPolicy cannot be resolved or is not a field

Whereas when i use "Row.RETURN_BLANK_AS_NULL" it says method is deprecated. Can i have some solution for this both problems to run my code succesfully?

Body:
Cell has many types and you should get value according to its type, getStringCellValue() is not enough

I often use this code to get

switch (cell.getCellTypeEnum()) {
    case FORMULA:
        CellValue cellValue = evaluator.evaluate(cell);
        switch (cellValue.getCellTypeEnum()) {
            case BOOLEAN:
                value = Boolean.toString(cellValue.getBooleanValue());
                break;
            case NUMERIC:
                value = Double.toString(cellValue.getNumberValue());
                break;
            case STRING:
                value = cellValue.getStringValue();
                break;
        }
        break;
    case BOOLEAN:
        value = Boolean.toString(cell.getBooleanCellValue());
        break;
    case NUMERIC:
        value = Double.toString(cell.getNumericCellValue());
        break;
    default:
        value = cell.getStringCellValue();
        break;
}


问:
How to Find Starting time of consuming data from a kafka topic by the consumer group
Is there any API we can use to find the starting time of consumer group started consuming from a Kafka topic?

I am using Kafka Version 0.11

答:
Kafka doesn't track this information so there's no API you can query to retrieve this data. However, there's a number of consumer group metrics you can monitor that should enable you to figure this out.

Also monitoring tools like Burrow should help you find this information.


问:
SQL: How to calculate correctly with any DATE_TIME and CURRENT_TIMESTAMP?
I have created a table where I listed some spare parts of my company.

The Table looks like this:

```<code>ID | Name | install_date | last_changed | order_nr. | WearStatus
----------
1  | "ABC" | **2017-11-08 10:34:40** | NULL | 123456 | **50**<br>
2  | "DEF" | **2017-11-08 10:34:40** | NULL | 654321 | **10**<br>
</code>```

.

.

I want to calculate the Future Date, where the spare Parts should be changed. For example:

I installed a Part on the 01. December and exactly 10 Days later on the 11. December this part has a Wear of 50%, then I know: It has 10 more Days left.

My calculation is according to the rule of three formula: Time = (100 * delta t) / Wear

I use the following SQL command:

```<code>SELECT ( (100*(CURRENT_TIMESTAMP - First_Usage) / Wear) + First_Usage) As 'Change_Date' FROM spare_parts
</code>```

And get the following Results:

If you see there are some crazy DATE_TIMES like 2017-19-41-43-19-31.

So my Question is now: How to format this "Numbers" to a useful DATE_TIME Format like YYYY-MM-DD hh:mm:ss ?

kind regards Toby

答:
MySQL olredy have date intervals functional. If in Wear is already days count, your variant is

```<code>SELECT DATE_ADD(First_Usage, INTERVAL Wear DAY) as 'Change_Date' FROM spare_parts;
</code>```

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

Body:
I have created a table where I listed some spare parts of my company.

The Table looks like this:

ID | Name | install_date | last_changed | order_nr. | WearStatus
----------
1  | "ABC" | **2017-11-08 10:34:40** | NULL | 123456 | **50**

2  | "DEF" | **2017-11-08 10:34:40** | NULL | 654321 | **10**

.

.

I want to calculate the Future Date, where the spare Parts should be changed. For example:

I installed a Part on the 01. December and exactly 10 Days later on the 11. December this part has a Wear of 50%, then I know: It has 10 more Days left.

My calculation is according to the rule of three formula: Time = (100 * delta t) / Wear

I use the following SQL command:

SELECT ( (100*(CURRENT_TIMESTAMP - First_Usage) / Wear) + First_Usage) As 'Change_Date' FROM spare_parts

And get the following Results:

If you see there are some crazy DATE_TIMES like 2017-19-41-43-19-31.

So my Question is now: How to format this "Numbers" to a useful DATE_TIME Format like YYYY-MM-DD hh:mm:ss ?

kind regards Toby

Body:
MySQL olredy have date intervals functional. If in Wear is already days count, your variant is

SELECT DATE_ADD(First_Usage, INTERVAL Wear DAY) as 'Change_Date' FROM spare_parts;

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add


问:
find the string with maximum number of lower case characters in java 8
I need to find the string with a maximum number of lowercases characters from Given List.

This is how i am currently doing

```<code>public static void main(String[] args) {

        List<String> list  = new ArrayList<>();

        list.add("Strig a with ABDD");
        list.add("STR dfd  BC dsff");

        OptionalLong max = list.stream().map(s->countLowerCase(s)).mapToLong(i->Long.valueOf(i)).max();
        System.out.println(max);

    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }
</code>```

is there any better way of doing this?

答:
There is no need to perform a map followed by mapToLong as you can use mapToLong with the long returning function in the first place:

```<code>    List<String> list  = Arrays.asList("Strig a with ABDD", "STR dfd  BC dsff");

    list.stream()
        .mapToLong(s -> s.chars().filter(Character::isLowerCase).count())
        .max()
        .ifPresent(System.out::println);
</code>```

There is no simpler way. If you really wan to get “the string with maximum number of lower case characters” rather than the number only, you can use:

```<code>list.stream()
    .max(Comparator.comparingLong(s -> s.chars().filter(Character::isLowerCase).count()))
    .ifPresent(System.out::println);
</code>```

which will print Strig a with ABDD, as this is the string with the maximum number of lower case characters in your list.

Body:
I need to find the string with a maximum number of lowercases characters from Given List.

This is how i am currently doing

public static void main(String[] args) {

        List<String> list  = new ArrayList<>();

        list.add("Strig a with ABDD");
        list.add("STR dfd  BC dsff");

        OptionalLong max = list.stream().map(s->countLowerCase(s)).mapToLong(i->Long.valueOf(i)).max();
        System.out.println(max);

    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }

is there any better way of doing this?

Body:
There is no need to perform a map followed by mapToLong as you can use mapToLong with the long returning function in the first place:

    List<String> list  = Arrays.asList("Strig a with ABDD", "STR dfd  BC dsff");

    list.stream()
        .mapToLong(s -> s.chars().filter(Character::isLowerCase).count())
        .max()
        .ifPresent(System.out::println);

There is no simpler way. If you really wan to get “the string with maximum number of lower case characters” rather than the number only, you can use:

list.stream()
    .max(Comparator.comparingLong(s -> s.chars().filter(Character::isLowerCase).count()))
    .ifPresent(System.out::println);

which will print Strig a with ABDD, as this is the string with the maximum number of lower case characters in your list.


问:
Trouble with sprites (loading and removing)-cocos2d iphone
Basically i have an array of Sprites to be loaded and removed one by one in an order.
I have a list of animal names in an array like

```<code> const NSString *Animal1[30] = {@"Lion .png",@"Zebra .png",...........
</code>```

To load a sprite i use the following code

```<code>image[i]= [Sprite spriteWithFile: [NSString stringWithFormat:@"%@",Animal1[i]]];
image[i].position = ccp( 240,180 );
[self addChild: image[i]];
</code>```

Then to remove the sprite after use I use the following code

```<code>[self removeChild:image[i] cleanup:YES];
</code>```

What happens when i run the code in simulator is the sprite loads one after other till 20th animal. After the 20th animals the application crashes.
I dont know what is the problem.If i have the array less than 20 it works fine but when it exceed the application crashes.
Can anyone plz help to resolve the issue.

答:
To verify all your files are ok try to load each one manually not using an array like(put a break point on each line and use Build & Debug):

```<code>(pseudo code)
add the lion sprite
add the tiger sprite
add the bear sprite
...etc...
</code>```

If that works then test your array by not using a loop to load the sprites, load each one by calling it's index like(put a break point on each line and use Build & Debug):

```<code>(pseudo code)
add image[1]
add image[2]
add image[3]
...etc...
</code>```

Then if that works fine I would setup your sprites into and array of sprites like:

```<code>(pseudo code)
create the sprite with image[i]
add the sprite to spriteArray
---repeat for each sprite---
</code>```

Then do another loop to add the sprites to the layer like:

```<code>CGSize size = [[CCDirector sharedDirector] winSize];
for CCSprite *aSprite in SpriteArray {
         aSprite.position = ccp((size.width - (aSprite.contentSize.width / 2)), (aSprite.contentSize.height / 2));  //positions the sprite to the lower right corner
         [self addChild aSprite];
    }
</code>```

I like to put my sprites in an array, that way it's easier to just traverse the array when I need to work with them.  Also,  instead of using absolute coordinates, I like to use coordinates that are relative to the size of the window and the size of the sprite.  By positioning them this way, it will convert the coordinates no matter what type of display or orientation or sprite size you are working with.

Hope this helps!

Body:
Basically i have an array of Sprites to be loaded and removed one by one in an order.
I have a list of animal names in an array like

 const NSString *Animal1[30] = {@"Lion .png",@"Zebra .png",...........

To load a sprite i use the following code

image[i]= [Sprite spriteWithFile: [NSString stringWithFormat:@"%@",Animal1[i]]];
image[i].position = ccp( 240,180 );
[self addChild: image[i]];

Then to remove the sprite after use I use the following code

[self removeChild:image[i] cleanup:YES];

What happens when i run the code in simulator is the sprite loads one after other till 20th animal. After the 20th animals the application crashes.
I dont know what is the problem.If i have the array less than 20 it works fine but when it exceed the application crashes.
Can anyone plz help to resolve the issue.

Body:
To verify all your files are ok try to load each one manually not using an array like(put a break point on each line and use Build & Debug):

(pseudo code)
add the lion sprite
add the tiger sprite
add the bear sprite
...etc...

If that works then test your array by not using a loop to load the sprites, load each one by calling it's index like(put a break point on each line and use Build & Debug):

(pseudo code)
add image[1]
add image[2]
add image[3]
...etc...

Then if that works fine I would setup your sprites into and array of sprites like:

(pseudo code)
create the sprite with image[i]
add the sprite to spriteArray
---repeat for each sprite---

Then do another loop to add the sprites to the layer like:

CGSize size = [[CCDirector sharedDirector] winSize];
for CCSprite *aSprite in SpriteArray {
         aSprite.position = ccp((size.width - (aSprite.contentSize.width / 2)), (aSprite.contentSize.height / 2));  //positions the sprite to the lower right corner
         [self addChild aSprite];
    }

I like to put my sprites in an array, that way it's easier to just traverse the array when I need to work with them.  Also,  instead of using absolute coordinates, I like to use coordinates that are relative to the size of the window and the size of the sprite.  By positioning them this way, it will convert the coordinates no matter what type of display or orientation or sprite size you are working with.

Hope this helps!


问:
A schema-less hierarchical database where only the "leafs" are documents
My data structure is tree-like, where the branches are pure keys, and only the leafs are schema less documents.

Example:

keyA
    KeyA_1
        KeyA_1A{
            key: value,
            key: value,
            key: valeu
        }
        KeyA_1B
            KeyA_1B_1{
               key: value,
               key: value,
               key: value
            }
   KeyA_2
        KeyA_2A{
            key: value,
            key: value
        }
KeyB
    KeyB_1{
         key: value,
         key: value,
         key: valeu
    }
    KeyB_2{
         key: value
    }```

Which database is the right for me?

答:
I think that the data structure you described here is not how it supposed to looks like in the DB, it's just how your application considers it.

If you want to store it, so later it can be easily travelable, I suggest to save your tree as a list of nodes which each node is a model (row/document), that have the following fields:

id (pk)

key (if you still need it)

next (fk, nullable)

data (json, optional)

This way you can build your tree and travel it till you'll meet with next = null with the tree-traversal technique you prefer.

Regards the DB itself, as said, you can choose the one you prefer (rational/non-rational, Postgres v9.2+ or MySql v5.7+ can be a good solution for you because they haves JSONB/JSON field support for your data.

Body:
My data structure is tree-like, where the branches are pure keys, and only the leafs are schema less documents.

Example:

keyA
    KeyA_1
        KeyA_1A{
            key: value,
            key: value,
            key: valeu
        }
        KeyA_1B
            KeyA_1B_1{
               key: value,
               key: value,
               key: value
            }
   KeyA_2
        KeyA_2A{
            key: value,
            key: value
        }
KeyB
    KeyB_1{
         key: value,
         key: value,
         key: valeu
    }
    KeyB_2{
         key: value
    }

Which database is the right for me?


问:
SQL - Count records & update multiple columns depending on value
I have two tables ... accounts & tax. In table tax I would like to updated records (?) depending on column category available in table accounts like this:

table 'accounts'

```<code>id|cat2|cat3
1|A|Active
2|A|Active
3|A|Inactive
4|A|Active
5|B|Inactive
6|B|Active
</code>```

table 'tax'

```<code>id|category|count_total|count_active|count_inactive
1|A|?|?|?
2|B|?|?|?
</code>```

Desired result:

```<code>id|category|count_total|count_active|count_inactive
1|A|4|3|1
2|B|2|1|1
</code>```

For count_total I tried this:

```<code>UPDATE tax t2,
(   SELECT count(*)
    FROM accounts
) t1
SET t2.count_total = t1.count(*)
WHERE t1.cat2 = t2.category;
</code>```

答:
You can use join to update your tax table

```<code>UPDATE tax t2
JOIN (
    SELECT
    cat2,
    COUNT(*) cnt,
    SUM(cat3 = 'Active') count_active,
    SUM(cat3 = 'Inactive') count_inactive
    FROM
    accounts
    GROUP BY cat2
) t1
ON t1.cat2 = t2.category
SET t2.count_total = t1.cnt ,
    t2.count_active = t1.count_active,
    t2.count_inactive = t1.count_inactive
</code>```

Demo

Body:
I have two tables ... accounts & tax. In table tax I would like to updated records (?) depending on column category available in table accounts like this:

table 'accounts'

id|cat2|cat3
1|A|Active
2|A|Active
3|A|Inactive
4|A|Active
5|B|Inactive
6|B|Active

table 'tax'

id|category|count_total|count_active|count_inactive
1|A|?|?|?
2|B|?|?|?

Desired result:

id|category|count_total|count_active|count_inactive
1|A|4|3|1
2|B|2|1|1

For count_total I tried this:

UPDATE tax t2,
(   SELECT count(*)
    FROM accounts
) t1
SET t2.count_total = t1.count(*)
WHERE t1.cat2 = t2.category;

Body:
You can use join to update your tax table

UPDATE tax t2
JOIN (
    SELECT
    cat2,
    COUNT(*) cnt,
    SUM(cat3 = 'Active') count_active,
    SUM(cat3 = 'Inactive') count_inactive
    FROM
    accounts
    GROUP BY cat2
) t1
ON t1.cat2 = t2.category
SET t2.count_total = t1.cnt ,
    t2.count_active = t1.count_active,
    t2.count_inactive = t1.count_inactive

Demo


问:
Remove space between two views in chained view in constraint layout
I am using chained view in constraint layout. Now I want the intermediate space between two text views to be removed.As the buttons at the bottom are at distance. I am trying to move them from design layout but its not happening as well. How to do it.Following is my xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="23dp"
        android:layout_marginStart="32dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@+id/imageView3"
        app:layout_constraintStart_toEndOf="@+id/imageView3" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="26dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textViewHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--<LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/linearLayout2">-->

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="25dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="70dp"
        app:layout_constraintEnd_toStartOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="32dp"
        android:layout_marginTop="26dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <!-- </LinearLayout>-->

    <!--  <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="@id/linearLayout"
       >-->

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="30dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="17dp"
        android:layout_gravity="center"
        android:layout_marginBottom="58dp"
        android:layout_marginEnd="213dp"
        android:layout_marginTop="58dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/textViewHeader" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="67dp"
        android:layout_marginStart="90dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="63dp"
        android:layout_marginEnd="89dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView4" />

    <!-- </LinearLayout>-->

</android.support.constraint.ConstraintLayout>
</code>```

At the bottom there are two text views,placed horizontally and there is space between them. Thanks much :)

答:
You have to add Guideline

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="23dp"
        android:layout_marginStart="32dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@+id/imageView3"
        app:layout_constraintStart_toEndOf="@+id/imageView3" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="26dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textViewHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--<LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/linearLayout2">-->

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="25dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="70dp"
        app:layout_constraintEnd_toStartOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="32dp"
        android:layout_marginTop="26dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <!-- </LinearLayout>-->

    <!--  <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="@id/linearLayout"
       >-->

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="30dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="17dp"
        android:layout_gravity="center"
        android:layout_marginBottom="58dp"
        android:layout_marginEnd="213dp"
        android:layout_marginTop="58dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/textViewHeader" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="67dp"
    android:gravity="center"
    app:layout_constraintEnd_toStartOf="@+id/guideline1"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent" />

<TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="63dp"
    android:gravity="center"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toEndOf="@+id/guideline1" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline1"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

    <!-- </LinearLayout>-->

</android.support.constraint.ConstraintLayout>
</code>```

About Guideline in ConstraintLayout:
Utility class representing a Guideline helper object for ConstraintLayout. Helper objects are not displayed on device (they are marked as View.GONE) and are only used for layout purposes. They only work within a ConstraintLayout. [...]

For more details, there is good documentation:

https://developer.android.com/reference/android/support/constraint/Guideline.html

Body:
I am using chained view in constraint layout. Now I want the intermediate space between two text views to be removed.As the buttons at the bottom are at distance. I am trying to move them from design layout but its not happening as well. How to do it.Following is my xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="23dp"
        android:layout_marginStart="32dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@+id/imageView3"
        app:layout_constraintStart_toEndOf="@+id/imageView3" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="26dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textViewHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="25dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="70dp"
        app:layout_constraintEnd_toStartOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="32dp"
        android:layout_marginTop="26dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="30dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="17dp"
        android:layout_gravity="center"
        android:layout_marginBottom="58dp"
        android:layout_marginEnd="213dp"
        android:layout_marginTop="58dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/textViewHeader" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="67dp"
        android:layout_marginStart="90dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="63dp"
        android:layout_marginEnd="89dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView4" />

</android.support.constraint.ConstraintLayout>

At the bottom there are two text views,placed horizontally and there is space between them. Thanks much :)

Body:
You have to add Guideline

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="23dp"
        android:layout_marginStart="32dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@+id/imageView3"
        app:layout_constraintStart_toEndOf="@+id/imageView3" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="26dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textViewHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!--<LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/linearLayout2">-->

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="25dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="70dp"
        app:layout_constraintEnd_toStartOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="32dp"
        android:layout_marginTop="26dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <!-- </LinearLayout>-->

    <!--  <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="1dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="60dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="@id/linearLayout"
       >-->

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="30dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        app:srcCompat="@mipmap/ic_launcher_round" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="17dp"
        android:layout_gravity="center"
        android:layout_marginBottom="58dp"
        android:layout_marginEnd="213dp"
        android:layout_marginTop="58dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/textViewHeader" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="67dp"
    android:gravity="center"
    app:layout_constraintEnd_toStartOf="@+id/guideline1"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent" />

<TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="63dp"
    android:gravity="center"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toEndOf="@+id/guideline1" />

<android.support.constraint.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/guideline1"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

    <!-- </LinearLayout>-->

</android.support.constraint.ConstraintLayout>

About Guideline in ConstraintLayout:
Utility class representing a Guideline helper object for ConstraintLayout. Helper objects are not displayed on device (they are marked as View.GONE) and are only used for layout purposes. They only work within a ConstraintLayout. [...]

For more details, there is good documentation:

https://developer.android.com/reference/android/support/constraint/Guideline.html


问:
uitableviewcell not showing swift 3
I'm working on a swift assignment about table view controller and my table view doesn't have anything on it. I have correctly connected the labels and classes and assigned tableview cell identifier as "cell" in the attribute on storyboard but I still have the error "need to register nib" and even if I wrote self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") the error is gone but there's still nothing on it.

My cell class is as below.

```<code>class cartTableViewCell: UITableViewCell {

@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemQuan: UILabel!
@IBOutlet weak var itemFrame: UILabel!
@IBOutlet weak var itemSize: UILabel!
@IBOutlet weak var itemPrice: UILabel!
@IBOutlet weak var itemSub: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}`
</code>```

my function is

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell

    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}`
</code>```

If I print(item.itemName), I can get some value. cell.itemName?.text is nil

I checked some answers online but so far no luck. Any help is highly appreciated.

答:
Just check the reuse identifier name in your code. I am just writing this for more explanation.

```<code>viewDidLoad(){
            let customNib = UINib(nibName: "CustomCell", bundle: Bundle.main)
            tableView.register(customNib, forCellReuseIdentifier: "customCell")
        }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
   cell.configureCell(text: data[indexPath.row])
}
</code>```

Never do this :

```<code>let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell
        if cell == nil {
                cell = cartTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            }
</code>```

Explantion :

A UITableViewCell object with the associated reuse identifier. This
  method always returns a valid cell. Ref:https://developer.apple.com/documentation/uikit/uitableview/1614878-dequeuereusablecell.

Title: uitableviewcell not showing swift 3

Body:
I'm working on a swift assignment about table view controller and my table view doesn't have anything on it. I have correctly connected the labels and classes and assigned tableview cell identifier as "cell" in the attribute on storyboard but I still have the error "need to register nib" and even if I wrote self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") the error is gone but there's still nothing on it.

My cell class is as below.

class cartTableViewCell: UITableViewCell {

@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemQuan: UILabel!
@IBOutlet weak var itemFrame: UILabel!
@IBOutlet weak var itemSize: UILabel!
@IBOutlet weak var itemPrice: UILabel!
@IBOutlet weak var itemSub: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}`

my function is

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell

    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}`

If I print(item.itemName), I can get some value. cell.itemName?.text is nil

I checked some answers online but so far no luck. Any help is highly appreciated.

Body:
Just check the reuse identifier name in your code. I am just writing this for more explanation.

viewDidLoad(){
            let customNib = UINib(nibName: "CustomCell", bundle: Bundle.main)
            tableView.register(customNib, forCellReuseIdentifier: "customCell")
        }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
   cell.configureCell(text: data[indexPath.row])
}

Never do this :

let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell
        if cell == nil {
                cell = cartTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            }

Explantion :

A UITableViewCell object with the associated reuse identifier. This
  method always returns a valid cell. Ref:https://developer.apple.com/documentation/uikit/uitableview/1614878-dequeuereusablecell.


问:
C: How to add a try again function to this asterisk square printing program

I need a program that asks for an integer &prints out an emtpy asterisk square based on the input number. And if the input was invalid then i need it to try and ask again
.
THIS is what i have so far (it already can make a square based on a variable number) i just need to enhence it so it asks again if the user is too dumb to input an integer

```<code>#include <stdio.h>
int Loops() {
    int s, e, z;
    printf("Input number \n");
    scanf("%d", &s);
    for(e = 0; e < s; e++) {
        for(z = 0; z < s; z++) {
            if(e==0 || e==s-1 || z==0 || z==s-1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
}

int main() {
   Loops();
}
</code>```

 i think the teacher mentioned something of adding a switch case...?

答:
I propose this solution, in a few words I check the type of number entered by the user, if it's >0 then run,you do not have to worry that it is float because you have defined an integer type and the part not integer is automatically troncated.</p>

```<code>#include <stdio.h>
int Loops() {
    int s, e, z;
    printf("Input number \n");
    scanf("%d", &s);
    if (s > 0 ) {
        for (e = 0; e < s; e++) {
            for (z = 0; z < s; z++) {
                if(e == 0 || e == s - 1 || z == 0 || z == s - 1)
                    printf("*");
                else
                    printf(" ");
            }
            printf("\n");
        }
    }
    else
        Loops();
}

int main() {
   Loops();

   return 0;
}
</code>```

Body:
I need a program that asks for an integer &prints out an emtpy asterisk square based on the input number. And if the input was invalid then i need it to try and ask again
.
THIS is what i have so far (it already can make a square based on a variable number) i just need to enhence it so it asks again if the user is too dumb to input an integer

#include <stdio.h>
int Loops() {
    int s, e, z;
    printf("Input number \n");
    scanf("%d", &s);
    for(e = 0; e < s; e++) {
        for(z = 0; z < s; z++) {
            if(e==0 || e==s-1 || z==0 || z==s-1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
}

int main() {
   Loops();
}

 i think the teacher mentioned something of adding a switch case...?

Body:
I propose this solution, in a few words I check the type of number entered by the user, if it's >0 then run,you do not have to worry that it is float because you have defined an integer type and the part not integer is automatically troncated.

#include <stdio.h>
int Loops() {
    int s, e, z;
    printf("Input number \n");
    scanf("%d", &s);
    if (s > 0 ) {
        for (e = 0; e < s; e++) {
            for (z = 0; z < s; z++) {
                if(e == 0 || e == s - 1 || z == 0 || z == s - 1)
                    printf("*");
                else
                    printf(" ");
            }
            printf("\n");
        }
    }
    else
        Loops();
}

int main() {
   Loops();

   return 0;
}


问:
Using Datatables with ASP.NET
I'd like use Datatables jquery plug-in with ASP.NET. What is the best way to generate the HTML table needed?</p>

答:
Use Ajax, there are plenty of code examples on the Datatables web site

https://datatables.net/examples/

This is how I got started using Datatables.

Title: Using Datatables with ASP.NET


问:
Effect of database driven product pages and SEO
What is the impact on SEO for an e commerce site the displays products/items information driven from a database (versus each product having it's own HTML page).

Will the SE find the item information ? If not, how do you overcome this issue ?

答:
Create individual pages for each product and use friendly URLs for all of them. These pages can be generated from a database, search engines don't mind at all. It is better for the pages to have a name like http://example.com/products/An-Awesome-Product/ than http://example.com/products.aspx?id=1234. ASP.NET MVC makes it trivial to do such things. With traditional webforms, you can use an HttpModule with a redirect so that the first example turns into the second one on the server such that search engines and visitors don't even notice.

Use a sitemap.xml to let the search engines know about your pages and when they were last updated.

Don't forget that the title of the page is quite important. And it does not do any harm to have decent metadata on the page with keywords and descriptions that are customized for the product.

Definitely do not generate pages with random content or filler content, as decent search engines are quite good at picking out patterns and penalize heavily for illicit behavior. Sadly, I've learned that from personal experience.

OwnerDisplayName: DaveQ

LastEditorDisplayName: cletus

OwnerDisplayName: David Thomas Garcia


问:
Laravel 5 - Php artisan syntax error
I am currently developing an app with Laravel 5 and suddenly the artisan stoped working!

I can't use a single command on it, it always return the error:

```<code>      [Symfony\Component\Debug\Exception\FatalErrorException]
      syntax error, unexpected ',', expecting variable (T_VARIABLE)
</code>```

I  tried to update via composer but when the artisan tries to clear-complie

```<code>Command: composer update

> php artisan clear-compiled

  [Symfony\Component\Debug\Exception\FatalErrorException]
  syntax error, unexpected ',', expecting variable (T_VARIABLE)
</code>```

Has anyone ever had this error before?

My Php version is 5.6.8

答:
Instead of executing the commands using command prompt.
It will be easy to look at LOG file found at location/directory

storage/logs/laravel.log

I am sure, you can easily check the log file and fix the syntax error.

Title: Laravel 5 - Php artisan syntax error

Body:
I am currently developing an app with Laravel 5 and suddenly the artisan stoped working!

I can't use a single command on it, it always return the error:

      [Symfony\Component\Debug\Exception\FatalErrorException]
      syntax error, unexpected ',', expecting variable (T_VARIABLE)

I  tried to update via composer but when the artisan tries to clear-complie

Command: composer update

> php artisan clear-compiled

  [Symfony\Component\Debug\Exception\FatalErrorException]
  syntax error, unexpected ',', expecting variable (T_VARIABLE)

Has anyone ever had this error before?

My Php version is 5.6.8


问:
Input text color change is not proper with addEventListener
From the input element Id 'email', I am performing an addEventListener operation for dynamic email validation. The color of text will be 'black' if it is valid or 'maroon' if it's not.

```<code><!-- HTML -->
<input type="text" id="email" name="email">

//Javascript
document.getElementById('email').addEventListener('keydown', function(e) {
            var value = this.value;
            ValidateEmail(value);

            function ValidateEmail(mail)   {
                if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(mail))
                {
                    console.log("ok");
                    var red = document.getElementById('email');
                    red.style.color = 'black';
                    return (true);
                } else {
                    console.log("You have entered an invalid email address!");
                    var red = document.getElementById('email');
                    red.style.color = '#9e1e1e';
                    return (false);
                }
            }
        });
</code>```

The above program is working but with one issue, ie. the function validates the text only on the next 'keydown' event.

Ex. 'smith@email.co' is a valid email string, but the color changes only on the next event operation (which is 'smith@email.com' or 'smith@email.c').

答:
The keydown event fires when the key is pressed, but before the value has been updated. This can be excellent as it lets you cancel the change in value that the keypress would normally trigger if it is a "bad" key, but it doesn't help solve your problem.

Use the input event instead of the keypress event. This will fire after the value has changed, even if it was changed by using the mouse to paste a new value into the field.

Body:
From the input element Id 'email', I am performing an addEventListener operation for dynamic email validation. The color of text will be 'black' if it is valid or 'maroon' if it's not.

<input type="text" id="email" name="email">

//Javascript
document.getElementById('email').addEventListener('keydown', function(e) {
            var value = this.value;
            ValidateEmail(value);

            function ValidateEmail(mail)   {
                if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(mail))
                {
                    console.log("ok");
                    var red = document.getElementById('email');
                    red.style.color = 'black';
                    return (true);
                } else {
                    console.log("You have entered an invalid email address!");
                    var red = document.getElementById('email');
                    red.style.color = '#9e1e1e';
                    return (false);
                }
            }
        });

The above program is working but with one issue, ie. the function validates the text only on the next 'keydown' event.

Ex. 'smith@email.co' is a valid email string, but the color changes only on the next event operation (which is 'smith@email.com' or 'smith@email.c').


问:
SQL fixed-value IN() vs. INNER JOIN performance
In answer to this SQL question, I've encountered a statement that fixed-value IN() operator is much slower than INNER JOIN with the same content, to the point that it is better to create temporary table for the values and JOIN them. Is it true (in general, with MySQL, any other SQL engine) and if yes - why? Intuitively, IN should be faster - you're comparing the potential match with a fixed set of values, which are already in memory and in needed format, while with JOIN you'd have to consult the indexes, potentially load data from disk, and perform other operations that may be not needed with IN. Am I missing something important?

Note that unlike this question and it's many duplicates, I'm talking about IN() having fixed set of values, not subquery.

答:
This relates to the length of the IN clause - and what is sometimes called a BUG in MySQL.

MySQL seems to have a low threshold for IN clauses, when it will swap to a TABLE/INDEX SCAN instead of collecting multiple partitions (one per IN item) and merging them.

With an INNER JOIN, it is almost always forced to use a direct row-by-row in JOIN collection, which is why it is sometimes faster

Refer to these MySQL manual pages

In Subquery considerations

In (constant list) performance

I could be wrong since it seems to imply that IN (constant value list) should always use a binary search on each item...


问:
js get chain of constructor names
I generate a chain of constructor names based on inheritance:

```<code>class Person {
}

class User extends Person {
}

$userClassIdentifier = generateIdentifier(User.constructor)
// userClassIdentifier = 'Person.User'

function generateIdentifier(constructor) {
        if (constructor.prototype && constructor.prototype.__proto__
            && constructor.prototype.__proto__.constructor && constructor.prototype.__proto__.constructor.name) {
            return  `${constructor.prototype.__proto__.constructor.name}.${constructor.name}`
        }
        return constructor.name
}
</code>```

this works for one level of inheritance. But it seems very hacky/ugly. Is there a nicer way to do it and to make it work for an unknown number of levels deep?

答:
If I have SUV extending Car extending Vehicle I expect 'Vehicle.Car.SUV'

I'd use getPrototypeOf and a loop, starting with the constructor you want to start with, and ending when that constructor's prototype is Function.prototype or null:

function getLineage(ctor) {
  let name = ctor.name;
  while ((ctor = Object.getPrototypeOf(ctor)) != Function.prototype && ctor) {
    name = ctor.name + "." + name;
  }
  return name;
}

class Vehicle { }
class Car extends Vehicle { }
class SUV extends Car { }

console.log(getLineage(SUV));```

One suggestion I'd make, though, would be to use a different separator rather than ., as . seems to suggest that (say) SUV is a property of Car, which of course it isn't. :-)

Title: js get chain of constructor names

Body:
I generate a chain of constructor names based on inheritance:

class Person {
}

class User extends Person {
}

$userClassIdentifier = generateIdentifier(User.constructor)
// userClassIdentifier = 'Person.User'

function generateIdentifier(constructor) {
        if (constructor.prototype && constructor.prototype.__proto__
            && constructor.prototype.__proto__.constructor && constructor.prototype.__proto__.constructor.name) {
            return  `${constructor.prototype.__proto__.constructor.name}.${constructor.name}`
        }
        return constructor.name
}

this works for one level of inheritance. But it seems very hacky/ugly. Is there a nicer way to do it and to make it work for an unknown number of levels deep?

Body:
If I have SUV extending Car extending Vehicle I expect 'Vehicle.Car.SUV'

I'd use getPrototypeOf and a loop, starting with the constructor you want to start with, and ending when that constructor's prototype is Function.prototype or null:

function getLineage(ctor) {
  let name = ctor.name;
  while ((ctor = Object.getPrototypeOf(ctor)) != Function.prototype && ctor) {
    name = ctor.name + "." + name;
  }
  return name;
}

class Vehicle { }
class Car extends Vehicle { }
class SUV extends Car { }

console.log(getLineage(SUV));

One suggestion I'd make, though, would be to use a different separator rather than ., as . seems to suggest that (say) SUV is a property of Car, which of course it isn't. :-)


问:
Remove some java files from jacoco test coverage using gradle
I want to exclude some source files in Jacaco Test coverage report.For other generated code I have done like this:

```<code>classDirectories = fileTree(
            dir: "${project.buildDir}/intermediates/classes/debug/com",
            excludes: [
                    '**/R.class',
                    '**/R$*.class']
                    )
</code>```

But for excluding Java files when I am trying to do like this:

```<code>   dir: "${project.buildDir}/intermediates/classes/debug/com",
            excludes: [
                 'src//java/com/example/application/Constants.java']
</code>```

have also tried like this:  '**/application/Constants.class'.It doesn't work. Do I need to include the path here:  dir: "${project.buildDir}/intermediates/classes/debug/com"?

I am using Android studio 3.0 (i don't think it matters here). Full code that I am trying:

```<code>task jacocoTestReport(type: JacocoReport) {
        group = "Reporting"
        description = "Generate Jacoco coverage reports"
        reports {
            xml.enabled = true
            html.enabled = true
        }

 sourceDirectories = files(sourceSets)

 classDirectories = fileTree(
            dir: "${project.buildDir}/intermediates/classes/debug/com",
            excludes: [
                    'src//java/com/example/application/Constants.java',     //this is not working
                    '**/R.class',
                    '**/R$*.class',
                    '**/BuildConfig.*',
                    '**/Manifest*.*',
                    '**/*$ViewInjector*.*',
                    '**/*$ViewBinder*.*',
                    '**/*$Lambda$*.*', // Jacoco can not handle several "$" in class name.
                    '**/*Module.*', // Modules for Dagger.
                    '**/*Dagger*.*', // Dagger auto-generated code.
                    '**/*MembersInjector*.*', // Dagger auto-generated code.
                    '**/*_Provide*Factory*.*',
                    '**/*_Factory.*', //Dagger auto-generated code
                    '**/*$*$*.*', // Anonymous classes generated by kotlin
                    //add libraries
                    'android/**/*.*',
                    'com/**/*.*',
                    'uk/**/*.*',
                    'io/**/*.*',
                    //remove what we don't test
                    'androidTest/**/*.*',
                    'test/**/*.*',
                    '**/injector/**/*.*',
                    '**/model/**/*.*',
                    '**/mock/**/*.*',
                    '**/event/**/*.*',
                    '**/**_ViewBinding**',
                    '**/*EventType.*',
                    '**/**Mocked'
            ]

    )
    executionData = fileTree(dir: 'build/jacoco', include: '**/*.exec')

}
</code>```

答:
classDirectories of task of type JacocoReport is about class files, not java source files. And I'm pretty sure that your directory

```<code> classDirectories = fileTree(
            dir: "${project.buildDir}/intermediates/classes/debug/com",
</code>```

contains class files and does not contain java files. Also as you can see other patterns are about class files:

```<code>                '**/R.class',
                '**/R$*.class',
</code>```

And that's why your exclusion

```<code>           'src//java/com/example/application/Constants.java',     //this is not working
</code>```

doesn't work. So change it to match existing class file in given directory.

Also note that you can easily debug result of fileTree(...) call by simply printing it:

```<code>tree.each {File file ->
    println file
}
</code>```

Body:
I want to exclude some source files in Jacaco Test coverage report.For other generated code I have done like this:

classDirectories = fileTree(
            dir: "${project.buildDir}/intermediates/classes/debug/com",
            excludes: [
                    '**/R.class',
                    '**/R$*.class']
                    )

But for excluding Java files when I am trying to do like this:

   dir: "${project.buildDir}/intermediates/classes/debug/com",
            excludes: [
                 'src//java/com/example/application/Constants.java']

have also tried like this:  '**/application/Constants.class'.It doesn't work. Do I need to include the path here:  dir: "${project.buildDir}/intermediates/classes/debug/com"?

I am using Android studio 3.0 (i don't think it matters here). Full code that I am trying:

task jacocoTestReport(type: JacocoReport) {
        group = "Reporting"
        description = "Generate Jacoco coverage reports"
        reports {
            xml.enabled = true
            html.enabled = true
        }

 sourceDirectories = files(sourceSets)

 classDirectories = fileTree(
            dir: "${project.buildDir}/intermediates/classes/debug/com",
            excludes: [
                    'src//java/com/example/application/Constants.java',     //this is not working
                    '**/R.class',
                    '**/R$*.class',
                    '**/BuildConfig.*',
                    '**/Manifest*.*',
                    '**/*$ViewInjector*.*',
                    '**/*$ViewBinder*.*',
                    '**/*$Lambda$*.*', // Jacoco can not handle several "$" in class name.
                    '**/*Module.*', // Modules for Dagger.
                    '**/*Dagger*.*', // Dagger auto-generated code.
                    '**/*MembersInjector*.*', // Dagger auto-generated code.
                    '**/*_Provide*Factory*.*',
                    '**/*_Factory.*', //Dagger auto-generated code
                    '**/*$*$*.*', // Anonymous classes generated by kotlin
                    //add libraries
                    'android/**/*.*',
                    'com/**/*.*',
                    'uk/**/*.*',
                    'io/**/*.*',
                    //remove what we don't test
                    'androidTest/**/*.*',
                    'test/**/*.*',
                    '**/injector/**/*.*',
                    '**/model/**/*.*',
                    '**/mock/**/*.*',
                    '**/event/**/*.*',
                    '**/**_ViewBinding**',
                    '**/*EventType.*',
                    '**/**Mocked'
            ]

    )
    executionData = fileTree(dir: 'build/jacoco', include: '**/*.exec')

}

Body:
classDirectories of task of type JacocoReport is about class files, not java source files. And I'm pretty sure that your directory

 classDirectories = fileTree(
            dir: "${project.buildDir}/intermediates/classes/debug/com",

contains class files and does not contain java files. Also as you can see other patterns are about class files:

                '**/R.class',
                '**/R$*.class',

And that's why your exclusion

           'src//java/com/example/application/Constants.java',     //this is not working

doesn't work. So change it to match existing class file in given directory.

Also note that you can easily debug result of fileTree(...) call by simply printing it:

tree.each {File file ->
    println file
}


问:
Scenario on Teradata Joins
I have two source tables

MST

```<code>CustNo  Date
C1  P1
C1  P2
C1  P3
C1  P4
C1  P5
C1  P6
</code>```

TMP

```<code>CustNo  Rule    Amt Date
C1  R1  A1  P1
C1  R1  A2  P2
C1  R1  A3  P3
</code>```

I want my result table as

```<code>CustNo  Rule    Amt Date
C1  R1  A1  P1
C1  R1  A2  P2
C1  R1  A3  P3
C1  R1  0   P4
C1  R1  0   P5
C1  R1  0   P6
</code>```

Can any help me how this can be achieved in TD

答:
```<code>select    a.custno,coalesce(b.rule,'R1') as rule,amt,a.date
from      mst a
leftjoin  tmp b
       on a.cust_date=b.cust_date
      and a.cust_no = b.cust_no
</code>```

Title: Scenario on Teradata Joins

Body:
I have two source tables

MST

CustNo  Date
C1  P1
C1  P2
C1  P3
C1  P4
C1  P5
C1  P6

TMP

CustNo  Rule    Amt Date
C1  R1  A1  P1
C1  R1  A2  P2
C1  R1  A3  P3

I want my result table as

CustNo  Rule    Amt Date
C1  R1  A1  P1
C1  R1  A2  P2
C1  R1  A3  P3
C1  R1  0   P4
C1  R1  0   P5
C1  R1  0   P6

Can any help me how this can be achieved in TD


问:
What do I need to do to sort all the records (for suppose 1000) and return top 50 records in Apache Solr?
I have total 1000 records and I need to sort all the records based on one property and need to get top 60 from the sorted 1000 records.</p>

答:
This is very basic Solr usage, and I'd strongly suggest at least trying to look at the documentation first.

For sorting your documents:

The sort parameter arranges search results in either ascending (asc) or descending (desc) order. The parameter can be used with either numerical or alphabetical content. The directions can be entered in either all lowercase or all uppercase letters (i.e., both asc or ASC). (sort=property asc)

And for the number of documents returned:

You can use the rows parameter to paginate results from a query. The parameter specifies the maximum number of documents from the complete result set that Solr should return to the client at one time. (rows=60)


问:
How do I compile C# code as a library instead of an executable?
I have a C# console application in Visual Studio 2010. It has a Main() method as well as a bunch of utility classes. I'd like those utility classes to be available to other solutions. From reading online it seems that I need to compile it as a Class Library (DLL). So here's what I did:

Went in Visual Studio to "Project > [ProjectName] Properties > Application" and changed "Output type" from "Console Application" to "Class Library"

Rebuilt; ProjectName.dll was created in bin/Debug.

Created a new Console Application

Solution Explorer > Add Reference > browse to ProjectName.DLL, select it.

However, neither IntelliSense nor the Object Browser could find the classes inside that DLL.

I tried recompiling several different Console Applications as Class Libraries and got the same result. I also noticed that it works if I initially create the solution as a Class Library, but not if I convert it to one later.

Any tips?

答:
At first, from the point of view of managed libraries it does not matter what kind of Output type is your managed library. I mean that you can successfully reference ConsoleApplication1.exe from ConsoleApplication2.exe project (so you have no reason to convert ConsoleApplication1.exe to ConsoleApplication1.dll). </p>

<p>At second, I've tried to reproduce your situation, but... without effect. My VS displays types/methods from ConsoleApplication1.dll. One reason I can suppose is that you have forgotten to set visibility modifier (public keyword) for your utility classes.  </p>

Body:
At first, from the point of view of managed libraries it does not matter what kind of Output type is your managed library. I mean that you can successfully reference ConsoleApplication1.exe from ConsoleApplication2.exe project (so you have no reason to convert ConsoleApplication1.exe to ConsoleApplication1.dll).

At second, I've tried to reproduce your situation, but... without effect. My VS displays types/methods from ConsoleApplication1.dll. One reason I can suppose is that you have forgotten to set visibility modifier (public keyword) for your utility classes.


问:
Total all matching integer elements in an array
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.

```<code>public static void main(String[] args) {

    int arr[] = {6,6,6,6,6,6};
    int matched = 1;
    int value = 0;
    int total = 0;
    for(int i=0;i<arr.length;i++){
        for(int j=(i+1);j<arr.length;j++){
            if(ar[i] == ar[j]){
                matched++;
                value = ar[i];
                break;
            }
        }
        total = (matched * value);
    } // End for loop
    System.out.println("Matched:"+(matched)+"");
    System.out.println("Total:"+total);
}
</code>```

But, if the array was for example...

```<code>int arr[] = {6,1,1,6,6,6};
</code>```

The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?

答:
If you are allowed to use arrays - if not too fancy - then you could use 3 loops:

The first finds minimum and maximum elements

The second determines the occurrence of each item

The third calculates the totals

In Java this would look like this:

```<code>public static void main(String[] args) {
    int[] array = {6, 3, 3, 6, 6, 6, 4, 4, 20};
    int min = array[0];
    int max = array[0];
    // Find min max
    for (int i : array) {
        if (i < min) {
            min = i;
        }
        if (i > max) {
            max = i;
        }
    }
    // Use array to sum up all elements
    int[] holderArray = new int[max - min + 1];
    for (int i : array) {
        holderArray[i - min]++;
    }
    // Calculate occurrence and sums
    for(int i = 0; i < holderArray.length; i++) {
        if(holderArray[i] > 0) {
            System.out.printf("number: %2d; count: %2d; sum: %2d%n", i + min, holderArray[i], (i + min) * holderArray[i]);
        }
    }
}
</code>```

This prints out:

```<code>number:  3; count:  2; sum:  6
number:  4; count:  2; sum:  8
number:  6; count:  4; sum: 24
number: 20; count:  1; sum: 20
</code>```

Body:
I was looking over some basic questions that might be asked in an interview. Using basic for loops (No hash maps etc)I want to sum up all the matching elements in an array.For example, 6 matching elements will result in (Matched: 6) and a total of 36 in the example below.An example of this could be rolling dice, and the score is the total of all the dice that match.

public static void main(String[] args) {

    int arr[] = {6,6,6,6,6,6};
    int matched = 1;
    int value = 0;
    int total = 0;
    for(int i=0;i<arr.length;i++){
        for(int j=(i+1);j<arr.length;j++){
            if(ar[i] == ar[j]){
                matched++;
                value = ar[i];
                break;
            }
        }
        total = (matched * value);
    } // End for loop
    System.out.println("Matched:"+(matched)+"");
    System.out.println("Total:"+total);
}

But, if the array was for example...

int arr[] = {6,1,1,6,6,6};

The output I get will be (Matched:5) and an a total of 30.Can could I store the matching pair of 1's and add them to the total using as little basic code as possible?

Body:
If you are allowed to use arrays - if not too fancy - then you could use 3 loops:

The first finds minimum and maximum elements

The second determines the occurrence of each item

The third calculates the totals

In Java this would look like this:

public static void main(String[] args) {
    int[] array = {6, 3, 3, 6, 6, 6, 4, 4, 20};
    int min = array[0];
    int max = array[0];
    // Find min max
    for (int i : array) {
        if (i < min) {
            min = i;
        }
        if (i > max) {
            max = i;
        }
    }
    // Use array to sum up all elements
    int[] holderArray = new int[max - min + 1];
    for (int i : array) {
        holderArray[i - min]++;
    }
    // Calculate occurrence and sums
    for(int i = 0; i < holderArray.length; i++) {
        if(holderArray[i] > 0) {
            System.out.printf("number: %2d; count: %2d; sum: %2d%n", i + min, holderArray[i], (i + min) * holderArray[i]);
        }
    }
}

This prints out:

number:  3; count:  2; sum:  6
number:  4; count:  2; sum:  8
number:  6; count:  4; sum: 24
number: 20; count:  1; sum: 20


问:
How to strtok a string that saved in an array and save it into three different arrays in c?
I have a string stored in an array.

```<code>    char a1[20],a2[20],a3[20];
    Modem_Send("AT*PSHPLMN?\r\n",13);
    ModemWaitForAtResponse((char *)APN_Buffer,80,20);
    p = strtok (APN_Buffer,"'\":");
    while (p!= NULL)
    {
    printf ("%s\r\n",p);
    p = strtok (NULL, "\":");
    }
</code>```

AT response will be for an ex:

```<code>"234","567","String"
</code>```

I want to save 234, 567 and String in three different arrays.

I can able to parse the characters but stuck at saving them in different arrays.

The output of above code is

```<code>234
,
567
,
String
</code>```

I need to save 234 in a1[20], 567 in a2[20], String in a3[20].

Thanks in advance.

答:
```<code>char a1[20], a2[20], a3[20];
char* arr[3] = {a1, a2, a3};
int i=0;
Modem_Send("AT*PSHPLMN?\r\n",13);
ModemWaitForAtResponse((char *)APN_Buffer,80,20);
p = strtok (APN_Buffer,"'\":");
while (p!= NULL)
{
 strcpy(arr[i++], p);
 printf ("%s\r\n",p);
 p = strtok (NULL, "\":");
}
</code>```

Body:
I have a string stored in an array.

    char a1[20],a2[20],a3[20];
    Modem_Send("AT*PSHPLMN?\r\n",13);
    ModemWaitForAtResponse((char *)APN_Buffer,80,20);
    p = strtok (APN_Buffer,"'\":");
    while (p!= NULL)
    {
    printf ("%s\r\n",p);
    p = strtok (NULL, "\":");
    }

AT response will be for an ex:

"234","567","String"

I want to save 234, 567 and String in three different arrays.

I can able to parse the characters but stuck at saving them in different arrays.

The output of above code is

234
,
567
,
String

I need to save 234 in a1[20], 567 in a2[20], String in a3[20].

Thanks in advance.