问:
How do I initialize app with external JSON?
I need to initialize my app with external json data. The problem I'm getting is that I can't force the app to wait loading children components for after the data arrives.

For example, let's use this as an example (not external loading here, I'm using setTimeout to make a point of waiting for data to arrive).

```<code>new Vue({
  el: '#app',
  router,
  render: h => h(App),
  beforeCreate() {
    setTimeout(() => {
      this.myConfig = 'loaded'; // I realize I'm not using $data here, but nevermind
    }, 1000)
  },
});
</code>```

And in my child component

```<code>created() {
  console.log(this.$root.myConfig);
},
</code>```

The problem is that created from the child is called before the beforeCreate finishes.

Data won't change from initial state. Thus, I don't need the reactivity of VueX.

As I'm using vue-router, an option maybe is to create a loading component as the default route, which should load the data, and then on arrival switch to the correct initial state.

Also, by looking at Async Components, maybe it's what I should use, but I get the feeling that it's a little more complicated than what I need.

Is there a best practice way to achieve this?

答:
You can use a simple boolean to hide the components while the data is loading with v-if. Set a variable named loading to true and change it to false when you're done loading. Then use v-if="!loading" on your component. You might want a nice loading text or spinner there for the user.

new Vue({
  el: '#app',
  data () {
    return {
      loading: true,
      myConfig: ''
    }
  },
  created () {
    setTimeout(() => {
      this.loading = false
      this.myConfig = 'loaded'
    }, 2000)
  },
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <p v-if="loading">loading...</p>
  <p v-else>{{ myConfig }}</p>
</div>

<script src="https://unpkg.com/vue@2.5.4/dist/vue.min.js"></script></code>```

Body:
I need to initialize my app with external json data. The problem I'm getting is that I can't force the app to wait loading children components for after the data arrives.

For example, let's use this as an example (not external loading here, I'm using setTimeout to make a point of waiting for data to arrive).

new Vue({
  el: '#app',
  router,
  render: h => h(App),
  beforeCreate() {
    setTimeout(() => {
      this.myConfig = 'loaded'; // I realize I'm not using $data here, but nevermind
    }, 1000)
  },
});

And in my child component

created() {
  console.log(this.$root.myConfig);
},

The problem is that created from the child is called before the beforeCreate finishes.

Data won't change from initial state. Thus, I don't need the reactivity of VueX.

As I'm using vue-router, an option maybe is to create a loading component as the default route, which should load the data, and then on arrival switch to the correct initial state.

Also, by looking at Async Components, maybe it's what I should use, but I get the feeling that it's a little more complicated than what I need.

Is there a best practice way to achieve this?

Body:
You can use a simple boolean to hide the components while the data is loading with v-if. Set a variable named loading to true and change it to false when you're done loading. Then use v-if="!loading" on your component. You might want a nice loading text or spinner there for the user.

new Vue({
  el: '#app',
  data () {
    return {
      loading: true,
      myConfig: ''
    }
  },
  created () {
    setTimeout(() => {
      this.loading = false
      this.myConfig = 'loaded'
    }, 2000)
  },
});

<div id="app">
  <p v-if="loading">loading...</p>
  <p v-else>{{ myConfig }}</p>
</div>

<script src="https://unpkg.com/vue@2.5.4/dist/vue.min.js"></script>


来源: stackexchange

答: That's because adding the 0 makes it an octal number. 345 octal is 229 decimal, for example. And as indicated in the comments, octal doesn't have 8 or 9.</p>

ContentLicense: CC BY-SA 3.0

Title: Why if a put a 0 infront of an int in 2D array change the output number? Java

Body:
During an exercice of 2D arrays where first of all we put numbers as a strings in the array like that. And OK there is no problem, everything ok.

String [][] a = {
            { "0345" , "345" , "041" , "41" },
            { "0344" , "344" , "030" , "30" },
            { "0333" , "333" , "031" , "31" },
            { "0346" , "346" , "045" , "45" },
            { "0101" , "101" , "021" , "21" },
            { "0455" , "455" , "037" , "37" },
            { "0100" , "100" , "040" , "40" },
    };
    for (int i = 0; i < c.length; ++i) {
        for(int j = 0; j < c[i].length; ++j) {
            System.out.print("|"+c[i][j]+"|");
        }
        System.out.println(" ");

So the out put it will show as these.

|0345||345||041||41|
|0344||344||030||30|
|0333||333||031||31|
|0346||346||045||45|
|0101||101||021||21|
|0455||455||037||37|
|0100||100||040||40|

But when I did the same but changing the String for int, by mistake I foget to remove the 0 infront of the numbers. So here is the code.

int [][] b = {
            { 0345 , 345 , 041 , 41 },
            { 0344 , 344 , 030 , 30 },
            { 0333 , 333 , 031 , 31 },
            { 0346 , 346 , 045 , 45 },
            { 0101 , 101 , 021 , 21 },
            { 0455 , 455 , 037 , 37 },
            { 0100 , 100 , 040 , 40 },
    };
    for (int i = 0; i < b.length; ++i) {
        for(int j = 0; j < b[i].length; ++j) {
            System.out.print("|"+b[i][j]+"|");
        }
        System.out.println(" ");
    }

And the output it's something I didn't expect.

|229||345||33||41|
|228||344||24||30|
|219||333||25||31|
|230||346||37||45|
|65||101||17||21|
|301||455||31||37|
|64||100||32||40|

So the thing is where I put 0345 the output it's 229 and so on.
When I saw that, try in to figure out, I put all numbers in order from 0 to 19 by mean so in one line 0 in the other 00 so on util 019. But for another reason I don't know all number with 08 - 09 - 018 - 019 doesn't work.
Here is the code of what I'm saying.

int[][] c = {
            { 010 , 10 , 00 , 0 },
            { 011 , 11 , 01 , 1 },
            { 012 , 12 , 02 , 2 },
            { 013 , 13 , 03 , 3 },
            { 014 , 14 , 04 , 4 },
            { 015 , 15 , 05 , 5 },
            { 016 , 16 , 06 , 6 },
            { 017 , 17 , 07 , 7 },
    };

    for (int i = 0; i < c.length; ++i) {
        for(int j = 0; j < c[i].length; ++j) {
            System.out.print("|"+c[i][j]+"|");
        }
        System.out.println(" ");

And here is the output.

|8||10||0||0|
|9||11||1||1|
|10||12||2||2|
|11||13||3||3|
|12||14||4||4|
|13||15||5||5|
|14||16||6||6|
|15||17||7||7|

So when you check the output, you realize that because of the error on the 08 - 09 (error or something I don't know) the 010 it's becaming 8.

Why is happening that ? There is an explanation for sure.


问:
MDB starts to consume messages before fully initialization of JNDI names
AS: Websphere 8.5.5

MQ impl: SIB

During application startup MDB starts to invoke onMessage method, which in turn invokes initialContext.lookup in order to find specific bean.
Sometimes (during variety of startup iterations) it returns null instead of reference to bean object.

This behavior is nondeterministic: in some startup iterations bean's context has time for all JNDI names initialization due to more longer MDB initialization and respectively a pause in message consumption.

Is there any workaround or magic IBM key to resolve issue ?

答:
If you have any additional initialisation happening inside the MDB it is helpful to consider the @PostContruct annotation.  I too had the onMessage firing too early, before initialisation was complete, resulting in the message not being processed.  After putting my additional initialisation logic in a method with this annotation, it solved my problem.

```<code>@PostConstruct
    public void initialize() {
....
}
</code>```

Body:
If you have any additional initialisation happening inside the MDB it is helpful to consider the @PostContruct annotation.  I too had the onMessage firing too early, before initialisation was complete, resulting in the message not being processed.  After putting my additional initialisation logic in a method with this annotation, it solved my problem.

@PostConstruct
    public void initialize() {
....
}


问:
ASP.NET MVC 5 : persisting variables in Controller
I instantiate the 'plate' object in the GET request of the view and then access it when the form is posted. The plate object is populated with the data from the form. Can I also use it to store the passed coordinates? Or what is the idiomatic way of doing what I'm trying to achieve?

Thanks!

```<code>public class DrawingController : Controller
{

        Plate plate;

        [HttpGet]
        public ActionResult Index()
        {
            plate = new Plate()
            {
              Holes = new Holes()
            }
            return View(plate);
        }

        // called by ajax when user clicks on "Save" to save the input coordinates
        [HttpPost]
        public void PassCoordinates(string coordinates)
        {
          // why is plate null here?
          plate.Holes.coordinates = coordinates;
        }

        [HttpPost]
        public ActionResult Index(Plate plate)
        {
         // I want to access plate.Holes.coordinates that I set in 'PassCoordinates'
         // how can I achieve this?
        }
}
</code>```

答:
If you want to maintain state across requests for each user

Use TempData collection, and ensure you set the values each time.  They will be available on only the next requests, and if you want them to stay multiple requests, you must set them each time.

Use Session to store values for the user's current session:
https://msdn.microsoft.com/en-us/library/ms178581.aspx

Store it in a cookie

Store it in query string

Store it in a database

Store it in an in memory database or caching service

Return the value via model to the next returned cshtml page, and place the value in a input form field, such that it is passed on the next request via the next post

Each method has advantages and disadvantages and without more information it's hard to determine what the appropriate choice is.

Body:
I instantiate the 'plate' object in the GET request of the view and then access it when the form is posted. The plate object is populated with the data from the form. Can I also use it to store the passed coordinates? Or what is the idiomatic way of doing what I'm trying to achieve?

Thanks!

public class DrawingController : Controller
{

        Plate plate;

        [HttpGet]
        public ActionResult Index()
        {
            plate = new Plate()
            {
              Holes = new Holes()
            }
            return View(plate);
        }

        // called by ajax when user clicks on "Save" to save the input coordinates
        [HttpPost]
        public void PassCoordinates(string coordinates)
        {
          // why is plate null here?
          plate.Holes.coordinates = coordinates;
        }

        [HttpPost]
        public ActionResult Index(Plate plate)
        {
         // I want to access plate.Holes.coordinates that I set in 'PassCoordinates'
         // how can I achieve this?
        }
}


问:
Openpyxl: read spreadsheet data in a range of columns
Hello I am trying to read data from a spreadsheet in a range which includes row 2 to 5 and it follows the column order but I keep getting error saying there is something wrong with the column range can anyone help me?
The code should look like this but instead of rows it should be columns:

```<code>for row in range(2, sheet.max_row + 1):
   state  = sheet['B' + str(row)].value
   county = sheet['C' + str(row)].value
   pop    = sheet['D' + str(row)].value
</code>```

the code I have attempted is:

```<code>import openpyxl
wb = openpyxl.load_workbook('name of wb')
sheet = wb.get_sheet_by_name('Sheet1')
for col in range('G', sheet.max_column + 1):
   state  = sheet[1 + str(column)].value
   county = sheet[2 + str(column)].value
   pop    = sheet[3 + str(column)].value
   hospitals  = sheet[4 + str(column)].value
   universities = sheet[5 + str(column)].value
</code>```

答: My guess is that your code "sheet.max_row + 1" is the culprit.  That would go OUTSIDE of the indexable range of your sheet list.</p>

Body:
Hello I am trying to read data from a spreadsheet in a range which includes row 2 to 5 and it follows the column order but I keep getting error saying there is something wrong with the column range can anyone help me?
The code should look like this but instead of rows it should be columns:

for row in range(2, sheet.max_row + 1):
   state  = sheet['B' + str(row)].value
   county = sheet['C' + str(row)].value
   pop    = sheet['D' + str(row)].value

the code I have attempted is:

import openpyxl
wb = openpyxl.load_workbook('name of wb')
sheet = wb.get_sheet_by_name('Sheet1')
for col in range('G', sheet.max_column + 1):
   state  = sheet[1 + str(column)].value
   county = sheet[2 + str(column)].value
   pop    = sheet[3 + str(column)].value
   hospitals  = sheet[4 + str(column)].value
   universities = sheet[5 + str(column)].value


问:
Should I consider the Simple XML Framework for Java?
Lately the Simple XML Framework gained popularity and some sites are presenting it.

I am thinking about replacing Apache Xerces-J with a new framework and I am considering Simple to be its successor.

Do you have any experiences with Simple?

What are its advantages and disadvantages?

Is it recommended for the use with enterprise software/within a servlet container or application server?

答:
JAXB is the enterprise standard for converting objects to/from XML.  There are many implementations:   Metro (the reference implementation included in Java SE 6), EclipseLink MOXy (I'm the tech lead), Apache JaxMe (no longer maintained), etc.

In terms of enterprise, JAXB is part of Java EE 5 and Java EE 6.  It is the binding layer for both Java Web Service standards:  JAX-WS (SOAP) and JAX-RS (REST).  This means it is supported by all the application server vendors:  Oracle, IBM, SAP, JBoss, etc.

All JAXB implementations are also well supported in Spring:

http://wiki.eclipse.org/EclipseLink/Examples/MOXy/Spring

For a comparison of JAXB and Simple check out:

http://bdoughan.blogspot.com/2010/10/how-does-jaxb-compare-to-simple.html

ContentLicense: CC BY-SA 2.5


问:
BufferedReader not reading second output
I am developing a client for a small game. Using sockets, I am parsing the request and responses with PrintWriter and BufferedReader classes.

The issue I have is when BufferedReader is used for the second time (second response from server).

Example:

```<code>public class BotClient {

private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;

public BotClient(final String gameId, final String botName) throws IOException {
    this.writer = new PrintWriter(socket.getOutputStream(), true);
    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

//Code that connects client to server. Works successfully.

public void sendGameRequest() {

try {
    //This first is the FIRST request to server. This works SUCCESSFULLY.
    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); // This will output game response successfully.

    //Now the problem occurs below here. I could do the same request but won't get an output.

    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); //EMPTY PRINT

    // The above is EXACTLY the same request however this prints out nothing.
</code>```

What could be the issue here and what is the best way to solve this problem?

答:
Analysis

I suppose that the second writer.println() method call is not going to happen, because the statement:

```<code>reader.lines().forEach(System.out::println);
</code>```

describes reading the lines from the stream, while the end of the stream (i.e. when the socket is closed) is not reached.

Body:
I am developing a client for a small game. Using sockets, I am parsing the request and responses with PrintWriter and BufferedReader classes.

The issue I have is when BufferedReader is used for the second time (second response from server).

Example:

public class BotClient {

private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;

public BotClient(final String gameId, final String botName) throws IOException {
    this.writer = new PrintWriter(socket.getOutputStream(), true);
    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

//Code that connects client to server. Works successfully.

public void sendGameRequest() {

try {
    //This first is the FIRST request to server. This works SUCCESSFULLY.
    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); // This will output game response successfully.

    //Now the problem occurs below here. I could do the same request but won't get an output.

    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); //EMPTY PRINT

    // The above is EXACTLY the same request however this prints out nothing.

What could be the issue here and what is the best way to solve this problem?

Body:
Analysis

I suppose that the second writer.println() method call is not going to happen, because the statement:

reader.lines().forEach(System.out::println);

describes reading the lines from the stream, while the end of the stream (i.e. when the socket is closed) is not reached.


问:
Claws Mail default from account setting has changed?
I use claws mail and my system upgraded to the latest 3.14.1. In the previous version, if I was looking at email in my personal email account and clicked Compose, I would get a compose window with the From being my personal account. If I was in my work account, I would get a compose window with my From being my work account.

In the new version, it always defaults to the "Default Account" no matter which emails I am looking at. If I reply to an email, it works correctly.

Is there a way to change this?

答:
There is a setting, which can be configured per folder, or hierarchy of folders, where you can set the default account to use when composing an email when that folder set is selected.

Right click on the folder, and choose properties. After choosing the compose tab on the left, about half way down on the right is a "Default Account" check box. When selected you can choose which account you want to compose with. If you select "Apply to subfolders" on the right of the option, you can set it for all the folders beneath this one too.

So, if you're on the root account folder, you can set the default compose account for all the folders within an email account.


问:
Sorted array object based on value
I have an array of objects with nested array objects.

```<code>[
    {
        "neighborhoods": [
            {
                 "origin": "Kenwood",
                 "destination": "Portage Bay"
            }
        ]
    },
    {
        "neighborhoods": [
             {
                 "origin": "First Hill",
                 "destination": "Denny-Blaine"
              }
        ]
    },
    {
        "neighborhoods": [
            {
                "origin": "Belltown",
                "destination": "Eastlake"
            }
        ]
    }
]
</code>```

I want to sort the objects alphabetically based on the origin value. What is the most efficient way to do this?

答:
You could take the property and the object at the index zero with origin value for sorting.

var array = [{ neighborhoods: [{ origin: "Kenwood", destination: "Portage Bay" }] }, { neighborhoods: [{ origin: "First Hill", destination: "Denny-Blaine" }] }, { neighborhoods: [{ origin: "Belltown", destination: "Eastlake" }] }];

array.sort(function (a, b) {
    function getValue(o) { return o.neighborhoods[0].origin; }
    var aa = getValue(a),
        bb = getValue(b);

    return aa > bb || -(aa < bb);
});

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Sorted array object based on value

Body:
I have an array of objects with nested array objects.

[
    {
        "neighborhoods": [
            {
                 "origin": "Kenwood",
                 "destination": "Portage Bay"
            }
        ]
    },
    {
        "neighborhoods": [
             {
                 "origin": "First Hill",
                 "destination": "Denny-Blaine"
              }
        ]
    },
    {
        "neighborhoods": [
            {
                "origin": "Belltown",
                "destination": "Eastlake"
            }
        ]
    }
]

I want to sort the objects alphabetically based on the origin value. What is the most efficient way to do this?

Body:
You could take the property and the object at the index zero with origin value for sorting.

var array = [{ neighborhoods: [{ origin: "Kenwood", destination: "Portage Bay" }] }, { neighborhoods: [{ origin: "First Hill", destination: "Denny-Blaine" }] }, { neighborhoods: [{ origin: "Belltown", destination: "Eastlake" }] }];

array.sort(function (a, b) {
    function getValue(o) { return o.neighborhoods[0].origin; }
    var aa = getValue(a),
        bb = getValue(b);

    return aa > bb || -(aa < bb);
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Get n oldest rows, but no more than x that have the same value in a column
I have a simple table

```<code>CREATE TABLE `example` (
  `id` int(12) NOT NULL,
  `food` varchar(250) NOT NULL
);
</code>```

With the following data

```<code>INSERT INTO `example` (`id`, `food`) VALUES
(1, 'apple'),
(2, 'apple'),
(3, 'apple'),
(4, 'apple'),
(5, 'apple'),
(6, 'apple'),
(7, 'apple'),
(8, 'banana'),
(9, 'banana'),
(10, 'potato'),
(11, 'potato'),
(12, 'potato'),
(13, 'banana'),
(14, 'banana'),
(15, 'banana');
</code>```

I want to get the oldest 10 rows

```<code>SELECT *
FROM example
ORDER BY id ASC
LIMIT 10
</code>```

But I don't want to get more than 5 rows where food has the same value.

My current query receives 7 apple (more than I want), 2 banana, and 1 potato. In the data provided, I'd want to receive 5 apple, 2 banana, and 3 potato.

How can I accomplish this?

Update:

SQL Group BY, Top N Items for each Group is not a duplicate because it involves a different database. In particular, GROUP BY works different in sql-server than it does in MySQL

答:
You can add a count (in reverse) for each food . . . using variables or a correlated subquery.  This will use the latter:</p>

```<code>select t.*
from (select t.*,
             (select count(*) from example t2 where t2.food = t.food and t2.id >= t.id) as seqnum
      from example  t
     ) t
where seqnum <= 5
order by id desc
limit 10;
</code>```

Body:
I have a simple table

CREATE TABLE `example` (
  `id` int(12) NOT NULL,
  `food` varchar(250) NOT NULL
);

With the following data

INSERT INTO `example` (`id`, `food`) VALUES
(1, 'apple'),
(2, 'apple'),
(3, 'apple'),
(4, 'apple'),
(5, 'apple'),
(6, 'apple'),
(7, 'apple'),
(8, 'banana'),
(9, 'banana'),
(10, 'potato'),
(11, 'potato'),
(12, 'potato'),
(13, 'banana'),
(14, 'banana'),
(15, 'banana');

I want to get the oldest 10 rows

SELECT *
FROM example
ORDER BY id ASC
LIMIT 10

But I don't want to get more than 5 rows where food has the same value.

My current query receives 7 apple (more than I want), 2 banana, and 1 potato. In the data provided, I'd want to receive 5 apple, 2 banana, and 3 potato.

How can I accomplish this?

Update:

SQL Group BY, Top N Items for each Group is not a duplicate because it involves a different database. In particular, GROUP BY works different in sql-server than it does in MySQL

Body:
You can add a count (in reverse) for each food . . . using variables or a correlated subquery.  This will use the latter:

select t.*
from (select t.*,
             (select count(*) from example t2 where t2.food = t.food and t2.id >= t.id) as seqnum
      from example  t
     ) t
where seqnum <= 5
order by id desc
limit 10;


问:
Difference between a statement and a query in SQL
I still live in this ambiguity: conceptually what's the difference between a statement and a query in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!

ADDITIONALLY: How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!

答:
From Wikipedia - SQL Language Elements

The SQL language is sub-divided into several language elements, including:

Clauses, which are constituent components of statements and queries. (In some cases, these are optional.)[9]

Expressions, which can produce either scalar values or tables consisting of columns and rows of data.

Predicates, which specify conditions that can be evaluated to SQL three-valued logic (3VL) or Boolean (true/false/unknown) truth values and which are used to limit the effects of statements and queries, or to change program flow.

Queries, which retrieve data based on specific criteria.

Statements, which may have a persistent effect on schemas and data, or which may control transactions, program flow, connections, sessions, or diagnostics.

SQL statements also include the semicolon (";") statement terminator. Though not required on every platform, it is defined as a standard part of the SQL grammar.

Insignificant whitespace is generally ignored in SQL statements and queries, making it easier to format SQL code for readability.


问:
Add enum field to Oracle DB in Java
I have an enum

```<code>public enum HourEmployeePOSITION_TYPE {
None,Cleaner,Waiter, Barmen, Barback, HeadWaiter, Manager, Assistant_Manager,General_Manager}
</code>```

And this enum type is one of the fields of my entity`

```<code> public class
    HourEmployeeEntities {
    private int id;
    private String firstName;
    private String lastName;
    private HourEmployeePOSITION_TYPE position;
</code>```

What I'm trying to do is insert that entity to databse.

```<code> connection = createConnection();
 statement = connection.createStatement();
 statement.execute("CREATE TABLE Employees(" +
                "id int," +
                " firstName varchar(60)," +
                " lastName varchar(60)," +
                " position varchar(60) not null check (position in ('None', 'Cleaner', 'Waiter', 'Barmen', 'Barback', 'HeadWaiter')))"
        );
</code>```

But this way is not working, as it takes the valus as boolean.
`

Are there any other ways to insert my field with enum type into the Oracle DB?

答:
I suggest you to store enum in db as int and use following pattern in your code:

```<code>public interface HasIntId {
    int getId();
}
</code>```

and enum HourEmployeePositionType will be:

```<code>public enum HourEmployeePositionType implements HasIntId {

    None(0),
    Cleaner(1),
    Waiter(2),
    Barmen(3),
    Barback(4),
    HeadWaiter(5),
    Manager(6),
    Assistant_Manager(7),
    General_Manager(8);

    private final int id;

    HourEmployeePositionType(int id) {
        this.id = id;
    }

    @Override
    public int getId() {
        return id;
    }

    public static HourEmployeePositionType getById(int id) {
         for (HourEmployeePositionType employeePositionType : HourEmployeePositionType.values()) {
             if (employeePositionType.getId == id) {
                 return employeePositionType;
             }
         }
         return HourEmployeePositionType.None;
    }
}
</code>```

Title: Add enum field to Oracle DB in Java

Body:
I have an enum

public enum HourEmployeePOSITION_TYPE {
None,Cleaner,Waiter, Barmen, Barback, HeadWaiter, Manager, Assistant_Manager,General_Manager}

And this enum type is one of the fields of my entity`

 public class
    HourEmployeeEntities {
    private int id;
    private String firstName;
    private String lastName;
    private HourEmployeePOSITION_TYPE position;

What I'm trying to do is insert that entity to databse.

 connection = createConnection();
 statement = connection.createStatement();
 statement.execute("CREATE TABLE Employees(" +
                "id int," +
                " firstName varchar(60)," +
                " lastName varchar(60)," +
                " position varchar(60) not null check (position in ('None', 'Cleaner', 'Waiter', 'Barmen', 'Barback', 'HeadWaiter')))"
        );

But this way is not working, as it takes the valus as boolean.
`

Are there any other ways to insert my field with enum type into the Oracle DB?

Body:
I suggest you to store enum in db as int and use following pattern in your code:

public interface HasIntId {
    int getId();
}

and enum HourEmployeePositionType will be:

public enum HourEmployeePositionType implements HasIntId {

    None(0),
    Cleaner(1),
    Waiter(2),
    Barmen(3),
    Barback(4),
    HeadWaiter(5),
    Manager(6),
    Assistant_Manager(7),
    General_Manager(8);

    private final int id;

    HourEmployeePositionType(int id) {
        this.id = id;
    }

    @Override
    public int getId() {
        return id;
    }

    public static HourEmployeePositionType getById(int id) {
         for (HourEmployeePositionType employeePositionType : HourEmployeePositionType.values()) {
             if (employeePositionType.getId == id) {
                 return employeePositionType;
             }
         }
         return HourEmployeePositionType.None;
    }
}


问:
All Material Angular directives come up as 'is not a known element'
I am on an Angular 5 project (5.0.0-rc0) with Angular 5 material (5.0.0-rc0) and for the life of me I can not debug while every single angular 5 material directive is coming up with

mat-xyz is not a known element

Here is what my app.module looks like

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Component } from '@angular/core';
// Import the Http Module and our Data Service
import { DataService } from './data.service';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import 'hammerjs';

import {
  MatAutocompleteModule,
  ...
  MatStepperModule
} from '@angular/material';
import { HttpModule } from '@angular/http';
import { CdkTableModule } from '@angular/cdk/table';
import { LandingComponent } from './sandbox/landing/landing.component';

@NgModule({
  declarations: [
    AppComponent,
    LandingComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  exports: [
    CdkTableModule,
    MatAutocompleteModule,
    ...
    MatTooltipModule,
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

The Landing component has HTML like so

```<code><form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" value="Sushi">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>
</code>```

and it's .ts is the following

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
</code>```

I know its probably something small or stupid, but for the life of me I can not find it

Thanks in advance!

答:
Webstorm has been giving me such a message for the past year and a half that I've worked with Angular.  Doesn't affect anything for me.  It can probably be turned off in the IDE but I'm curious if Webstorm ever gets this figured out.

The message I see is Unknown html tag mat-card... and similar.

Body:
I am on an Angular 5 project (5.0.0-rc0) with Angular 5 material (5.0.0-rc0) and for the life of me I can not debug while every single angular 5 material directive is coming up with

mat-xyz is not a known element

Here is what my app.module looks like

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Component } from '@angular/core';
// Import the Http Module and our Data Service
import { DataService } from './data.service';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import 'hammerjs';

import {
  MatAutocompleteModule,
  ...
  MatStepperModule
} from '@angular/material';
import { HttpModule } from '@angular/http';
import { CdkTableModule } from '@angular/cdk/table';
import { LandingComponent } from './sandbox/landing/landing.component';

@NgModule({
  declarations: [
    AppComponent,
    LandingComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  exports: [
    CdkTableModule,
    MatAutocompleteModule,
    ...
    MatTooltipModule,
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

The Landing component has HTML like so

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" value="Sushi">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>

and it's .ts is the following

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

I know its probably something small or stupid, but for the life of me I can not find it

Thanks in advance!


问:
MobX + React makes me mad
First of all, I am not experienced React developer. Just let you know.

I have a store:

```<code>import {observable, action, reaction, computed, autorun} from 'mobx';
import scrollTo from 'react-scroll-to-component'
</code>```

class ActivePostsStore {

```<code>  @observable _posts = new Map()
  @observable _visiblePosts = new Set()

  @computed get visiblePosts() {
    return this._visiblePosts
  }

  @action
  addPost(uuid, ref) {
    // console.log('add post')
    this._posts.set(uuid, ref)
  }

  @action
  scrollToPost(uuid) {
    // console.log('scroll to post')
    scrollTo(this._posts.get(uuid), {})
  }

  @action
  addVisiblePost(uuid) {
    console.log('add vis post', this._visiblePosts.values())
    this._visiblePosts.add(uuid)
  }

  @action
  removeVisiblePost(uuid) {
    console.log('rem vis post', this._visiblePosts.values())
    this._visiblePosts = new Set([...this._visiblePosts].filter(el => el !== uuid))
  }

  // reacts = reaction(() => this._visiblePosts, () => console.log('===='))
  // reactToVisiblePosts() {
  //
  // }
}

const store = new ActivePostsStore()
export default store
</code>```

My first problem, that I can pass store through Provider in my Layout Component or _document.js (I use Next.js).

```<code>/*Doesn't work. In root layout*/
<Provider store={ActivePostsStore}>
  <Content />
</Provider>
</code>```

Every time when I tried to use Provider I got my store undefined. In RootLayout or _document.js too. Sure, I provided @observer annotation for component which use store. But store is still undefined.

Then, I tried to use @inject('activePostsStore') result is Error, that tells me, like I didn't provide any store at all. But, actually, I did.

SO! I decided to inject it directly like:

```<code>@inject(() => ({
  store: ActivePostsStore
}))
@observer
</code>```

Finally, I can use actions to add or remove elements for visiblePosts (i log it). BUT! My store props does not react at all, if I change state of store. For example it does not react to adding new entries to visiblePosts. Or it even can be undefined if I reload page. My code for component is:

```<code>render() {
    const {classes} = this.props
    return (
      <div className={classNames(classes.postsTree)}>
        {this.props.store.visiblePosts}
        {this.state.groupedDates !== undefined && this.state.groupedDates.map(([date, posts], index) =>
          <PostsTreeGroup
            active={_.some(posts.map(([uuid]) => uuid), uuid => this.props.store.visiblePosts.has(uuid))}
            key={date}
            date={date}
            posts={posts}/>
        )}
      </div>
    )
  }
</code>```

Can somebody help me to make things works, please!

答:
Question1:

Provider only works when you call inject on your component, where you want the store to appear in its props. So you have to call inject, otherwise the store is undefined (because no one set the component's property for your store).

The string you pass to inject must be exactly the property name you gave it in your Provider.

You have:

```<code><Provider store={ActivePostsStore}> // store is the property name
</code>```

So you also have to call

```<code>@inject('store')
</code>```

Then mobx looks for the key store, finds it in your provider and assigns it to your component.

Question2:

You would calculate your visible posts in your store and not the other way round.
So the method visiblePosts only returns visible posts.

Store:

```<code>@computed get visiblePosts() {
  return this._visiblePosts.map(uuid => this._posts.get(uuid));
}
</code>```

Then in your component you can render only the visible posts:

Component:

```<code>this.props.store.visiblePosts.map(post => {
 return <PostsTreeGroup ...>
})
</code>```

I also see you do some sort of sorting?

You would then tell your store how to sort (e.g. set a property ) and then let your store do the sorting in the visiblePosts method.

Title: MobX + React makes me mad

Body:
First of all, I am not experienced React developer. Just let you know.

I have a store:

import {observable, action, reaction, computed, autorun} from 'mobx';
import scrollTo from 'react-scroll-to-component'

class ActivePostsStore {

  @observable _posts = new Map()
  @observable _visiblePosts = new Set()

  @computed get visiblePosts() {
    return this._visiblePosts
  }

  @action
  addPost(uuid, ref) {
    // console.log('add post')
    this._posts.set(uuid, ref)
  }

  @action
  scrollToPost(uuid) {
    // console.log('scroll to post')
    scrollTo(this._posts.get(uuid), {})
  }

  @action
  addVisiblePost(uuid) {
    console.log('add vis post', this._visiblePosts.values())
    this._visiblePosts.add(uuid)
  }

  @action
  removeVisiblePost(uuid) {
    console.log('rem vis post', this._visiblePosts.values())
    this._visiblePosts = new Set([...this._visiblePosts].filter(el => el !== uuid))
  }

  // reacts = reaction(() => this._visiblePosts, () => console.log('===='))
  // reactToVisiblePosts() {
  //
  // }
}

const store = new ActivePostsStore()
export default store

My first problem, that I can pass store through Provider in my Layout Component or _document.js (I use Next.js).

/*Doesn't work. In root layout*/
<Provider store={ActivePostsStore}>
  <Content />
</Provider>

Every time when I tried to use Provider I got my store undefined. In RootLayout or _document.js too. Sure, I provided @observer annotation for component which use store. But store is still undefined.

Then, I tried to use @inject('activePostsStore') result is Error, that tells me, like I didn't provide any store at all. But, actually, I did.

SO! I decided to inject it directly like:

@inject(() => ({
  store: ActivePostsStore
}))
@observer

Finally, I can use actions to add or remove elements for visiblePosts (i log it). BUT! My store props does not react at all, if I change state of store. For example it does not react to adding new entries to visiblePosts. Or it even can be undefined if I reload page. My code for component is:

render() {
    const {classes} = this.props
    return (

        {this.props.store.visiblePosts}
        {this.state.groupedDates !== undefined && this.state.groupedDates.map(([date, posts], index) =>
          <PostsTreeGroup
            active={_.some(posts.map(([uuid]) => uuid), uuid => this.props.store.visiblePosts.has(uuid))}
            key={date}
            date={date}
            posts={posts}/>
        )}

    )
  }

Can somebody help me to make things works, please!

Body:
Question1:

Provider only works when you call inject on your component, where you want the store to appear in its props. So you have to call inject, otherwise the store is undefined (because no one set the component's property for your store).

The string you pass to inject must be exactly the property name you gave it in your Provider.

You have:

<Provider store={ActivePostsStore}> // store is the property name

So you also have to call

@inject('store')

Then mobx looks for the key store, finds it in your provider and assigns it to your component.

Question2:

You would calculate your visible posts in your store and not the other way round.
So the method visiblePosts only returns visible posts.

Store:

@computed get visiblePosts() {
  return this._visiblePosts.map(uuid => this._posts.get(uuid));
}

Then in your component you can render only the visible posts:

Component:

this.props.store.visiblePosts.map(post => {
 return <PostsTreeGroup ...>
})

I also see you do some sort of sorting?

You would then tell your store how to sort (e.g. set a property ) and then let your store do the sorting in the visiblePosts method.


问:
Large eCommerce site: Is it time for HTML5?
I currently work for a large company and I design for their high-traffic ecommerce website. We support tens-of-thousands of users across a variety of browsers. Our current browser stats point to most people using either Firefox 3+ and IE8. There are about 5% of users still on IE6.

Is it time to start coding for the future and impliment HTML5 across the site? Is it a responsible thing to do or should I wait a year for people to upgrade to better supporting browsers?

Thank you.

答:
The name "HTML5" is tending to be used by most people at the moment to describe all the exciting new features in web browsers. Not all of these features are actually part of the HTML5 spec - for example, CSS and Javascript have new features which are being referred to under the HTML5 banner. I'm going to assume you mean all these features.

My answer would be to investigate which features you can implement, but remain backward-compatible. Many of the features of HTML5, CSS3, etc can be added to your site without making it un-usable for older browsers.

Some examples: (but do spend time researching for more)

New input types, such as <input type='date'> and <input type='number'>
These give you new features in a modern browser, but old browsers will still show a normal input field.

More info: http://www.456bereastreet.com/archive/201004/html5_input_types/

Semantic HTML5 tags, such as
, , etc.

These give you additional semantic meaning to your HTML tags, which is good for SEO and other automated systems that look at your site. They are broadly backward-compatible, though in order to support them in IE6/7/8, you will need to include an IE hack such as HTML5Shiv. However, I would suggest using Modernizr, which includes the HTML5Shiv plus a stack of other useful functionality.

Some CSS3 features such as border-radius. IE doesn't know about this, but the result is that IE will have square corners and other browsers will have rounded corners. So nothing that breaks the site for IE users.

But if you really want to, IE can be made to support a number of CSS3 features, including border-radius, using tools such as CSS3Pie.

Instead of using SVG graphics directly, use a Javascript graphics library such as Raphael, which will draw SVG in browsers that support it, and fall back to VML for IE (which will even work in IE6).

Obviously stuff like the <video> or <canvas> tags aren't going to work in older browsers, but frankly, it'll take you long enough just implementing the features you can use straight away; by the time you're ready to take a step further, things will have moved on anyway.

Body:
The name "HTML5" is tending to be used by most people at the moment to describe all the exciting new features in web browsers. Not all of these features are actually part of the HTML5 spec - for example, CSS and Javascript have new features which are being referred to under the HTML5 banner. I'm going to assume you mean all these features.

My answer would be to investigate which features you can implement, but remain backward-compatible. Many of the features of HTML5, CSS3, etc can be added to your site without making it un-usable for older browsers.

Some examples: (but do spend time researching for more)

New input types, such as <input type='date'> and <input type='number'>
These give you new features in a modern browser, but old browsers will still show a normal input field.

More info: http://www.456bereastreet.com/archive/201004/html5_input_types/

Semantic HTML5 tags, such as <section>, <footer>, etc.

These give you additional semantic meaning to your HTML tags, which is good for SEO and other automated systems that look at your site. They are broadly backward-compatible, though in order to support them in IE6/7/8, you will need to include an IE hack such as HTML5Shiv. However, I would suggest using Modernizr, which includes the HTML5Shiv plus a stack of other useful functionality.

Some CSS3 features such as border-radius. IE doesn't know about this, but the result is that IE will have square corners and other browsers will have rounded corners. So nothing that breaks the site for IE users.

But if you really want to, IE can be made to support a number of CSS3 features, including border-radius, using tools such as CSS3Pie.

Instead of using SVG graphics directly, use a Javascript graphics library such as Raphael, which will draw SVG in browsers that support it, and fall back to VML for IE (which will even work in IE6).

Obviously stuff like the <video> or <canvas> tags aren't going to work in older browsers, but frankly, it'll take you long enough just implementing the features you can use straight away; by the time you're ready to take a step further, things will have moved on anyway.


问:
How to use a Boolean variable in an if statement to change text (C#)
So i am trying to create a simple text adventure in unity and i have written a script the changes the state of the text depending on key presses. To try and add a bit of complexity i have attempted to add a system where when in one state it is displayed that an item is picked up and the variable for that item has been set to true which is stated at the top of the script. Then, when the user next enters a different state it is checked to see if the variable is true or false in which if the variable is true different text will be displayed to if it where false. My issue is that every time i enter the state withe the IF statements the variable is automatically set to false no matter what. An answer would be more than appreciated :).

Engine:

```<code>using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextController : MonoBehaviour {

public Text text;
private enum states {cell, floor, CellDoor, mirror, bed, rock, shard};
private states myState;
bool rock;
bool shard;

    // Use this for initialization
    void Start () {
        rock = false;
        shard = false;
        myState = states.cell;
    }

    // Update is called once per frame
    void Update () {
        print (myState);
        if (myState == states.cell){
            state_cell ();
        }else if (myState == states.floor){
            state_floor ();
        }else if (myState == states.CellDoor){
            state_CellDoor ();
        }else if (myState == states.mirror){
           state_mirror ();
        }else if (myState == states.bed){
            state_bed ();
        }else if (myState == states.rock){
            state_rock ();
        }else if (myState == states.shard){
            state_shard ();
        }
    }
</code>```

Variable change:

```<code>void state_rock (){
        rock = true;
        text.text = "You conjure what strength you have and eagerly pry at a slightly loose looking part of the concrete " +
                    "with your blistered hands. Finally a piece breaks free, you drop it into one of your pockets.\n\n" +
                    "You have obtained a rock! \n\n" +
                    "Press R to return to the cell.";
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    print(rock);
</code>```

Statements that don't work:

```<code>void state_mirror (){
    print (rock);
    if (rock = true);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock = false);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    if (Input.GetKeyDown(KeyCode.T)){
        myState = states.shard;
    }

}
</code>```

Console saying item is obtained, 'true'

Console saying that the item has not been obtained for some reason, 'false'

答:
Well, there are several problems in your script.

Lets start with this :

```<code> if (rock = true);{...
</code>```

You need to realize that you are assign rock = true, you need to use double equals to compare. Even more, is advisable to use if(boolVar) , because automatically will execute if it's true.

```<code>if(rock){ do something }
//is the same that
if(rock == true){}
</code>```

Also, another important thing, is that you should not put a ; after the if, because when you do that the code inside the brackets will not be related to the conditional.

Body:
So i am trying to create a simple text adventure in unity and i have written a script the changes the state of the text depending on key presses. To try and add a bit of complexity i have attempted to add a system where when in one state it is displayed that an item is picked up and the variable for that item has been set to true which is stated at the top of the script. Then, when the user next enters a different state it is checked to see if the variable is true or false in which if the variable is true different text will be displayed to if it where false. My issue is that every time i enter the state withe the IF statements the variable is automatically set to false no matter what. An answer would be more than appreciated :).

Engine:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextController : MonoBehaviour {

public Text text;
private enum states {cell, floor, CellDoor, mirror, bed, rock, shard};
private states myState;
bool rock;
bool shard;

    // Use this for initialization
    void Start () {
        rock = false;
        shard = false;
        myState = states.cell;
    }

    // Update is called once per frame
    void Update () {
        print (myState);
        if (myState == states.cell){
            state_cell ();
        }else if (myState == states.floor){
            state_floor ();
        }else if (myState == states.CellDoor){
            state_CellDoor ();
        }else if (myState == states.mirror){
           state_mirror ();
        }else if (myState == states.bed){
            state_bed ();
        }else if (myState == states.rock){
            state_rock ();
        }else if (myState == states.shard){
            state_shard ();
        }
    }

Variable change:

void state_rock (){
        rock = true;
        text.text = "You conjure what strength you have and eagerly pry at a slightly loose looking part of the concrete " +
                    "with your blistered hands. Finally a piece breaks free, you drop it into one of your pockets.\n\n" +
                    "You have obtained a rock! \n\n" +
                    "Press R to return to the cell.";
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    print(rock);

Statements that don't work:

void state_mirror (){
    print (rock);
    if (rock = true);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock = false);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    if (Input.GetKeyDown(KeyCode.T)){
        myState = states.shard;
    }

}

Console saying item is obtained, 'true'

Console saying that the item has not been obtained for some reason, 'false'

Body:
Well, there are several problems in your script.

Lets start with this :

 if (rock = true);{...

You need to realize that you are assign rock = true, you need to use double equals to compare. Even more, is advisable to use if(boolVar) , because automatically will execute if it's true.

if(rock){ do something }
//is the same that
if(rock == true){}

Also, another important thing, is that you should not put a ; after the if, because when you do that the code inside the brackets will not be related to the conditional.


问:
create heatmap for each row in pandas dataframe
Below is a df called "compmatrix":

```<code>             -3.0        -5.0       -7.0
Gain/DD*DD%  0.009000    0.034000   0.088000
Gain/Expsr%  0.487000    0.927000   1.628000
Gain/MaxDD   0.015000    0.021000   0.025000
MaxDD*iBeta  32.633      193.536    856.520
</code>```

I'd like to apply a heatmap to each row (vs. the whole dataframe), because of the big difference in values.

```<code>import seaborn as sns
sns.heatmap(compmatrix,cmap='RdYlGn_r',annot=True)
</code>```

but the fact that there's no axis=1 has thrown me off. Can't seem to find the solution I'm looking for in the documentation.

答:
Found a handy solution to the problem (and no need for seaborn):</p>

```<code>compmatrix.style.background_gradient(cmap='RdYlGn',axis=1)
</code>```

Body:
Below is a df called "compmatrix":

             -3.0        -5.0       -7.0
Gain/DD*DD%  0.009000    0.034000   0.088000
Gain/Expsr%  0.487000    0.927000   1.628000
Gain/MaxDD   0.015000    0.021000   0.025000
MaxDD*iBeta  32.633      193.536    856.520

I'd like to apply a heatmap to each row (vs. the whole dataframe), because of the big difference in values.

import seaborn as sns
sns.heatmap(compmatrix,cmap='RdYlGn_r',annot=True)

but the fact that there's no axis=1 has thrown me off. Can't seem to find the solution I'm looking for in the documentation.

Body:
Found a handy solution to the problem (and no need for seaborn):

compmatrix.style.background_gradient(cmap='RdYlGn',axis=1)


问:
Convert SVG co-ordinate to page co-ordinate in D3 js
I am trying to show an animated tool-tip, changing its position after every 1 second, for multiple graphs.

```<code>var tooltip = d3.select("body")
        .append("div")
        .attr("id", "tooltip")
        .attr("class", "tooltip");
</code>```

As this is a div, translate will not work with this. So, I am trying to translate like this way, with svg co-ordinates.

```<code>tooltip.html("Tooltip")
            .style("left", x(currentTime) + "px")
            .style("top", height + "px");
</code>```

But it takes this as page co-ordinate value.

How to convert SVG co-ordinate to page co-ordinate?
Or is there any other way to create tool-tip as a SVG element?

答:
Assuming your div tooltip is absolutely position, your "page" coordinate is just the position of the svg element plus the position of the thing in the svg element.

Here's a quick example (mouse over the circles):

<!DOCTYPE html>

    <svg
      width="300" height="300"
      style="left: 100px; top: 100px; position: absolute">
    </svg>

      This is my tooltip

```

Body:
I am trying to show an animated tool-tip, changing its position after every 1 second, for multiple graphs.

var tooltip = d3.select("body")
        .append("div")
        .attr("id", "tooltip")
        .attr("class", "tooltip");

As this is a div, translate will not work with this. So, I am trying to translate like this way, with svg co-ordinates.

tooltip.html("Tooltip")
            .style("left", x(currentTime) + "px")
            .style("top", height + "px");

But it takes this as page co-ordinate value.

How to convert SVG co-ordinate to page co-ordinate?
Or is there any other way to create tool-tip as a SVG element?

Body:
Assuming your div tooltip is absolutely position, your "page" coordinate is just the position of the svg element plus the position of the thing in the svg element.

Here's a quick example (mouse over the circles):

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    <svg
      width="300" height="300"
      style="left: 100px; top: 100px; position: absolute">
    </svg>
    <div id="tooltip" style="position: absolute; border: 1px solid black">
      This is my tooltip
    </div>
    <script>
      var json = [
        {x: Math.random() * 300, y: Math.random() * 300},
        {x: Math.random() * 300, y: Math.random() * 300},
        {x: Math.random() * 300, y: Math.random() * 300}
      ];

      var svg = d3.select('svg');

      svg
        .selectAll('circle')
        .data(json)
        .enter()
        .append('circle')
        .attr('cx', function(d){ return d.x })
        .attr('cy', function(d){ return d.y })
        .attr('r', 30)
        .style('fill', 'red')
        .on('mouseover', function(d){
          var svgPos = svg.node().getBoundingClientRect();
          d3.select('#tooltip')
            .style('left', svgPos.left + d.x + 'px')
            .style('top', svgPos.top + d.y + 'px');
        })

    </script>

  </body>

</html>


问:
Convert a Text to an Array - PostgreSQL
im learning PostgreSQL and i encountered a little Problem.

I have a text like this:

```<code>'{1,1}'
</code>```

and want to create an Array that holds my two values, so that i can access them.
How do i do that ?
I tried

```<code>SELECT string_to_array('{1,1}', '{', '}', ',');
</code>```

But that does not seem to work.

答:
'{1,1}' can be casted to an array directly:

```<code>select '{1,1}'::int[]
</code>```

Title: Convert a Text to an Array - PostgreSQL

Body:
im learning PostgreSQL and i encountered a little Problem.

I have a text like this:

'{1,1}'

and want to create an Array that holds my two values, so that i can access them.
How do i do that ?
I tried

SELECT string_to_array('{1,1}', '{', '}', ',');

But that does not seem to work.

Body:
'{1,1}' can be casted to an array directly:

select '{1,1}'::int[]


问:
String Benchmarks in C# - Refactoring for Speed/Maintainability
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

```<code>private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }
</code>```

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```

However, it changes drastically over the longhaul:

With 10,000 Iterations:

```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```

Here's the code after Refactor #1:

```<code>private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }
</code>```

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

```<code>static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }
</code>```

This results in the following Benchmark:

```
MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder
```

Changing the for loop to a foreach loop resulted in the following benchmark result:

```<code>static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }
</code>```

```
RefactoredForEachMakeNiceString    Took:  45163 Ticks
```

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

```<code>static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }
</code>```

Final Benchmark Results:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```0

Or, if you prefer milliseconds:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```1

So the percentage gains are:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```2

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

```<code>       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }
</code>```

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

答:
My first refactoring would be to change the name of the method to something more descriptive. MakeNiceString imo is not a name that would indicate to me what this method does.

How about PascalCaseToSentence? Not loving that name, but it's better than MakeNiceString.

OwnerDisplayName: Gortok

Body:
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks

However, it changes drastically over the longhaul:

With 10,000 Iterations:

MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486

Here's the code after Refactor #1:

private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }

This results in the following Benchmark:

MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder

Changing the for loop to a foreach loop resulted in the following benchmark result:

static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }

RefactoredForEachMakeNiceString    Took:  45163 Ticks

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }

Final Benchmark Results:

MakeNiceString Took                   139363 Ticks
SplitCamelCase Took                   489174 Ticks
ImprovedMakeNiceString Took           115478 Ticks
RefactoredMakeNiceString Took          38819 Ticks
RefactoredForEachMakeNiceString Took   44700 Ticks
CompiledRegex Took                    227021 Ticks

Or, if you prefer milliseconds:

MakeNiceString Took                  38 ms
SplitCamelCase Took                 123 ms
ImprovedMakeNiceString Took          33 ms
RefactoredMakeNiceString Took        11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took                   63 ms

So the percentage gains are:

MakeNiceString                   38 ms   Baseline
SplitCamelCase                  123 ms   223% slower
ImprovedMakeNiceString           33 ms   13.15% faster
RefactoredMakeNiceString         11 ms   71.05% faster
RefactoredForEachMakeNiceString  12 ms   68.42% faster
CompiledRegex                    63 ms   65.79% slower

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

LastEditorDisplayName: Gortok


答: Queries is used for retrieve data based on specific criteria, but statement may have a persistent effect on schemas and data, or which may control transactions, program flow, connections, sessions, or diagnostics. See also Wikipedia.

Title: Difference between a statement and a query in SQL

Body:
I still live in this ambiguity: conceptually what's the difference between a statement and a query in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!

ADDITIONALLY: How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!


问:
How do I get a ball to glide in python tkinter?
I have this program that I tried to make in python tkinter. A ball would appear on screen and every time I click I want the ball to glide to the point at which I clicked. The x and y locations of the ball changed but the ball only redraws after the ball is finished "moving." Can someone tell me what I am doing wrong.</p>

```<code>from tkinter import *
import time
width = 1280
height = 700
ballRadius = 10
iterations = 100
mouseLocation = [width/2, height/2]
ballLocation = [width/2, height/2]

root = Tk()

def drawBall(x, y):
    canvas.delete(ALL)
    canvas.create_oval(x - ballRadius, y - ballRadius, x + ballRadius, y + ballRadius, fill="blue")
    print(x, y)

def getBallLocation(event):
    mouseLocation[0] = event.x
    mouseLocation[1] = event.y
    dx = (ballLocation[0] - mouseLocation[0]) / iterations
    dy = (ballLocation[1] - mouseLocation[1]) / iterations
    for i in range(iterations):
        ballLocation[0] -= dx
        ballLocation[1] -= dy
        drawBall(round(ballLocation[0]), round(ballLocation[1]))
        time.sleep(0.02)
    ballLocation[0] = event.x
    ballLocation[1] = event.y

canvas = Canvas(root, width=width, height=height, bg="black")
canvas.pack()
canvas.create_oval(width/2-ballRadius, height/2-ballRadius, width/2+ballRadius, height/2+ballRadius, fill="blue")
canvas.bind("<Button-1>", getBallLocation)

root.mainloop()
</code>```

答:
In your code time.sleep pauses the entire GUI, that's why you don't see the intermediate locations of the ball. Instead you can construct a function with widget.after method. Try the following:

```<code>    print(x, y)

dx = 0
dy = 0
def getBallLocation(event):
    canvas.unbind("<Button-1>")
    global dx, dy
    mouseLocation[0] = event.x
    mouseLocation[1] = event.y
    dx = (ballLocation[0] - mouseLocation[0]) / iterations
    dy = (ballLocation[1] - mouseLocation[1]) / iterations
    draw()

i = 0
def draw():
    global i
    ballLocation[0] -= dx
    ballLocation[1] -= dy
    drawBall(round(ballLocation[0]), round(ballLocation[1]))
    if i < iterations-1:
        canvas.after(20, draw)
        i += 1
    else:
        canvas.bind("<Button-1>", getBallLocation)
        i = 0

canvas = Canvas(root, width=width, height=height, bg="black")
</code>```

Body:
I have this program that I tried to make in python tkinter. A ball would appear on screen and every time I click I want the ball to glide to the point at which I clicked. The x and y locations of the ball changed but the ball only redraws after the ball is finished "moving." Can someone tell me what I am doing wrong.

from tkinter import *
import time
width = 1280
height = 700
ballRadius = 10
iterations = 100
mouseLocation = [width/2, height/2]
ballLocation = [width/2, height/2]

root = Tk()

def drawBall(x, y):
    canvas.delete(ALL)
    canvas.create_oval(x - ballRadius, y - ballRadius, x + ballRadius, y + ballRadius, fill="blue")
    print(x, y)

def getBallLocation(event):
    mouseLocation[0] = event.x
    mouseLocation[1] = event.y
    dx = (ballLocation[0] - mouseLocation[0]) / iterations
    dy = (ballLocation[1] - mouseLocation[1]) / iterations
    for i in range(iterations):
        ballLocation[0] -= dx
        ballLocation[1] -= dy
        drawBall(round(ballLocation[0]), round(ballLocation[1]))
        time.sleep(0.02)
    ballLocation[0] = event.x
    ballLocation[1] = event.y

canvas = Canvas(root, width=width, height=height, bg="black")
canvas.pack()
canvas.create_oval(width/2-ballRadius, height/2-ballRadius, width/2+ballRadius, height/2+ballRadius, fill="blue")
canvas.bind("<Button-1>", getBallLocation)

root.mainloop()

Body:
In your code time.sleep pauses the entire GUI, that's why you don't see the intermediate locations of the ball. Instead you can construct a function with widget.after method. Try the following:

    print(x, y)

dx = 0
dy = 0
def getBallLocation(event):
    canvas.unbind("<Button-1>")
    global dx, dy
    mouseLocation[0] = event.x
    mouseLocation[1] = event.y
    dx = (ballLocation[0] - mouseLocation[0]) / iterations
    dy = (ballLocation[1] - mouseLocation[1]) / iterations
    draw()

i = 0
def draw():
    global i
    ballLocation[0] -= dx
    ballLocation[1] -= dy
    drawBall(round(ballLocation[0]), round(ballLocation[1]))
    if i < iterations-1:
        canvas.after(20, draw)
        i += 1
    else:
        canvas.bind("<Button-1>", getBallLocation)
        i = 0

canvas = Canvas(root, width=width, height=height, bg="black")


问:
Using Grep and Regex to generate a text file which lists all files that have specific strings in them
I am having trouble figuring out a very specific use case for Grep and Regex.  I have searched a lot and can't seem to find the answer.

I want to run Grep recursively from within a root directory which contains directories for hundreds of different programs.  I want the output to print to a text file and list the file names of all the files which match some regex.  Specifically, here's what I need to do in english:

find all files that contain the text [stringA] AND ["stringB"] OR ['stringB'] and print the file paths for each of these files to an output text file with some context added.  For the two stringB pieces, the quotes are important and I only want to find files that have stringB with single or double quotes around it.  In other words,

all files that contain stringA with no quotes and stringB with either single or double quotes.

Any help is appreciated, thanks!

Edit: Sorry for asking a terrible question :)

I have done some research and have figured out part of it.  I have figured out the regex for finding the string I am looking for.  The actual string is "ATA".  To find this globally, case-insensitive, and with either type of quotes around it with some or no whitespace on either side of the string, we can use:

```<code>/['"]\s*ATA\s*['"]/gi
</code>```

The first string I need to also find is a function call: call wflnkmod( and the regex for that is:

```<code>/call\swflnkmod\(/gi
</code>```

Now I just need to figure out how to search a file and ensure that it has an instance of each of these in it, then figure out the grep command to use to search all files recursively and print them to an output file!

答:
for AND search it's better to chain greps, OR can be handled.

Assume we are looking for words cat and "ata" or 'ata'.  If you're only interested in the filenames, not the actual matches...

```<code>grep -wilm1 cat file* | xargs  grep -wilEm1 "'ata'|\"ata\""

file1
file2
</code>```

searches for the full word match -w (not substrings), exits after first match -m1  and ignores cases (-i).  The OR requires -E flag.  -l prints the filenames only.

here are the files used for testing.

```<code>==> file1 <==
cat
fat hat "ata"

==> file2 <==
cat fat hat 'ata'

==> file3 <==
cat fat hat ata

==> file4 <==
category fat hat ata
</code>```

Body:
I am having trouble figuring out a very specific use case for Grep and Regex.  I have searched a lot and can't seem to find the answer.

I want to run Grep recursively from within a root directory which contains directories for hundreds of different programs.  I want the output to print to a text file and list the file names of all the files which match some regex.  Specifically, here's what I need to do in english:

find all files that contain the text [stringA] AND ["stringB"] OR ['stringB'] and print the file paths for each of these files to an output text file with some context added.  For the two stringB pieces, the quotes are important and I only want to find files that have stringB with single or double quotes around it.  In other words,

all files that contain stringA with no quotes and stringB with either single or double quotes.

Any help is appreciated, thanks!

Edit: Sorry for asking a terrible question :)

I have done some research and have figured out part of it.  I have figured out the regex for finding the string I am looking for.  The actual string is "ATA".  To find this globally, case-insensitive, and with either type of quotes around it with some or no whitespace on either side of the string, we can use:

/['"]\s*ATA\s*['"]/gi

The first string I need to also find is a function call: call wflnkmod( and the regex for that is:

/call\swflnkmod\(/gi

Now I just need to figure out how to search a file and ensure that it has an instance of each of these in it, then figure out the grep command to use to search all files recursively and print them to an output file!

Body:
for AND search it's better to chain greps, OR can be handled.

Assume we are looking for words cat and "ata" or 'ata'.  If you're only interested in the filenames, not the actual matches...

grep -wilm1 cat file* | xargs  grep -wilEm1 "'ata'|\"ata\""

file1
file2

searches for the full word match -w (not substrings), exits after first match -m1  and ignores cases (-i).  The OR requires -E flag.  -l prints the filenames only.

here are the files used for testing.

==> file1 <==
cat
fat hat "ata"

==> file2 <==
cat fat hat 'ata'

==> file3 <==
cat fat hat ata

==> file4 <==
category fat hat ata


问:
Continuously render numpy arrays in loop
I have code that runs in a while loop and returns a new numpy array on every iteration. I would like to continuously render that array to an onscreen window.

Based on Displaying Numpy Matrix as Video, Is there a way to detach matplotlib plots so that the computation can continue?, How to update matplotlib's imshow() window interactively?, and real-time plotting in while loop with matplotlib, this is my best attempt:

```<code>import matplotlib.pyplot as plt
import numpy as np

# plt.ion()
image = np.zeros((800, 800))
im = plt.imshow(image)
while True:
    image += .01
    im.set_data(image)
    plt.pause(0.05)
plt.show()
</code>```

It does not work (for some reason it just renders a purple square that does not change color). I am using ImageMagick on Ubuntu 16.04. Thank you for your assistance.

答:
Simple correction:

```<code>image = np.zeros((800, 800, 3))
</code>```

Now it works.

Body:
I have code that runs in a while loop and returns a new numpy array on every iteration. I would like to continuously render that array to an onscreen window.

Based on Displaying Numpy Matrix as Video, Is there a way to detach matplotlib plots so that the computation can continue?, How to update matplotlib's imshow() window interactively?, and real-time plotting in while loop with matplotlib, this is my best attempt:

import matplotlib.pyplot as plt
import numpy as np

# plt.ion()
image = np.zeros((800, 800))
im = plt.imshow(image)
while True:
    image += .01
    im.set_data(image)
    plt.pause(0.05)
plt.show()

It does not work (for some reason it just renders a purple square that does not change color). I am using ImageMagick on Ubuntu 16.04. Thank you for your assistance.

Body:
Simple correction:

image = np.zeros((800, 800, 3))

Now it works.


问:
-webkit-background-clip:text not work in Android phone
it seems that the css3 -webkit-background-clip:text, don`t work in the Android phone with webkit core blowers. Because I want to make the text with  the gradient effect, the -webkit-background-clip:text  just work well in PC. is it really like so? Is there somebody to  help with this issue, thanks! </p>

答:
I faced a similar case on a Android Lollipop device. I had used -webkit-background-clip:text on a <button> tag. It worked well in chromium browser, and it even worked on a Android Marshmallow device. But the same clip effect won't appear on that lollipop device. After hours, fixed it by changing <button> tag to a
 and it worked. Not sure if this could be your case, if not, post your css code.

Body: I faced a similar case on a Android Lollipop device. I had used -webkit-background-clip:text on a <button> tag. It worked well in chromium browser, and it even worked on a Android Marshmallow device. But the same clip effect won't appear on that lollipop device. After hours, fixed it by changing <button> tag to a <div> and it worked. Not sure if this could be your case, if not, post your css code.


问:
Maintaining binary compatibility with previous versions
Apologies if this is more Server Fault than SO, but it is related to coding so here goes...

I have someone else's code that I am trying to compile on RHEL 7 but will run (for the moment at least) on RHEL 6. I've written my own RPM spec file to build and output an RPM file. The RPM builds fine on both RHEL 6 and RHEL 7 but when I build it on RHEL 7, does not produce an RPM which can be installed on RHEL 6 due to versions of GLIBC.

Is there a simple switch I can add to the build somewhere which will allow the resulting binary to be satisfied with an earlier version of GLIBC and be able to be installed on RHEL 6?

To be clear, I don't actually need a RHEL 7 binary at present, I'd just like to be able to compile for RHEL 6 on a RHEL 7 dev box.

答:
You can use mock (sadly only in EPEL) to create a Red Hat Enterprise Linux 6 chroot on your Red Hat Enterprise Linux 7 system.  If you use only libraries with Tier 1 ABI compatibility, your application will continue to run on Red Hat Enterprise Linux 7 without recompilation.  Building on the oldest supported release (from the application point of view) is really the only way to do this.  If you need a more recent C++ compiler and that's the reason why you are building on Red Hat Enterprise Linux 7, consider using Developer Toolset (DTS) instead.

Tier 1 libraries are described in the Application Compatibility Guide.  There is supposed to be a PDF attachment with the previous list of packages, but I cannot access this right now.


问:
Auto add history table into view in SQL Server
We have a history view which has tables for 2011, 2012, ...., 2017.

When the time passes to 2018, we need to add the 2018 table into the view.

The definition for the table is like:

```<code>create view v_a
as
   select id, name, 1 from 2011
   union all
   select id, name, 1 from 2012
   ....
   union all
   select id, name, 1 from 2017
</code>```

I want the view changing to

```<code>create view v_a
as
    select id, name, 1 from 2011
    union all
    select id, name, 1 from 2012
    ....
    union all
    select id, name, 1 from 2017
    union all
    select id, name, 1 from 2018
</code>```

How can I implement it by using an automatic script?

答:
You have to create an SQL Agent Job that run the following SQL command (build command dynamically):</p>

```<code>DECLARE @intCurrentYEAR as INTEGER
DECLARE @intInitialYEAR as INTEGER
DECLARE @strQuery VARCHAR(MAX)

SELECT @intCurrentYEAR = YEAR(GETDATE())
SET @intInitialYEAR = 2011

SET @strQuery = 'Alter view v_a as select id,name,1 from [' + CAST (@intInitialYEAR AS VARCHAR(4)) + '] '

SET @intInitialYEAR = @intInitialYEAR + 1

WHILE @intInitialYEAR <= @intCurrentYEAR
BEGIN

SET @strQuery = @strQuery + ' UNION ALL select id,name,1 from [' + CAST (@intInitialYEAR AS VARCHAR(4)) + '] '

SET @intInitialYEAR = @intInitialYEAR + 1

END

EXEC(@strQuery)
</code>```

Body:
We have a history view which has tables for 2011, 2012, ...., 2017.

When the time passes to 2018, we need to add the 2018 table into the view.

The definition for the table is like:

create view v_a
as
   select id, name, 1 from 2011
   union all
   select id, name, 1 from 2012
   ....
   union all
   select id, name, 1 from 2017

I want the view changing to

create view v_a
as
    select id, name, 1 from 2011
    union all
    select id, name, 1 from 2012
    ....
    union all
    select id, name, 1 from 2017
    union all
    select id, name, 1 from 2018

How can I implement it by using an automatic script?

Body:
You have to create an SQL Agent Job that run the following SQL command (build command dynamically):

DECLARE @intCurrentYEAR as INTEGER
DECLARE @intInitialYEAR as INTEGER
DECLARE @strQuery VARCHAR(MAX)

SELECT @intCurrentYEAR = YEAR(GETDATE())
SET @intInitialYEAR = 2011

SET @strQuery = 'Alter view v_a as select id,name,1 from [' + CAST (@intInitialYEAR AS VARCHAR(4)) + '] '

SET @intInitialYEAR = @intInitialYEAR + 1

WHILE @intInitialYEAR <= @intCurrentYEAR
BEGIN

SET @strQuery = @strQuery + ' UNION ALL select id,name,1 from [' + CAST (@intInitialYEAR AS VARCHAR(4)) + '] '

SET @intInitialYEAR = @intInitialYEAR + 1

END

EXEC(@strQuery)


问:
How to convert an .aar file into a .jar
To work with Eclipse IDE in for an IBM MobileFirst Platform project, I need to convert an .aar file into a .jar. I tried to extract the classes.jar file, but it is practically empty, with none class. I mean, at the Android SDK, the extras/android/m2repository/com/android/support/support-v4 libraries only have classes until 24.1 version, from there all the versions bellow, only have the empty classes.jar file. So, what can I do with the classes in these versions?

Trying to clarify a little bit this topic, this question helped me:

Android Archive Library (aar) vs standard jar

Some one knows a process to turn this Android Archive file into a Java Archive file?

答:
I need to convert an .aar file into a .jar

By definition, an AAR is not a JAR and cannot necessarily be "converted" into a JAR.

Frequently, if the artifact is distributed as an AAR, instead of a JAR, that is because there is more than just Java code that is part of the artifact.

I mean, at the Android SDK, the extras/android/m2repository/com/android/support/support-v4 libraries only have classes until 24.1 version

Correct. Since then, support-v4 has merely been a container for transitive dependencies. You will see a list of them in the POM file adjacent to the artifact.

For example, the 25.3.1 POM file shows all of the artifacts that will be pulled in when you use support-v4 in an AAR-artifact-aware IDE (Android Studio, IntelliJ IDEA, etc.):

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.android.support</groupId>
  <artifactId>support-v4</artifactId>
  <version>25.3.1</version>
  <packaging>aar</packaging>
  <dependencies>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-compat</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-media-compat</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-core-utils</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-core-ui</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-fragment</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>
</code>```

As you can see from the <type> elements, most of those transitive dependencies themselves are AARs.

Sometimes, the AAR does not contain much other than a JAR.
For example, the 25.3.1 edition of support-core-utils — one of the AARs that support-v4 pulls in — has nothing of importance other than its classes.jar that I can see.

However, other AARs have things beyond the JAR. For example, support-compat and support-media-compat have AIDL files. Other AARs — such as appcompat-v7 — have resources or assets. If you try just using the JAR out of the AAR, and you try using a class that expects those resources or AIDL files or whatever to exist, your app will crash.

You can attempt to convert an AAR into an old-style Eclipse library project. As the saying goes, your mileage may vary. Plus, I have no idea if IBM MobileFirst supports library projects.

Title: How to convert an .aar file into a .jar

Body:
I need to convert an .aar file into a .jar

By definition, an AAR is not a JAR and cannot necessarily be "converted" into a JAR.

Frequently, if the artifact is distributed as an AAR, instead of a JAR, that is because there is more than just Java code that is part of the artifact.

I mean, at the Android SDK, the extras/android/m2repository/com/android/support/support-v4 libraries only have classes until 24.1 version

Correct. Since then, support-v4 has merely been a container for transitive dependencies. You will see a list of them in the POM file adjacent to the artifact.

For example, the 25.3.1 POM file shows all of the artifacts that will be pulled in when you use support-v4 in an AAR-artifact-aware IDE (Android Studio, IntelliJ IDEA, etc.):

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.android.support</groupId>
  <artifactId>support-v4</artifactId>
  <version>25.3.1</version>
  <packaging>aar</packaging>
  <dependencies>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-compat</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-media-compat</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-core-utils</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-core-ui</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>support-fragment</artifactId>
      <version>25.3.1</version>
      <type>aar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

As you can see from the <type> elements, most of those transitive dependencies themselves are AARs.

Sometimes, the AAR does not contain much other than a JAR.
For example, the 25.3.1 edition of support-core-utils — one of the AARs that support-v4 pulls in — has nothing of importance other than its classes.jar that I can see.

However, other AARs have things beyond the JAR. For example, support-compat and support-media-compat have AIDL files. Other AARs — such as appcompat-v7 — have resources or assets. If you try just using the JAR out of the AAR, and you try using a class that expects those resources or AIDL files or whatever to exist, your app will crash.

You can attempt to convert an AAR into an old-style Eclipse library project. As the saying goes, your mileage may vary. Plus, I have no idea if IBM MobileFirst supports library projects.