问:
Route file failing to update in Express.js
I am new to using both Node and Express.

Express.js looked great, so I created a local deployment of a vanilla install.

Visiting http://localhost:3000/users prints the expected message:

respond with a resource

I try changing the text to this instead:

respond with no resource

But the change is not made. This is the contents of users.js, almost exactly the same as default:

```<code>var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with no  resource');
});

module.exports = router;
</code>```

And here is a screenshot. Top left is the above code. Bottom left demonstrates a grep for "respond with a resource" failing to produce any results. The right hand side is my browser displaying old data.

What am I doing wrong that the data is not updating?

答:
Your application will not automatically update if you use node <path/to/main>.js to run your application. node will run your application in the form it was when initially started, until that process is terminated.

The most common way to address this is by using a process manager, the most popular one used during development is nodemon. To use nodemon,  install it globally on your machine using npm i -g nodemon (you'll probably need admin rights to do this). Then, run your application using nodemon instead of node.

nodemon <path/to/main>.js

Body:
I am new to using both Node and Express.

Express.js looked great, so I created a local deployment of a vanilla install.

Visiting http://localhost:3000/users prints the expected message:

respond with a resource

I try changing the text to this instead:

respond with no resource

But the change is not made. This is the contents of users.js, almost exactly the same as default:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with no  resource');
});

module.exports = router;

And here is a screenshot. Top left is the above code. Bottom left demonstrates a grep for "respond with a resource" failing to produce any results. The right hand side is my browser displaying old data.

What am I doing wrong that the data is not updating?


来源: stackexchange

问:
Converting an IEnumerable<string> to IEnumerable<ListItem>
I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable'
  to
  'System.Web.UI.WebControls.ListItem'

```<code>public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}
</code>```

答:
```<code>private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        return results.Select(x => new ListItem(x));
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable'
  to
  'System.Web.UI.WebControls.ListItem'

public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}

ContentLicense: CC BY-SA 2.5


问:
Getting started with Play 2.0 -- Cannot find symbol: play.db.jpa.Model
I'm getting started with Play 2.0 by following along with the tutorial. I'm hitting an early roadblock though. When I try play test, I'm hitting a compiler error:

```<code>[error] /Users/spoletto/Desktop/historical/kleio/app/models/Student.java:9: cannot find symbol
[error] symbol  : class Model
[error] location: package play.db.jpa
[error] public class Student extends play.db.jpa.Model {
</code>```

Likewise, in Eclipse, it's not finding the Model class (though it is finding the play.db.jpa package). I know I'm probably missing something really basic, but I'm stumped. Any help would be much appreciated.

答:
I got issues on latest with Play 2.6. Had to update build.sbt with

```<code>libraryDependencies ++= Seq(
  javaJdbc,
  guice,
  "org.postgresql" % "postgresql" % "9.3-1102-jdbc41"
)
</code>```

And then in the class files re route imports on example code:

This import didn't work import play.db.*;

Switched to

```<code>import play.libs.concurrent.CustomExecutionContext;
import play.api.db.*;
</code>```

Now it compiles. Hopefully I can figure out the rest ok

ContentLicense: CC BY-SA 3.0

Body:
I'm getting started with Play 2.0 by following along with the tutorial. I'm hitting an early roadblock though. When I try play test, I'm hitting a compiler error:

[error] /Users/spoletto/Desktop/historical/kleio/app/models/Student.java:9: cannot find symbol
[error] symbol  : class Model
[error] location: package play.db.jpa
[error] public class Student extends play.db.jpa.Model {

Likewise, in Eclipse, it's not finding the Model class (though it is finding the play.db.jpa package). I know I'm probably missing something really basic, but I'm stumped. Any help would be much appreciated.

Body:
I got issues on latest with Play 2.6. Had to update build.sbt with

libraryDependencies ++= Seq(
  javaJdbc,
  guice,
  "org.postgresql" % "postgresql" % "9.3-1102-jdbc41"
)

And then in the class files re route imports on example code:

This import didn't work import play.db.*;

Switched to

import play.libs.concurrent.CustomExecutionContext;
import play.api.db.*;

Now it compiles. Hopefully I can figure out the rest ok


问:
Swift : Can I use home and work locations using MapKit?
Everyone knows that Maps app can detect your home and work location and it shows you with "maps destination" feature. I am just wondering how it gets our specific location like work and home. Is it because we are stable on some places and it figures out we live here and we work there in specific time?

I'm also wondering that how can we get detected datas from the maps. Is it possible that I can use home and work locations on my app, using MapKit?

答: No you cannot, since it’s confidential users data. Only apples map app can use it</p>


问:
What is the sequence of calls of copy constructor in a multi-level inheritance?
I have been trying to figure this out rigorously. Given three classes inheriting from each other, how does the sequence work?
For eg: Classes Vehicle->Car->Mercedes</p>

答:
First bases, explicit and inherited, are constructed, then member variables, both in left-to-right order. So, if you have

```<code>class Base0;
class Subbase;
class Base1: Subbbase;
struct Der: Base0, Base1 {
    Der();
    Type member1;
    Type member2;
};
</code>```

then the order of initialization is Base0 -> Subbase -> Base1 -> member1 -> member2, then goes the ctor body (by which moment all bases and members have already been initialized).

Destructor works in reverse: body -> member2 -> member1 -> Base1 -> Subbase -> Base0.

Body:
First bases, explicit and inherited, are constructed, then member variables, both in left-to-right order. So, if you have

class Base0;
class Subbase;
class Base1: Subbbase;
struct Der: Base0, Base1 {
    Der();
    Type member1;
    Type member2;
};

then the order of initialization is Base0 -> Subbase -> Base1 -> member1 -> member2, then goes the ctor body (by which moment all bases and members have already been initialized).

Destructor works in reverse: body -> member2 -> member1 -> Base1 -> Subbase -> Base0.


问:
How to get the string value of a NSScrollView in Swift (OSX)?
I would like to get the string value of a NSScrollView object, but I can’t find any function, is there a way to get the string value?</p>

答:
I know this is an old question, but I just ran into the same problem and I believe I know what the OP did to get confused:

I come from an iOS background and I'm not used to the extra UI control layers used in IB for Mac OS development.  When you drag a text view from the palette to the canvas, it gives it to you embedded in a scrollview...and when I hooked up the outlets, I wasn't paying attention, and connected the scroll view rather than the text view.

I had to go back to my storyboard, drill down into the scroll view that housed my text view, and hook up the outlet with the actual text view.  Once I did that, yes, there is a .string property that is exactly what most people will want.


问:
How to resolve "IndexError: string index out of range" error in python?
I use the following code to read data from a text file, and add some lines in between of some of the lines, but after running the code, before doing that, I get an error as mentioned bellow.

The data in the text file is converted from csv file and are comma separeted.

```<code>import os
import re
import time
from datetime import datetime

file_list = []
file_counter = 1
for filename in os.listdir(os.getcwd()):
    file_list.append(filename)

for filename in file_list:
    if(filename=='q.py'):   continue
    file = open(filename,"r").read().split('\n')
    file_to_write = "file" +str(file_counter) +".txt"
    file_w = open(file_to_write,"w")
    file_w.write(file[0])
    file_w.write("\n")
    number_of_lines = sum(1 for _ in file)
    lis = []
    for i in range(number_of_lines):
        lis.append(file[i])
    modified_time = []
    for i in range(number_of_lines):
        line = lis[i].split(' ')

        if(line[0]=='name' or line[0]==''):
            continue;
        temp1 = ""
        temp1+=line[2][0]
        temp1+=line[2][1]
        temp1+=line[2][2]
        temp1+=line[2][3]
        temp1+=line[2][4]
        temp1+=line[2][5]
        temp1+='0'
        temp1+='0'
        line[2] = temp1
        try:
            modified_time.append(line[0]+' '+line[1]+' '+line[2]+'
'+line[3]+' '+line[4]+' '+line[5])
        except:
            continue

    for i in range(len(modified_time)-1):
        line1 = modified_time[i].split(' ')
        if(line1[0]=='name' or line1[0]==''):
            continue;
        line2 = modified_time[i+1].split(' ')
        date1 = line1[1]
        date2 = line2[1]
        time1 = line1[2]
        time2 = line2[2]
        day1 = datetime.strptime(date1, '%Y/%m/%d').date()
        day2 = datetime.strptime(date2, '%Y/%m/%d').date()
        diff1 = (day2-day1).days*24*60

        format = '%H:%M:%S'
        startDateTime = datetime.strptime(time1, format)
        endDateTime = datetime.strptime(time2, format)

        diff2 = endDateTime-startDateTime
        diff2 = diff2.seconds/60

        diff =  diff1 + int(diff2)

        lis_written = line1[0] + ' ' + line1[1] + ' ' + line1[2] + ' ' +
line1[3] + ' ' + line1[4] + ' ' + line1[5] + '\n';
        file_w.write(lis_written)
        format = '%Y/%m/%d %H:%M:%S'
        time_counter = datetime.strptime(line1[1]+' '+line1[2], format)

        from datetime import timedelta

        for i in range(diff-1):
            time_counter = time_counter +timedelta(0,60)
            time_value = str(time_counter)
            time_value = time_value.split(' ')
            giventime = time_value[1]
            givendate = time_value[0]

            temp_str = ""
            temp_str+=givendate[0]
            temp_str+=givendate[1]
            temp_str+=givendate[2]
            temp_str+=givendate[3]
            temp_str+='/'
            temp_str+=givendate[5]
            temp_str+=givendate[6]
            temp_str+='/'
            temp_str+=givendate[8]
            temp_str+=givendate[9]

            lis_written = line1[0] + ' ' + temp_str + ' ' + giventime + ' ' +
str(-999) + ' ' + line1[4] + ' ' + line1[5] + '\n';
            file_w.write(lis_written)

    file_w.write(file[len(file)-1])
    file_w.write("\n")
    file_counter+=1
</code>```

This is the error I get at line 33:

```<code>Traceback (most recent call last):
  File "C:\Users\bxr5813\Desktop\time series\run\New folder\New folder\q.py",
line 33, in <module>
    temp1+=line[2][4]
IndexError: string index out of range
</code>```

The format of the input text file is as follows:

```<code>Value Date Time MilliSecond
919 04/15/16 19:41:02 700682752
551 04/15/16 19:46:51 014109952
717 04/15/16 19:49:48 333956864
2679 04/15/16 19:52:49 8053952
2890 04/15/16 19:55:43 73351552
2897 04/15/16 19:58:38 257767936
1790 04/15/16 21:39:14 13785728
2953 04/15/16 21:42:10 801841152
2516 04/15/16 21:45:04 467205376
2530 04/15/16 21:47:58 688858368
2951 04/15/16 21:51:02 6165952
2954 04/15/16 21:53:56 48836992
2537 04/15/16 21:56:52 105879296
2523 04/15/16 21:59:45 920951808
2536 04/15/16 22:02:49 103219968
2727 04/15/16 22:05:43 708147456
2554 04/15/16 22:11:48 323045888
2703 04/15/16 22:14:46 932627712
2958 04/15/16 22:17:40 574788352
2683 04/15/16 22:20:34 7734976
2542 04/15/16 22:23:29 353888512
2536 04/15/16 22:29:15 787323136
</code>```

答:
Have you tried debugging? I think you should change if(line[0]=='name' or line[0]==''): to if(line[0]=='Value' or line[0]==''): and you get Index Error because the code tries to copy the fourth index of 'Time' in the first loop.

Also, your code seems like it needs a bit of simplification. For example, you can write

```<code>file_list = []
for filename in os.listdir(os.getcwd()):
    file_list.append(filename)
</code>```

as file_list = [i for i in os.listdir(os.getcwd())].

You can also simplify

```<code>temp1 = ""
temp1+=line[2][0]
temp1+=line[2][1]
temp1+=line[2][2]
temp1+=line[2][3]
temp1+=line[2][4]
temp1+=line[2][5]
temp1+='0'
temp1+='0'
line[2] = temp1
</code>```

to line[2] = line[2][:5] + '00'.

line[0]+' '+line[1]+' '+line[2]+' '+line[3]+' '+line[4]+' '+line[5] + '\n' can be modified to ' '.join(modified_time) + '\n', and line array seems like it has index 3 as maximum, not 5.

Also, it is recommended for you to close your files opened to read or write if you don't use file anymore, using file_used.close().

I haven't debugged throughout the program, but I think you need to debug your code. I recommend you to use Visual Studio Code program. It's quite useful.

Body:
I use the following code to read data from a text file, and add some lines in between of some of the lines, but after running the code, before doing that, I get an error as mentioned bellow.

The data in the text file is converted from csv file and are comma separeted.

import os
import re
import time
from datetime import datetime

file_list = []
file_counter = 1
for filename in os.listdir(os.getcwd()):
    file_list.append(filename)

for filename in file_list:
    if(filename=='q.py'):   continue
    file = open(filename,"r").read().split('\n')
    file_to_write = "file" +str(file_counter) +".txt"
    file_w = open(file_to_write,"w")
    file_w.write(file[0])
    file_w.write("\n")
    number_of_lines = sum(1 for _ in file)
    lis = []
    for i in range(number_of_lines):
        lis.append(file[i])
    modified_time = []
    for i in range(number_of_lines):
        line = lis[i].split(' ')

        if(line[0]=='name' or line[0]==''):
            continue;
        temp1 = ""
        temp1+=line[2][0]
        temp1+=line[2][1]
        temp1+=line[2][2]
        temp1+=line[2][3]
        temp1+=line[2][4]
        temp1+=line[2][5]
        temp1+='0'
        temp1+='0'
        line[2] = temp1
        try:
            modified_time.append(line[0]+' '+line[1]+' '+line[2]+'
'+line[3]+' '+line[4]+' '+line[5])
        except:
            continue

    for i in range(len(modified_time)-1):
        line1 = modified_time[i].split(' ')
        if(line1[0]=='name' or line1[0]==''):
            continue;
        line2 = modified_time[i+1].split(' ')
        date1 = line1[1]
        date2 = line2[1]
        time1 = line1[2]
        time2 = line2[2]
        day1 = datetime.strptime(date1, '%Y/%m/%d').date()
        day2 = datetime.strptime(date2, '%Y/%m/%d').date()
        diff1 = (day2-day1).days*24*60

        format = '%H:%M:%S'
        startDateTime = datetime.strptime(time1, format)
        endDateTime = datetime.strptime(time2, format)

        diff2 = endDateTime-startDateTime
        diff2 = diff2.seconds/60

        diff =  diff1 + int(diff2)

        lis_written = line1[0] + ' ' + line1[1] + ' ' + line1[2] + ' ' +
line1[3] + ' ' + line1[4] + ' ' + line1[5] + '\n';
        file_w.write(lis_written)
        format = '%Y/%m/%d %H:%M:%S'
        time_counter = datetime.strptime(line1[1]+' '+line1[2], format)

        from datetime import timedelta

        for i in range(diff-1):
            time_counter = time_counter +timedelta(0,60)
            time_value = str(time_counter)
            time_value = time_value.split(' ')
            giventime = time_value[1]
            givendate = time_value[0]

            temp_str = ""
            temp_str+=givendate[0]
            temp_str+=givendate[1]
            temp_str+=givendate[2]
            temp_str+=givendate[3]
            temp_str+='/'
            temp_str+=givendate[5]
            temp_str+=givendate[6]
            temp_str+='/'
            temp_str+=givendate[8]
            temp_str+=givendate[9]

            lis_written = line1[0] + ' ' + temp_str + ' ' + giventime + ' ' +
str(-999) + ' ' + line1[4] + ' ' + line1[5] + '\n';
            file_w.write(lis_written)

    file_w.write(file[len(file)-1])
    file_w.write("\n")
    file_counter+=1

This is the error I get at line 33:

Traceback (most recent call last):
  File "C:\Users\bxr5813\Desktop\time series\run\New folder\New folder\q.py",
line 33, in <module>
    temp1+=line[2][4]
IndexError: string index out of range

The format of the input text file is as follows:

Value Date Time MilliSecond
919 04/15/16 19:41:02 700682752
551 04/15/16 19:46:51 014109952
717 04/15/16 19:49:48 333956864
2679 04/15/16 19:52:49 8053952
2890 04/15/16 19:55:43 73351552
2897 04/15/16 19:58:38 257767936
1790 04/15/16 21:39:14 13785728
2953 04/15/16 21:42:10 801841152
2516 04/15/16 21:45:04 467205376
2530 04/15/16 21:47:58 688858368
2951 04/15/16 21:51:02 6165952
2954 04/15/16 21:53:56 48836992
2537 04/15/16 21:56:52 105879296
2523 04/15/16 21:59:45 920951808
2536 04/15/16 22:02:49 103219968
2727 04/15/16 22:05:43 708147456
2554 04/15/16 22:11:48 323045888
2703 04/15/16 22:14:46 932627712
2958 04/15/16 22:17:40 574788352
2683 04/15/16 22:20:34 7734976
2542 04/15/16 22:23:29 353888512
2536 04/15/16 22:29:15 787323136

Body:
Have you tried debugging? I think you should change if(line[0]=='name' or line[0]==''): to if(line[0]=='Value' or line[0]==''): and you get Index Error because the code tries to copy the fourth index of 'Time' in the first loop.

Also, your code seems like it needs a bit of simplification. For example, you can write

file_list = []
for filename in os.listdir(os.getcwd()):
    file_list.append(filename)

as file_list = [i for i in os.listdir(os.getcwd())].

You can also simplify

temp1 = ""
temp1+=line[2][0]
temp1+=line[2][1]
temp1+=line[2][2]
temp1+=line[2][3]
temp1+=line[2][4]
temp1+=line[2][5]
temp1+='0'
temp1+='0'
line[2] = temp1

to line[2] = line[2][:5] + '00'.

line[0]+' '+line[1]+' '+line[2]+' '+line[3]+' '+line[4]+' '+line[5] + '\n' can be modified to ' '.join(modified_time) + '\n', and line array seems like it has index 3 as maximum, not 5.

Also, it is recommended for you to close your files opened to read or write if you don't use file anymore, using file_used.close().

I haven't debugged throughout the program, but I think you need to debug your code. I recommend you to use Visual Studio Code program. It's quite useful.


问:
Code that reads file and keeps track of "friends"
I need some help!  I have a file that has a bunch of numbers in a list.  It looks something like this:

0 1

1 3

4 8

4 1

I need a way to see how many times the numbers are linked...

For example, 1 is linked to 3 and 4,

while 4 is linked to 1 and 8

Any tips?

Code as of right now using Ajax1234's suggestion

```<code>with open(file_name) as friends:
    network = [line.rstrip('\n') for line in friends]
    d = defaultdict(list)
    data = filter(lambda x:x, [list(re.findall('\d+', i)) for i in friends])
    for a,b in data:
        d[int(a)].append(int(b))

    print(dict(d))
</code>```

It does not output anything.

When printing network:

```<code>['0 1', '0 2', '0 3', '1 4', '1 6', '1 7', '1 9', '2 3', '2 6', '2 8', '2 9', '3 8', '3 9', '4 6', '4 7', '4 8', '5 9', '6 8', '7 8']
</code>```

答:
You can use a collections.defaultdict:

```<code>from collections import defaultdict
import re
d = defaultdict(list)
s = """
  0 1
  1 3
  4 8
  4 1
 """
network = [list(map(int, re.findall('\d+', line.rstrip('\n')))) for line in friends][1:] #for removing the single first value.
for a, b in network:
    d[a].append(b)

print(dict(d))

new_friend_lists = {a:b+[i for i in d if a in d[i]] for a, b in d.items()}
for a, b in new_friend_lists.items():
    for i in b:
       if i not in d:
            d[i].extend([c for c, e in new_friend_lists.items() if i in e])
       d[a].append(i)

final_list = {a:list(set(b)) for a, b in d.items()}
</code>```

When running the code above on the file data output you posted above, this is the output:

```<code>{0: [1, 2, 3], 1: [0, 9, 4, 6, 7], 2: [0, 8, 3, 6, 9], 3: [0, 8, 2, 9], 4: [8, 1, 6, 7], 5: [9], 6: [8, 1, 2, 4], 7: [8, 1, 4], 8: [2, 3, 4, 6, 7], 9: [1, 2, 3, 5]}
</code>```

Body:
I need some help!  I have a file that has a bunch of numbers in a list.  It looks something like this:

0 1

1 3

4 8

4 1

I need a way to see how many times the numbers are linked...

For example, 1 is linked to 3 and 4,

while 4 is linked to 1 and 8

Any tips?

Code as of right now using Ajax1234's suggestion

with open(file_name) as friends:
    network = [line.rstrip('\n') for line in friends]
    d = defaultdict(list)
    data = filter(lambda x:x, [list(re.findall('\d+', i)) for i in friends])
    for a,b in data:
        d[int(a)].append(int(b))

    print(dict(d))

It does not output anything.

When printing network:

['0 1', '0 2', '0 3', '1 4', '1 6', '1 7', '1 9', '2 3', '2 6', '2 8', '2 9', '3 8', '3 9', '4 6', '4 7', '4 8', '5 9', '6 8', '7 8']

Body:
You can use a collections.defaultdict:

from collections import defaultdict
import re
d = defaultdict(list)
s = """
  0 1
  1 3
  4 8
  4 1
 """
network = [list(map(int, re.findall('\d+', line.rstrip('\n')))) for line in friends][1:] #for removing the single first value.
for a, b in network:
    d[a].append(b)

print(dict(d))

new_friend_lists = {a:b+[i for i in d if a in d[i]] for a, b in d.items()}
for a, b in new_friend_lists.items():
    for i in b:
       if i not in d:
            d[i].extend([c for c, e in new_friend_lists.items() if i in e])
       d[a].append(i)

final_list = {a:list(set(b)) for a, b in d.items()}

When running the code above on the file data output you posted above, this is the output:

{0: [1, 2, 3], 1: [0, 9, 4, 6, 7], 2: [0, 8, 3, 6, 9], 3: [0, 8, 2, 9], 4: [8, 1, 6, 7], 5: [9], 6: [8, 1, 2, 4], 7: [8, 1, 4], 8: [2, 3, 4, 6, 7], 9: [1, 2, 3, 5]}


问:
Grails 3 - Add font resource folder
I can't find where I can tell grails to include a font folder with some font-face (font-awesome). In past version, it would be include in the config.groovy file, but it don't seems like it have one in the version 3. Where can I put this configuration to tell grails to take count of this folder when generating my views?

Thank you

答:
For the asset pipeline to know about the grails-app/assets/fonts directory, add includes = ["fonts/*"] to build.gradle, like this:

```<code>assets {
    minifyJs = true
    minifyCss = true
    includes = ["fonts/*"]
}
</code>```

At first my fonts were still not showing up until after I did a grails clean.

Title: Grails 3 - Add font resource folder

Body:
For the asset pipeline to know about the grails-app/assets/fonts directory, add includes = ["fonts/*"] to build.gradle, like this:

assets {
    minifyJs = true
    minifyCss = true
    includes = ["fonts/*"]
}

At first my fonts were still not showing up until after I did a grails clean.


问:
PDO Driver cannot connect to sql - using xampp
I have been looking for a solution for this for hours now and I found a lot of solutions, but unfortunately none of them worked.

The error I am getting is :

Fatal error: Uncaught PDOException: could not find driver in
  C:\xampp\htdocs\site\includes\database\sqlsrv\database.inc:124 Stack
  trace: #0
  C:\xampp\htdocs\site\includes\database\sqlsrv\database.inc(124):
  PDO->__construct('sqlsrv:Server=l...', 'sa', 'PWHERE...', Array) #1
  C:\xampp\htdocs\site\includes\database\database.inc(1689):
  DatabaseConnection_sqlsrv->__construct(Array) #2
  C:\xampp\htdocs\site\includes\database\database.inc(1479):
  Database::openConnection('xilenacc', 'default') #3
  C:\xampp\htdocs\site\includes\database\database.inc(2350):
  Database::getConnection('default') #4
  C:\xampp\htdocs\site\includes\lock.inc(167): db_query('SELECT expire,
  ...', Array) #5 C:\xampp\htdocs\site\includes\lock.inc(146):
  lock_may_be_available('schema:runtime:...') #6
  C:\xampp\htdocs\site\includes\bootstrap.inc(433):
  lock_acquire('schema:runtime:...') #7
  C:\xampp\htdocs\site\includes\bootstrap.inc(455):
  DrupalCacheArray->set(Array) #8 [internal function]:
  DrupalCacheArray->__destruct() #9 {main} thrown in
  C:\xampp\htdocs\site\includes\database\sqlsrv\database.inc on line
  124`

This is line 124 at database.inc:

```<code> PDO::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);`
    <br>
</code>```

Information on what I am using:

PHP Version: 7.0.25

Mssql express 2016

Windows Server 2012

If I can provide further information, please let me know.

What I tried:

Downloading SQLSRV30 from microsoft website and putting the extensions in php -> Result: After putting the dll names in php.ini, I restarted apache and checked phpinfo(), I didn't find sqlsrv.

I double checked the information I have in settings.php - they are correct,
 I even tried changing my sql pw because I thought it might be causing this,
 but it didn't work.

答:
Finally after hours of googling, I found a solution that actually worked even though it doesn't look so important.

The solution that worked with me is to install Microsoft Redistributable 2012. Kinda weird but worked!

Body:
I have been looking for a solution for this for hours now and I found a lot of solutions, but unfortunately none of them worked.

The error I am getting is :

Fatal error: Uncaught PDOException: could not find driver in
  C:\xampp\htdocs\site\includes\database\sqlsrv\database.inc:124 Stack
  trace: #0
  C:\xampp\htdocs\site\includes\database\sqlsrv\database.inc(124):
  PDO->__construct('sqlsrv:Server=l...', 'sa', 'PWHERE...', Array) #1
  C:\xampp\htdocs\site\includes\database\database.inc(1689):
  DatabaseConnection_sqlsrv->__construct(Array) #2
  C:\xampp\htdocs\site\includes\database\database.inc(1479):
  Database::openConnection('xilenacc', 'default') #3
  C:\xampp\htdocs\site\includes\database\database.inc(2350):
  Database::getConnection('default') #4
  C:\xampp\htdocs\site\includes\lock.inc(167): db_query('SELECT expire,
  ...', Array) #5 C:\xampp\htdocs\site\includes\lock.inc(146):
  lock_may_be_available('schema:runtime:...') #6
  C:\xampp\htdocs\site\includes\bootstrap.inc(433):
  lock_acquire('schema:runtime:...') #7
  C:\xampp\htdocs\site\includes\bootstrap.inc(455):
  DrupalCacheArray->set(Array) #8 [internal function]:
  DrupalCacheArray->__destruct() #9 {main} thrown in
  C:\xampp\htdocs\site\includes\database\sqlsrv\database.inc on line
  124`

This is line 124 at database.inc:

 PDO::__construct($dsn, $connection_options['username'], $connection_options['password'], $connection_options['pdo']);`

Information on what I am using:

PHP Version: 7.0.25

Mssql express 2016

Windows Server 2012

If I can provide further information, please let me know.

What I tried:

Downloading SQLSRV30 from microsoft website and putting the extensions in php -> Result: After putting the dll names in php.ini, I restarted apache and checked phpinfo(), I didn't find sqlsrv.

I double checked the information I have in settings.php - they are correct,
 I even tried changing my sql pw because I thought it might be causing this,
 but it didn't work.


问:
Is there any easy way to remote debug a swift (vapor/perfect/kitura) application running on an (develpoment) server?
Using Xcode it’s quite easy to debug a server side swift (vapor/perfect/kitura) application running on the local machine. Unfortunately it’s not always easy to run a server application on the local workstations cause of datebase connections and various other interactions that are difficult to „emulate“ on a local machine. To make the application behave more like in production use, I would prefer to do some kind of remote debugging of the server side swift (vapor/perfect/kitura) application running on the server.

It seams like llvm is able to support remote-debugging. Is there any option to attache Xcode Debugger to the remote application (running on the server), or is there any other IDE capable of doing this?

答:
My point of view is related to Vapor, but probably other frameworks also support it.

You can have different configurations for different environments, so I shouldn't be so hard to emulate production on development machine.

The only way to remote debug are log files. You can create your own logger - with vapor it is possible - and for "remote development build" you can have verbose logs. This is the only possible way which I know and recommend you.

You can consider this https://github.com/SwiftyBeaver/SwiftyBeaver


问:
Pane Shape Modification
Ok so to make a long story short I'm trying to create a sort of chat/message system and need a small bit of assistance. I'm trying to create an arrow on my container as the one shown in the image below. The image is taken off of ControlsFX and from their PopOver window. I CANNOT use their popover widget because it behaves a little wonky with what I'm using it for.

I went ahead and created my own little chat window popup that positions itself over the parent object that I define but I would really like it to have an arrow pointing to the object. The arrow will also ALWAYS face down and should be in the lower left-hand corner of the popup.

It should also be noted that the popup is NOT a window its a simple VBox that populates with lines of text. I could of course wrap that in a Pane if its needed. Can anyone come up with the proper way to create this arrow? I have my VBox background as a gradient as well so the arrow can't just be like plopped on the bottom through getChildren().add with the "same color" because then the gradient would be off. It has to be (somehow) a part of the container.

===========================================================================
EDIT:

Alright so I spent the greater part of today learning SVG Pathing which isn't too awful complicated but it's slightly tedious. The path I ended up going with is:

```<code>"M30 0 h100 a6,6 0 0,1 6,6 v50 a6,6 0 0,1 -6,6 h-88 L38 68 L34 62 h-4 a6,6 0
 0,1 -6,-6 v-50 a6,6 0 0,1 6,-6 z"
</code>```

Now the only problem with this is the arrow tail height grows with the size of the pane. For instance if I have a LOT of text in the box the pane grows in height (of course) and the arrow gets longer too. This behavior isn't a total deal breaker but it's not really what I had intended. I expected the capital Ls in the pathing to make sure that the points of the arrow stay put no matter what but it didn't work. Any thoughts on this?

答:
There are a number of ways to achieve the effect which you wish.
One way is to use a CSS -fx-shape attribute specification on a region.  See the JavaFX CSS reference for info on this setting and how to use it.

The sample below uses inline styles, but for a more maintainable and substantial application use an external CSS stylesheet.

```<code>import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Bubble extends Application {
    private static final String SQUARE_BUBBLE =
            "M24 1h-24v16.981h4v5.019l7-5.019h13z";
    // source for svg path string: https://iconmonstr.com/speech-bubble-7/
    private static final String ROUND_BUBBLE =
            "M12 1c-6.628 0-12 4.573-12 10.213 0 2.39.932 4.591 2.427 6.164l-2.427 5.623 7.563-2.26c9.495 2.598 16.437-3.251 16.437-9.527 0-5.64-5.372-10.213-12-10.213z";

    @Override
    public void start(Stage stage) {
        Label label = new Label("hello, world");
        label.setStyle("-fx-font-size: 16px;");

        StackPane bubble = new StackPane(label);
        bubble.setPadding(new Insets(20));
        bubble.setStyle(
            "-fx-background-color: lightblue; " +
            "-fx-border-color: navy; -fx-border-width: 2px; " +
            "-fx-shape: \"" + ROUND_BUBBLE + "\";"
        );
        bubble.setEffect(new DropShadow(10, 5, 5, Color.MIDNIGHTBLUE));

        StackPane layout = new StackPane(bubble);
        layout.setPadding(new Insets(20));

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

I realize that the bubble shape demoed in this application isn't exactly the shape which you want but I don't understand from your description what the shape you want is.  There are numerous bubble shapes already created at iconmonstr.com, you can just use its interface to search for speech bubbles and select the shape you want, or you can define your own svg path for your custom shape if you have the tools (e.g. Inkscape) and skill for that.  To extract the svg path from an existing svg file, open up the svg file, hope that it is encoded in a compact path string format, and if it is, just copy and paste the path part from the svg into your JavaFX css file.

Another way to do this would be to programmatically construct a path which you would layer with the content by placing both in a StackPane.

Title: Pane Shape Modification

Body:
Ok so to make a long story short I'm trying to create a sort of chat/message system and need a small bit of assistance. I'm trying to create an arrow on my container as the one shown in the image below. The image is taken off of ControlsFX and from their PopOver window. I CANNOT use their popover widget because it behaves a little wonky with what I'm using it for.

I went ahead and created my own little chat window popup that positions itself over the parent object that I define but I would really like it to have an arrow pointing to the object. The arrow will also ALWAYS face down and should be in the lower left-hand corner of the popup.

It should also be noted that the popup is NOT a window its a simple VBox that populates with lines of text. I could of course wrap that in a Pane if its needed. Can anyone come up with the proper way to create this arrow? I have my VBox background as a gradient as well so the arrow can't just be like plopped on the bottom through getChildren().add with the "same color" because then the gradient would be off. It has to be (somehow) a part of the container.

===========================================================================
EDIT:

Alright so I spent the greater part of today learning SVG Pathing which isn't too awful complicated but it's slightly tedious. The path I ended up going with is:

"M30 0 h100 a6,6 0 0,1 6,6 v50 a6,6 0 0,1 -6,6 h-88 L38 68 L34 62 h-4 a6,6 0
 0,1 -6,-6 v-50 a6,6 0 0,1 6,-6 z"

Now the only problem with this is the arrow tail height grows with the size of the pane. For instance if I have a LOT of text in the box the pane grows in height (of course) and the arrow gets longer too. This behavior isn't a total deal breaker but it's not really what I had intended. I expected the capital Ls in the pathing to make sure that the points of the arrow stay put no matter what but it didn't work. Any thoughts on this?

Body:
There are a number of ways to achieve the effect which you wish.
One way is to use a CSS -fx-shape attribute specification on a region.  See the JavaFX CSS reference for info on this setting and how to use it.

The sample below uses inline styles, but for a more maintainable and substantial application use an external CSS stylesheet.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Bubble extends Application {
    private static final String SQUARE_BUBBLE =
            "M24 1h-24v16.981h4v5.019l7-5.019h13z";
    // source for svg path string: https://iconmonstr.com/speech-bubble-7/
    private static final String ROUND_BUBBLE =
            "M12 1c-6.628 0-12 4.573-12 10.213 0 2.39.932 4.591 2.427 6.164l-2.427 5.623 7.563-2.26c9.495 2.598 16.437-3.251 16.437-9.527 0-5.64-5.372-10.213-12-10.213z";

    @Override
    public void start(Stage stage) {
        Label label = new Label("hello, world");
        label.setStyle("-fx-font-size: 16px;");

        StackPane bubble = new StackPane(label);
        bubble.setPadding(new Insets(20));
        bubble.setStyle(
            "-fx-background-color: lightblue; " +
            "-fx-border-color: navy; -fx-border-width: 2px; " +
            "-fx-shape: \"" + ROUND_BUBBLE + "\";"
        );
        bubble.setEffect(new DropShadow(10, 5, 5, Color.MIDNIGHTBLUE));

        StackPane layout = new StackPane(bubble);
        layout.setPadding(new Insets(20));

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I realize that the bubble shape demoed in this application isn't exactly the shape which you want but I don't understand from your description what the shape you want is.  There are numerous bubble shapes already created at iconmonstr.com, you can just use its interface to search for speech bubbles and select the shape you want, or you can define your own svg path for your custom shape if you have the tools (e.g. Inkscape) and skill for that.  To extract the svg path from an existing svg file, open up the svg file, hope that it is encoded in a compact path string format, and if it is, just copy and paste the path part from the svg into your JavaFX css file.

Another way to do this would be to programmatically construct a path which you would layer with the content by placing both in a StackPane.


问:
how i can show object in gridview or in any usful contro
```<code>public class EventDetail
{
    private Int64 logID;

    public Int64 LogID
    {
        get { return logID; }
        set { logID = value; }
    }
    private Object logedObject;

    public Object LogedObject
    {
        get { return logedObject; }
        set { logedObject = value; }
    }

}
</code>```

答: Look at the DataBinder class, it should allow you to do what you want ;-)</p>


问:
Calculate GPS coordinates from a starting point
Is there a library (JS or .NET) or a set of formulas that would help me calculate set of gps coordinates based on starting location, direction and distance.

For example.

I have an exact lon/lat of a certain location. I'd like to calculate an exact lon/lot 5 miles NE from that location.

答:
With Javascript you can use the geodesy library (under the MIT license), which is the code behind the Movable-Type.co.uk website.

For example:

```<code>const LatLon = require('geodesy').LatLonSpherical;

const p1 = new LatLon(59.912140, 10.743796);
const distance = 42*10**3;
const bearing = 240.0

const p2 = p1.rhumbDestinationPoint(distance, bearing);

console.log(p2); // LatLon { lat: 59.72328246275707, lon: 10.093154371545552 }
</code>```

This finds a second point given initial position, distance and bearing. This particular code is for Node, but it can also be used in the browser.

It should be noted that there are often several different ways to do the various calculations. Some are complex and accurate, while some are simple and less accurate. Using a spherical earth model, as I did in my example, is less accurate, but good enough for ordinary use.

Another library you could check out is geolib.

Body:
With Javascript you can use the geodesy library (under the MIT license), which is the code behind the Movable-Type.co.uk website.

For example:

const LatLon = require('geodesy').LatLonSpherical;

const p1 = new LatLon(59.912140, 10.743796);
const distance = 42*10**3;
const bearing = 240.0

const p2 = p1.rhumbDestinationPoint(distance, bearing);

console.log(p2); // LatLon { lat: 59.72328246275707, lon: 10.093154371545552 }

This finds a second point given initial position, distance and bearing. This particular code is for Node, but it can also be used in the browser.

It should be noted that there are often several different ways to do the various calculations. Some are complex and accurate, while some are simple and less accurate. Using a spherical earth model, as I did in my example, is less accurate, but good enough for ordinary use.

Another library you could check out is geolib.


问:
Converting rdd to dataframe: AttributeError: 'RDD' object has no attribute 'toDF'
```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

conf = SparkConf().setAppName("myApp").setMaster("local")
sc = SparkContext(conf=conf)

a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])

a.show()
</code>```

Results in:

```<code>Traceback (most recent call last):
  File "/Users/ktemlyakov/messing_around/SparkStuff/mock_maersk_data.py", line 7, in <module>
    a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])
AttributeError: 'RDD' object has no attribute 'toDF'
</code>```

What am I missing?

答:
u can directly do this</p>

```<code>a_df = a.toDF()
type(a_df)
</code>```

Body:
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext

conf = SparkConf().setAppName("myApp").setMaster("local")
sc = SparkContext(conf=conf)

a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])

a.show()

Results in:

Traceback (most recent call last):
  File "/Users/ktemlyakov/messing_around/SparkStuff/mock_maersk_data.py", line 7, in <module>
    a = sc.parallelize([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]]).toDF(['ind', "state"])
AttributeError: 'RDD' object has no attribute 'toDF'

What am I missing?

Body:
u can directly do this

a_df = a.toDF()
type(a_df)


问:
Group rows into a new row and sum in r
So I have data that seems like this:

```<code> Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $2                 D
   1            $1                 E
   2            $5                 A
   2            $1                 B
   2            $1                 H
   2            $3                 G
   2            $5                 C
   2            $5                 F
</code>```

How do I make it so that I will show the top 3 for each week and sum all other amounts into "Others"? I want it to show:

```<code> Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $3                 Others
   2            $5                 A
   2            $5                 C
   2            $5                 F
   2            $5                 Others
</code>```

Notice that the other amounts that are not top 3 are summed into a new total amount, and it accounts for the random number of rows for each week (say week 1 has 5 total amounts for each person, but week 2 has 6, and week 3 may be 8 or 10, and week 4 may be 1 total, but I want the equation to apply for each row)

答:
Here's one way you could do it:

```<code>library(tidyverse)

df <- df %>%
  group_by(Week) %>%
  arrange(desc(Total_Amount), .by_group = TRUE) %>%
  mutate(id = row_number()) %>%
  mutate(Person = case_when(id > 3 ~ "Others",
                            TRUE ~ as.character(Person)))
</code>```

Then remove the $ sign so we can sum the Total_Amount:

```<code>df$Total_Amount <- as.numeric(gsub("\\$", "", df$Total_Amount))
</code>```

Finally, sum the Total_Amount by group and add the $ sign to bring everything back:

```<code>df %>%
  group_by(Week, Person) %>%
  summarise(Total_Amount = sum(Total_Amount)) %>%
  mutate(Total_Amount = paste0("$", Total_Amount)) %>%
  select(Week, Total_Amount, Person)
</code>```

Which returns:

```<code># A tibble: 8 x 3
# Groups:   Week [2]
   Week Total_Amount Person
  <int>        <chr>  <chr>
1     1           $5      A
2     1           $5      B
3     1           $4      C
4     1           $3 Others
5     2           $5      A
6     2           $5      C
7     2           $5      F
8     2           $5 Others
</code>```

Title: Group rows into a new row and sum in r

Body:
So I have data that seems like this:

 Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $2                 D
   1            $1                 E
   2            $5                 A
   2            $1                 B
   2            $1                 H
   2            $3                 G
   2            $5                 C
   2            $5                 F

How do I make it so that I will show the top 3 for each week and sum all other amounts into "Others"? I want it to show:

 Week        Total Amount        Person
   1            $5                 A
   1            $5                 B
   1            $4                 C
   1            $3                 Others
   2            $5                 A
   2            $5                 C
   2            $5                 F
   2            $5                 Others

Notice that the other amounts that are not top 3 are summed into a new total amount, and it accounts for the random number of rows for each week (say week 1 has 5 total amounts for each person, but week 2 has 6, and week 3 may be 8 or 10, and week 4 may be 1 total, but I want the equation to apply for each row)

Body:
Here's one way you could do it:

library(tidyverse)

df <- df %>%
  group_by(Week) %>%
  arrange(desc(Total_Amount), .by_group = TRUE) %>%
  mutate(id = row_number()) %>%
  mutate(Person = case_when(id > 3 ~ "Others",
                            TRUE ~ as.character(Person)))

Then remove the $ sign so we can sum the Total_Amount:

df$Total_Amount <- as.numeric(gsub("\\$", "", df$Total_Amount))

Finally, sum the Total_Amount by group and add the $ sign to bring everything back:

df %>%
  group_by(Week, Person) %>%
  summarise(Total_Amount = sum(Total_Amount)) %>%
  mutate(Total_Amount = paste0("$", Total_Amount)) %>%
  select(Week, Total_Amount, Person)

Which returns:

# A tibble: 8 x 3
# Groups:   Week [2]
   Week Total_Amount Person
  <int>        <chr>  <chr>
1     1           $5      A
2     1           $5      B
3     1           $4      C
4     1           $3 Others
5     2           $5      A
6     2           $5      C
7     2           $5      F
8     2           $5 Others


问:
Mailing system in GoogleSheets, resume of crypto-transactions. I'm notified only about 1 of 7 operations, and more than once. How to edit the script?
Actually the code is as follows, there are 7 active operations plus one of the required two sendEmail functions.

Most of this code has been copied from another discussion so not mine, tried to adjust it up to my purpose.

The goal is:
1. get the script to check if a cell on the sheet called AutoMail is empty or filled with either "gain position" or "purchase position" (it's not one cell, there are two, the one on the left is eventually filled with the first expression and on the right with the latter);
2. in case of gain/purchase position, get the relative coin abbreviation and amount from two cells located on another sheet (YourData) and to paste them in a personalized text used as subject and then in the body of my message, and of course let this email reach my inbox, possibly ONCE the cell is filled up with the above mentioned expressions, not every minute.

I'd like the script to check the sheets once every minute, I think I mistake in the trigger setting as well. The repetition of var ss1 and var sheet1 might be useless here.

```<code>    function readCell() {
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain1 = sheet1.getRange("C2:C46").getValue();
      var operationpurchase1 = sheet1.getRange("D2:D46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin1 = sheet2.getRange("B3");
      var amount1 = sheet2.getRange("B4");
      if(operationgain1="gain position") sendEmail(operationgain1);
        function sendEmail(operationgain1) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount1+" "+coin1+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin1+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain2 = sheet1.getRange("E2:E46").getValue();
      var operationpurchase2 = sheet1.getRange("F2:F46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin2 = sheet2.getRange("C3");
      var amount2 = sheet2.getRange("C4");
      if(operationgain2="gain position") sendEmail(operationgain2);
        function sendEmail(operationgain2) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount2+" "+coin2+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin2+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain3 = sheet1.getRange("G2:G46").getValue();
      var operationpurchase3 = sheet1.getRange("H2:H46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin3 = sheet2.getRange("D3");
      var amount3 = sheet2.getRange("D4");
      if(operationgain3="gain position") sendEmail(operationgain3);
        function sendEmail(operationgain3) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount3+" "+coin3+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin3+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain4 = sheet1.getRange("I2:I46").getValue();
      var operationpurchase4 = sheet1.getRange("J2:J46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin4 = sheet2.getRange("E3");
      var amount4 = sheet2.getRange("E4");
      if(operationgain4="gain position") sendEmail(operationgain4);
        function sendEmail(operationgain4) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount4+" "+coin4+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin4+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain5 = sheet1.getRange("K2:K46").getValue();
      var operationpurchase5 = sheet1.getRange("L2:L46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin5 = sheet2.getRange("F3");
      var amount5 = sheet2.getRange("F4");
      if(operationgain5="gain position") sendEmail(operationgain5);
        function sendEmail(operationgain5) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount5+" "+coin5+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin5+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain6 = sheet1.getRange("M2:M46").getValue();
      var operationpurchase6 = sheet1.getRange("N2:N46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin6 = sheet2.getRange("G3");
      var amount6 = sheet2.getRange("G4");
      if(operationgain6="gain position") sendEmail(operationgain6);
        function sendEmail(operationgain6) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount6+" "+coin6+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin6+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain7 = sheet1.getRange("O2:O46").getValue();
      var operationpurchase7 = sheet1.getRange("P2:P46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin7 = sheet2.getRange("H3").getValue();
      var amount7 = sheet2.getRange("H4").getValue();
      if(operationgain7="gain position") sendEmail(operationgain7);
        function sendEmail(operationgain7) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount7+" "+coin7+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin7+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
    };
</code>```

答:
How about this modification? But I worry about whether I could completely understand your question. If I misunderstand your question, please tell me. My understanding from your question is as follows.

When the word of "gain position" is included in the cells of "O2:O46", you want to send an email with var subject = "Your "+amount+" "+coin+" are somewhere in gain position.".

When the word of "purchase position" is included in the cells of "P2:P46", you want to send an email with var subject = "Purchase position for your "+amount+" "+coin+" somewhere there!";.

coin and amount are used at sendEmail().

Is sheet used at var operationpurchase = sheet.getRange("P2:P46").getValue(); sheet1? In this sample, I used sheet1.

About var coin = sheet2.getActiveCell("H3"); and var amount = sheet2.getActiveCell("H4");, I didn't know what you want to do. I'm sorry. So I estimated that you might want the values of "H3" and "H4".

The modified script which is reflected above is as follows.

Modified script :

```<code>function readCell() {
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain = sheet1.getRange("O2:O46").getValues(); // Modified
  var operationpurchase = sheet1.getRange("P2:P46").getValues(); // Modified
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin = sheet2.getRange("H3").getValue(); // Modified
  var amount = sheet2.getRange("H4").getValue(); // Modified

  // Below script was added.
  var email, subject, body
  if (~Array.prototype.concat.apply([], operationgain).indexOf("gain position")) {
    email = "//my email here//";
    subject = "Your " + amount + " " + coin + " are somewhere in gain position.";
    body = "Keep an eye on your " + coin + "s, they're goin' up.";
  }
  if (~Array.prototype.concat.apply([], operationpurchase).indexOf("purchase position")) {
    email = "//my email here//";
    subject = "Purchase position for your " + amount + " " + coin + " somewhere there!";
    body = "Your " + coin + "s might be about to be sold, give them a look.";
  }
  if (email && subject && body) MailApp.sendEmail(email,subject,body);
};
</code>```

Note :

~Array.prototype.concat.apply([], operationpurchase).indexOf("purchase position") means that the 2 dimensional array retrieved by getValues() is flattened, and the strings of purchase position is searched.

If this was not useful for you, I'm sorry.

Body:
Actually the code is as follows, there are 7 active operations plus one of the required two sendEmail functions.

Most of this code has been copied from another discussion so not mine, tried to adjust it up to my purpose.

The goal is:
1. get the script to check if a cell on the sheet called AutoMail is empty or filled with either "gain position" or "purchase position" (it's not one cell, there are two, the one on the left is eventually filled with the first expression and on the right with the latter);
2. in case of gain/purchase position, get the relative coin abbreviation and amount from two cells located on another sheet (YourData) and to paste them in a personalized text used as subject and then in the body of my message, and of course let this email reach my inbox, possibly ONCE the cell is filled up with the above mentioned expressions, not every minute.

I'd like the script to check the sheets once every minute, I think I mistake in the trigger setting as well. The repetition of var ss1 and var sheet1 might be useless here.

    function readCell() {
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain1 = sheet1.getRange("C2:C46").getValue();
      var operationpurchase1 = sheet1.getRange("D2:D46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin1 = sheet2.getRange("B3");
      var amount1 = sheet2.getRange("B4");
      if(operationgain1="gain position") sendEmail(operationgain1);
        function sendEmail(operationgain1) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount1+" "+coin1+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin1+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain2 = sheet1.getRange("E2:E46").getValue();
      var operationpurchase2 = sheet1.getRange("F2:F46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin2 = sheet2.getRange("C3");
      var amount2 = sheet2.getRange("C4");
      if(operationgain2="gain position") sendEmail(operationgain2);
        function sendEmail(operationgain2) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount2+" "+coin2+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin2+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain3 = sheet1.getRange("G2:G46").getValue();
      var operationpurchase3 = sheet1.getRange("H2:H46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin3 = sheet2.getRange("D3");
      var amount3 = sheet2.getRange("D4");
      if(operationgain3="gain position") sendEmail(operationgain3);
        function sendEmail(operationgain3) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount3+" "+coin3+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin3+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain4 = sheet1.getRange("I2:I46").getValue();
      var operationpurchase4 = sheet1.getRange("J2:J46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin4 = sheet2.getRange("E3");
      var amount4 = sheet2.getRange("E4");
      if(operationgain4="gain position") sendEmail(operationgain4);
        function sendEmail(operationgain4) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount4+" "+coin4+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin4+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain5 = sheet1.getRange("K2:K46").getValue();
      var operationpurchase5 = sheet1.getRange("L2:L46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin5 = sheet2.getRange("F3");
      var amount5 = sheet2.getRange("F4");
      if(operationgain5="gain position") sendEmail(operationgain5);
        function sendEmail(operationgain5) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount5+" "+coin5+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin5+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain6 = sheet1.getRange("M2:M46").getValue();
      var operationpurchase6 = sheet1.getRange("N2:N46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin6 = sheet2.getRange("G3");
      var amount6 = sheet2.getRange("G4");
      if(operationgain6="gain position") sendEmail(operationgain6);
        function sendEmail(operationgain6) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount6+" "+coin6+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin6+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
      var ss1 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet1 = ss1.getSheetByName("AutoMail");
      var operationgain7 = sheet1.getRange("O2:O46").getValue();
      var operationpurchase7 = sheet1.getRange("P2:P46").getValue();
      var ss2 = SpreadsheetApp.getActiveSpreadsheet();
      var sheet2 = ss2.getSheetByName("YourData");
      var coin7 = sheet2.getRange("H3").getValue();
      var amount7 = sheet2.getRange("H4").getValue();
      if(operationgain7="gain position") sendEmail(operationgain7);
        function sendEmail(operationgain7) {
          var email = "adrian@semeniuk.biz";
          var subject = "Your "+amount7+" "+coin7+" are somewhere in gain position.";
          var body = "Keep an eye on your "+coin7+"s, they're goin' up.";
          MailApp.sendEmail(email,subject,body);}
    };

Body:
How about this modification? But I worry about whether I could completely understand your question. If I misunderstand your question, please tell me. My understanding from your question is as follows.

When the word of "gain position" is included in the cells of "O2:O46", you want to send an email with var subject = "Your "+amount+" "+coin+" are somewhere in gain position.".

When the word of "purchase position" is included in the cells of "P2:P46", you want to send an email with var subject = "Purchase position for your "+amount+" "+coin+" somewhere there!";.

coin and amount are used at sendEmail().

Is sheet used at var operationpurchase = sheet.getRange("P2:P46").getValue(); sheet1? In this sample, I used sheet1.

About var coin = sheet2.getActiveCell("H3"); and var amount = sheet2.getActiveCell("H4");, I didn't know what you want to do. I'm sorry. So I estimated that you might want the values of "H3" and "H4".

The modified script which is reflected above is as follows.

Modified script :

function readCell() {
  var ss1 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = ss1.getSheetByName("AutoMail");
  var operationgain = sheet1.getRange("O2:O46").getValues(); // Modified
  var operationpurchase = sheet1.getRange("P2:P46").getValues(); // Modified
  var ss2 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet2 = ss2.getSheetByName("YourData");
  var coin = sheet2.getRange("H3").getValue(); // Modified
  var amount = sheet2.getRange("H4").getValue(); // Modified

  // Below script was added.
  var email, subject, body
  if (~Array.prototype.concat.apply([], operationgain).indexOf("gain position")) {
    email = "//my email here//";
    subject = "Your " + amount + " " + coin + " are somewhere in gain position.";
    body = "Keep an eye on your " + coin + "s, they're goin' up.";
  }
  if (~Array.prototype.concat.apply([], operationpurchase).indexOf("purchase position")) {
    email = "//my email here//";
    subject = "Purchase position for your " + amount + " " + coin + " somewhere there!";
    body = "Your " + coin + "s might be about to be sold, give them a look.";
  }
  if (email && subject && body) MailApp.sendEmail(email,subject,body);
};

Note :

~Array.prototype.concat.apply([], operationpurchase).indexOf("purchase position") means that the 2 dimensional array retrieved by getValues() is flattened, and the strings of purchase position is searched.

If this was not useful for you, I'm sorry.


问:
Multiple CKEditor in one page
I'm trying to put two CKEditor on the same page.
Here is what I did:
first the ckeditor config.js

```<code>CKEDITOR.editorConfig = function( config ) {
    config.language = 'en';
    // config.uiColor = '#AADC6E';

    CKEDITOR.stylesSet.add('my_custom_style', [
        { name: 'Page Title', element: 'h2', attributes: {'class': 'general-title min'} }
    ]);

    //Config the KCFinder
    config.filebrowserImageBrowseUrl = "/laravel-filemanager?type=Images";
    config.filebrowserImageUploadUrl = "/laravel-filemanager/upload?type=Images&_token=";

    config.toolbarGroups = [
        { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
        { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
        { name: 'forms', groups: [ 'forms' ] },
        '/',
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
        { name: 'links', groups: [ 'links' ] },
        { name: 'insert', groups: [ 'insert' ] },
        '/',
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'colors', groups: [ 'colors' ] },
        { name: 'tools', groups: [ 'tools' ] },
        { name: 'others', groups: [ 'others' ] },
        { name: 'about', groups: [ 'about' ] }
    ];

    config.removeButtons = 'Save,NewPage,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Language,About';
};
</code>```

and then I have this two forms on the same page which has textarea

```<code><form>
    <div class="form-group">
       {!! Form::label('details', 'Details') !!}
       {!! Form::textarea('details', '', array('class'=>'form-control', 'placeholder'=>'Enter Details...', 'rows'=>3)) !!}
          <script>
              CKEDITOR.replace('details');
          </script>
  </div>
</form>
</code>```

and the second one

```<code><form>
    <div class="form-group">
      {!! Form::label('intro', 'Intro') !!}
      {!! Form::textarea('intro', '', array('class'=>'form-control', 'placeholder'=>'Enter Details...', 'rows'=>3)) !!}
       <script>
          CKEDITOR.replace( 'intro');
       </script>
</div>
</form>
</code>```

The first one seems to be working well but the second one didn't appear to work.

答:
I found out what was wrong here

```<code>CKEDITOR.stylesSet.add('my_custom_style', [
        { name: 'Page Title', element: 'h2', attributes: {'class': 'general-title min'} }
    ]);
</code>```

this was my style, and it shouldn't be inside the main CKEDITOR.editorConfig it should be outside and it works OK

```<code>CKEDITOR.editorConfig = function( config ) {
    config.language = 'en';
    config.uiColor = '#AADC6E';
    ...........
    ...........
    ];

    config.removeButtons = 'Save,NewPage,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Language,About';
};
</code>```

Now here outside of the main function comes the style function

```<code>CKEDITOR.stylesSet.add('my_custom_style', [
    { name: 'Page Title', element: 'h2', attributes: {'class': 'general-title min'} }
]);
</code>```

Title: Multiple CKEditor in one page

Body:
I'm trying to put two CKEditor on the same page.
Here is what I did:
first the ckeditor config.js

CKEDITOR.editorConfig = function( config ) {
    config.language = 'en';
    // config.uiColor = '#AADC6E';

    CKEDITOR.stylesSet.add('my_custom_style', [
        { name: 'Page Title', element: 'h2', attributes: {'class': 'general-title min'} }
    ]);

    //Config the KCFinder
    config.filebrowserImageBrowseUrl = "/laravel-filemanager?type=Images";
    config.filebrowserImageUploadUrl = "/laravel-filemanager/upload?type=Images&_token=";

    config.toolbarGroups = [
        { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
        { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
        { name: 'forms', groups: [ 'forms' ] },
        '/',
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
        { name: 'links', groups: [ 'links' ] },
        { name: 'insert', groups: [ 'insert' ] },
        '/',
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'colors', groups: [ 'colors' ] },
        { name: 'tools', groups: [ 'tools' ] },
        { name: 'others', groups: [ 'others' ] },
        { name: 'about', groups: [ 'about' ] }
    ];

    config.removeButtons = 'Save,NewPage,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Language,About';
};

and then I have this two forms on the same page which has textarea

<form>

       {!! Form::label('details', 'Details') !!}
       {!! Form::textarea('details', '', array('class'=>'form-control', 'placeholder'=>'Enter Details...', 'rows'=>3)) !!}

</form>

and the second one

<form>

      {!! Form::label('intro', 'Intro') !!}
      {!! Form::textarea('intro', '', array('class'=>'form-control', 'placeholder'=>'Enter Details...', 'rows'=>3)) !!}

</form>

The first one seems to be working well but the second one didn't appear to work.

Body:
I found out what was wrong here

CKEDITOR.stylesSet.add('my_custom_style', [
        { name: 'Page Title', element: 'h2', attributes: {'class': 'general-title min'} }
    ]);

this was my style, and it shouldn't be inside the main CKEDITOR.editorConfig it should be outside and it works OK

CKEDITOR.editorConfig = function( config ) {
    config.language = 'en';
    config.uiColor = '#AADC6E';
    ...........
    ...........
    ];

    config.removeButtons = 'Save,NewPage,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Language,About';
};

Now here outside of the main function comes the style function

CKEDITOR.stylesSet.add('my_custom_style', [
    { name: 'Page Title', element: 'h2', attributes: {'class': 'general-title min'} }
]);


问:
We are unable to spy the Table using object spy of test complete,
We are automating a desktop application (ININ) using Test complete. We are unable to spy  the table  using  object spy of test complete. However while recording we are able to click that  row, but we need entire text of that row. Even in the object spy properties we couldn’t able to find the properties of this row.

Element:

Aliases.InteractionDesktop.HwndSource_CafeShellWindow.WinFormsAdapter.WinFormsHostPanel.MyInteractionsQueueControl.QueueListView2

Table element and Row screenshot. We tried using  following  methods to get the text of that Row but we got null data.

```<code>   GetSubItemRect_2
   GetSubItemAt
   get_Items
   get_SelectedItem
   get_Text
   get_WindowText
   GetColumns and tried `enter code here`to get column text.
   GetItemAtenter code here
   GetSubItemRect
   Items.Item_2
   Items.Item
   Items.get_InnerList
   Items.get_Item_2
   Items.get_Item
</code>```

答:
First your application should be an Open application as described Hear
(ININ is a product name I suppose) and TestComplete should be supports technology mention hear of the application.

test complete supports most of table grids ...the link

Also If you posted code while recording can be help more..

The best place to get exact answer is Test Complete forum

Body:
We are automating a desktop application (ININ) using Test complete. We are unable to spy  the table  using  object spy of test complete. However while recording we are able to click that  row, but we need entire text of that row. Even in the object spy properties we couldn’t able to find the properties of this row.

Element:

Aliases.InteractionDesktop.HwndSource_CafeShellWindow.WinFormsAdapter.WinFormsHostPanel.MyInteractionsQueueControl.QueueListView2

Table element and Row screenshot. We tried using  following  methods to get the text of that Row but we got null data.

   GetSubItemRect_2
   GetSubItemAt
   get_Items
   get_SelectedItem
   get_Text
   get_WindowText
   GetColumns and tried `enter code here`to get column text.
   GetItemAtenter code here
   GetSubItemRect
   Items.Item_2
   Items.Item
   Items.get_InnerList
   Items.get_Item_2
   Items.get_Item


问:
How to read values from property file in a JavaBean (domain class)?
I have a domain class and I want to read values from property file (autowiring messageSource wouldn't work here) so any ideas ?
I am using spring,hibernate
and here's a sample:</p>

```<code>package com.myapp.domain;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name = "domain")
public class MyDomain implements Serializable {

    private long entityId;
    private String domain="some_hardcoded_value" // need to read it from a property file;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    public long getEntityId() {
        return entityId;
    }

    public void setEntityId(long entityId) {
        this.entityId = entityId;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    @Column(name = "domain")
    public String getDomain() {
        return domain;
    }

}
</code>```

答:
I still don't understand the question, but I'll assume that you want to set bean properties from a properties file.

The other answers have shown how to get a Properties object from a .properties file (I'll show additional ways below), I will show you how to wire properties from it using Spring's BeanWrapper interface:

```<code>public static void wireBeanFromProperties(Object bean, Properties props){

    BeanWrapper wrapper = new BeanWrapperImpl(bean);
    for(Entry<Object, Object> entry:props.entrySet()){
        String propertyName = entry.getKey().toString();
        if(wrapper.isWritableProperty(propertyName)){
            wrapper.setPropertyValue(propertyName, entry.getValue());
        }
    }

}
</code>```

Or, if you know for sure that all properties from the properties file can be mapped to this bean properties of the class:

```<code>public static void wireBeanFromProperties(final Object bean,
    final Properties props){
    final BeanWrapper wrapper = new BeanWrapperImpl(bean);
    // will throw an exception if the Properties object
    // contains any unknown keys
    wrapper.setPropertyValues(props);
}
</code>```

Reference: 5.4. Bean manipulation and the BeanWrapper

Actually, the Spring-specific ways to load resources from the classpath use the Resource mechanism

```<code>InputStream str = new ClassPathResource("classpath:some.properties")
                      .getInputStream();
</code>```

The nice part is that you can wire both InputStreams and Resources easily from XML using the classpath: syntax:

Java Code

```<code>private InputStream stream;
private Resource resource;
public void setStream(InputStream stream){
    this.stream = stream;
}
public void setResource(Resource resource){
    this.resource = resource;
}
</code>```

property wiring:

```<code><bean class="MyClass">
    <property name="stream" value="classpath:file1.properties" />
    <property name="resource" value="classpath:file2.properties" />
</bean>
</code>```

If you just want to initialize a static final field, here's how to do it:

```<code>private static final String DOMAIN;
static{
    InputStream inputStream=null;
    try{
        inputStream = new ClassPathResource("classpath:some.properties")
                          .getInputStream();
        Properties props = new Properties();
        props.load(inputStream);
        String key = "your.property";
        if(!props.containsKey(key))
            throw new IllegalStateException("Property not found");
        DOMAIN= props.getProperty(key);
    } catch(IOException e){
        throw new IllegalStateException(e);
    }finally{
        // apache commons / IO
        IOUtils.closeQuietly(inputStream);
    }
}
</code>```

Body:
I have a domain class and I want to read values from property file (autowiring messageSource wouldn't work here) so any ideas ?
I am using spring,hibernate
and here's a sample:

package com.myapp.domain;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@SuppressWarnings("serial")
@Entity
@Table(name = "domain")
public class MyDomain implements Serializable {

    private long entityId;
    private String domain="some_hardcoded_value" // need to read it from a property file;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    public long getEntityId() {
        return entityId;
    }

    public void setEntityId(long entityId) {
        this.entityId = entityId;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    @Column(name = "domain")
    public String getDomain() {
        return domain;
    }

}

Body:
I still don't understand the question, but I'll assume that you want to set bean properties from a properties file.

The other answers have shown how to get a Properties object from a .properties file (I'll show additional ways below), I will show you how to wire properties from it using Spring's BeanWrapper interface:

public static void wireBeanFromProperties(Object bean, Properties props){

    BeanWrapper wrapper = new BeanWrapperImpl(bean);
    for(Entry<Object, Object> entry:props.entrySet()){
        String propertyName = entry.getKey().toString();
        if(wrapper.isWritableProperty(propertyName)){
            wrapper.setPropertyValue(propertyName, entry.getValue());
        }
    }

}

Or, if you know for sure that all properties from the properties file can be mapped to this bean properties of the class:

public static void wireBeanFromProperties(final Object bean,
    final Properties props){
    final BeanWrapper wrapper = new BeanWrapperImpl(bean);
    // will throw an exception if the Properties object
    // contains any unknown keys
    wrapper.setPropertyValues(props);
}

Reference: 5.4. Bean manipulation and the BeanWrapper

Actually, the Spring-specific ways to load resources from the classpath use the Resource mechanism

InputStream str = new ClassPathResource("classpath:some.properties")
                      .getInputStream();

The nice part is that you can wire both InputStreams and Resources easily from XML using the classpath: syntax:

Java Code

private InputStream stream;
private Resource resource;
public void setStream(InputStream stream){
    this.stream = stream;
}
public void setResource(Resource resource){
    this.resource = resource;
}

property wiring:

<bean class="MyClass">
    <property name="stream" value="classpath:file1.properties" />
    <property name="resource" value="classpath:file2.properties" />
</bean>

If you just want to initialize a static final field, here's how to do it:

private static final String DOMAIN;
static{
    InputStream inputStream=null;
    try{
        inputStream = new ClassPathResource("classpath:some.properties")
                          .getInputStream();
        Properties props = new Properties();
        props.load(inputStream);
        String key = "your.property";
        if(!props.containsKey(key))
            throw new IllegalStateException("Property not found");
        DOMAIN= props.getProperty(key);
    } catch(IOException e){
        throw new IllegalStateException(e);
    }finally{
        // apache commons / IO
        IOUtils.closeQuietly(inputStream);
    }
}


问:
How to export JavaScript array info to csv (on client side)?
I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this:

```<code>[["name1", "city_name1", ...]["name2", "city_name2", ...]]
</code>```

Any idea how I can export this to CSV on the client side?

答:
I use this function to convert an string[][] to a csv file. It quotes a cell, if it contains a ", a , or other whitespace (except blanks):

/**
 * Takes an array of arrays and returns a `,` sparated csv file.
 * @param {string[][]} table
 * @returns {string}
 */
function toCSV(table) {
    return table
        .map(function(row) {
            return row
                .map(function(cell) {
                    // We remove blanks and check if the column contains
                    // other whitespace,`,` or `"`.
                    // In that case, we need to quote the column.
                    if (cell.replace(/ /g, '').match(/[\s,"]/)) {
                        return '"' + cell.replace(/"/g, '""') + '"';
                    }
                    return cell;
                })
                .join(',');
        })
        .join('\n'); // or '\r\n' for windows

}
```

<p><strong>Note</strong>: does not work on Internet Explorer < 11 unless <code>map</code> is polyfilled.</p>

<p><strong>Note</strong>: If the cells contain numbers, you can add <code>cell=''+cell</code> before <code>if (cell.replace...</code> to convert numbers to strings.</p>

<p>Or you can write it in one line using ES6:</p>

<pre class="lang-js prettyprint-override"><code>t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')
</code>```

Body:
I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this:

[["name1", "city_name1", ...]["name2", "city_name2", ...]]

Any idea how I can export this to CSV on the client side?

Body:
I use this function to convert an string[][] to a csv file. It quotes a cell, if it contains a ", a , or other whitespace (except blanks):

/**
 * Takes an array of arrays and returns a `,` sparated csv file.
 * @param {string[][]} table
 * @returns {string}
 */
function toCSV(table) {
    return table
        .map(function(row) {
            return row
                .map(function(cell) {
                    // We remove blanks and check if the column contains
                    // other whitespace,`,` or `"`.
                    // In that case, we need to quote the column.
                    if (cell.replace(/ /g, '').match(/[\s,"]/)) {
                        return '"' + cell.replace(/"/g, '""') + '"';
                    }
                    return cell;
                })
                .join(',');
        })
        .join('\n'); // or '\r\n' for windows

}

Note: does not work on Internet Explorer < 11 unless map is polyfilled.

Note: If the cells contain numbers, you can add cell=''+cell before if (cell.replace... to convert numbers to strings.

Or you can write it in one line using ES6:

t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')


问:
Cycling through columns vs cycling through rows when working with 2D arrays
I am trying to understand this code.  The first thing that's confusing to me is that in the second line of code I believe they are creating an array of pointers and the plan is that those pointers are going to point to arrays.

I know that the computer doesn't care but to me, it's most logical to have the array of pointers be horizontal and then each array can drop down from the points on that horizontal line.

So, is it reasonable to have  "dynamicArray = new int *[COLUMNS];"  instead?

```<code>int **dynamicArray = 0;
</code>```

//memory allocated for elements of rows.

```<code>dynamicArray = new int *[ROWS] ;
</code>```

//memory allocated for  elements of each column.

```<code>for( int i = 0 ; i < ROWS ; i++ )
dynamicArray[i] = new int[COLUMNS];
</code>```

//free the allocated memory

```<code>for( int i = 0 ; i < ROWS ; i++ )
delete [] dynamicArray[i] ;
delete [] dynamicArray ;
</code>```

EDIT: I thought about this more and the thing that I am getting tripped up on a lot is that I think about the rows and columns in the wrong way.

dynamicArray = new int *[ROWS];

I understand this to be an array of pointers and each pointer is pointing to a column.  The number of elements in each column is equal to the number of rows (columns have one vertical element for each row in our 2D array).
Am I understanding this right?

I also get tripped up a lot when I need to use nested for loops to initialize a 2 D array.

答:
Rows/columns are symmetric/interchangeable, and as you say, "the computer doesn't care". Having said that, why do you think "it's most logical to have the array of pointers be horizontal and then each array can drop down from the points on that horizontal line"?

I would think the other way. I would find it much easier to "visualize" rows of horizontal objects (after all, we write horizontally (say, an array of chars), and the lines/rows go top to bottom (say, an array of arrays)). I think the code is more natural (to me) than what you suggest.

The point is, we all think differently, and at the end of the day, ROWS/COLUMNS are just variables, which could have been easily written as X/Y or V/H or W/H or whatever.

Body:
I am trying to understand this code.  The first thing that's confusing to me is that in the second line of code I believe they are creating an array of pointers and the plan is that those pointers are going to point to arrays.

I know that the computer doesn't care but to me, it's most logical to have the array of pointers be horizontal and then each array can drop down from the points on that horizontal line.

So, is it reasonable to have  "dynamicArray = new int *[COLUMNS];"  instead?

int **dynamicArray = 0;

//memory allocated for elements of rows.

dynamicArray = new int *[ROWS] ;

//memory allocated for  elements of each column.

for( int i = 0 ; i < ROWS ; i++ )
dynamicArray[i] = new int[COLUMNS];

//free the allocated memory

for( int i = 0 ; i < ROWS ; i++ )
delete [] dynamicArray[i] ;
delete [] dynamicArray ;

EDIT: I thought about this more and the thing that I am getting tripped up on a lot is that I think about the rows and columns in the wrong way.

dynamicArray = new int *[ROWS];

I understand this to be an array of pointers and each pointer is pointing to a column.  The number of elements in each column is equal to the number of rows (columns have one vertical element for each row in our 2D array).
Am I understanding this right?

I also get tripped up a lot when I need to use nested for loops to initialize a 2 D array.


问:
How to set background to subtitle in ffmpeg?
It is described here how ot burn a srt file into a video.
However, I want to put a semi-transparent background to the subtitles so that the texts can be read more easily. How can I do that?</p>

答: You can use this Aegisub script. This script automatically generate transparent background for every line of subtitle.


问:
Convert numpy array type and values from Float64 to Float32
I am trying to convert threshold array(pickle file of isolation forest from scikit learn) of type from Float64 to Float32

```<code>for i in range(len(tree.tree_.threshold)):
    tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32)
</code>```

Then Printing it

```<code>for value in tree.tree_.threshold[:5]:
    print(type(value))
    print(value)
</code>```

the output i am getting is :

```<code><class 'numpy.float64'>
526226.0
<class 'numpy.float64'>
91.9514312744
<class 'numpy.float64'>
3.60330319405
<class 'numpy.float64'>
-2.0
<class 'numpy.float64'>
-2.0
</code>```

I am not getting a proper conversion to Float32. I want to convert values and their type to Float32, Did anybody have any workaround this ?

答:
You can try this:</p>

```<code>tree.tree_.threshold[i]=tree.tree_.threshold[i].astype('float32',casting='same_kind’)
</code>```

Body:
I am trying to convert threshold array(pickle file of isolation forest from scikit learn) of type from Float64 to Float32

for i in range(len(tree.tree_.threshold)):
    tree.tree_.threshold[i] = tree.tree_.threshold[i].astype(np.float32)

Then Printing it

for value in tree.tree_.threshold[:5]:
    print(type(value))
    print(value)

the output i am getting is :

<class 'numpy.float64'>
526226.0
<class 'numpy.float64'>
91.9514312744
<class 'numpy.float64'>
3.60330319405
<class 'numpy.float64'>
-2.0
<class 'numpy.float64'>
-2.0

I am not getting a proper conversion to Float32. I want to convert values and their type to Float32, Did anybody have any workaround this ?

Body:
You can try this:

tree.tree_.threshold[i]=tree.tree_.threshold[i].astype('float32',casting='same_kind’)


问:
Google Geocode API - Echo specific details in PHP
I'm using this script to get the geo-code information from Google but I don't know how to filter out just specifics such as Lat, Lon, Town, County. Here is my code (which I beleive will work under the new API-3?):

```<code><?php
$address="LS1 7AS";
$result=file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
    $geocodedinfo=json_decode($result);

print_r($geocodedinfo);
?>
</code>```

This prints out all of the information I need but as a block, I just want to have some of them so I can insert it into a table, for example:

```<code>$town = "town from result";
$county = "county from result";
$lat = "lat from result";
$lon = "lon from result";
</code>```

答:
Please try this:

```<code>$address="LS1 7AS";
$result = @file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
if ($result === FALSE) {
    //manage exception from file_get_contents call
} else {
    $geocodedinfo = json_decode($result);
    if ($geocodedinfo->status == "OK") {
        $county = "";
        $town = "";
        foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
            if ( $addrcomps->types[0] == 'postal_town')
                $town = $addrcomps->long_name;
            if ( $addrcomps->types[0] == 'administrative_area_level_2')
                $county = $addrcomps->long_name;
        }
        $lat = $geocodedinfo->results[0]->geometry->location->lat;
        $lon = $geocodedinfo->results[0]->geometry->location->lng;
    }
}
</code>```

Sometimes the file_get_contents function calls returns an exception. So you should use @ before call it.

Body:
I'm using this script to get the geo-code information from Google but I don't know how to filter out just specifics such as Lat, Lon, Town, County. Here is my code (which I beleive will work under the new API-3?):

<?php
$address="LS1 7AS";
$result=file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
    $geocodedinfo=json_decode($result);

print_r($geocodedinfo);
?>

This prints out all of the information I need but as a block, I just want to have some of them so I can insert it into a table, for example:

$town = "town from result";
$county = "county from result";
$lat = "lat from result";
$lon = "lon from result";

Body:
Please try this:

$address="LS1 7AS";
$result = @file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
if ($result === FALSE) {
    //manage exception from file_get_contents call
} else {
    $geocodedinfo = json_decode($result);
    if ($geocodedinfo->status == "OK") {
        $county = "";
        $town = "";
        foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
            if ( $addrcomps->types[0] == 'postal_town')
                $town = $addrcomps->long_name;
            if ( $addrcomps->types[0] == 'administrative_area_level_2')
                $county = $addrcomps->long_name;
        }
        $lat = $geocodedinfo->results[0]->geometry->location->lat;
        $lon = $geocodedinfo->results[0]->geometry->location->lng;
    }
}

Sometimes the file_get_contents function calls returns an exception. So you should use @ before call it.


问:
How to undo npm update?
Is there a way to undo the command npm update? I ran the command and now I have a bunch of unmet dependencies and some errors.

I'm trying to manually reinstall and fix all the errors but does anyone know how to essentially revert an npm update?

答: All I did was to do "rm -rf node_modules" to uninstall the updated node_modules and then "npm install" to reinstall them; my package.json hadn't change when I did npm update which caused all the havoc.  So by deleting and reinstalling node_modules I'm gladly back in business.</p>

Title: How to undo npm update?


问:
Tool to find duplicate sections in a text (XML) file?
I have an XML file, and I want to find nodes that have duplicate CDATA. Are there any tools that exist that can help me do this?

I'd be fine with a tool that does this generally for text documents.

答: You could write a simple C# app that uses Linq to read all the nodes twice as separate entities, then finds all values that are equal.</p>

OwnerDisplayName: parsifal

OwnerDisplayName: ck


问:
Viewing dataframes in Spyder using a command in its console
I have been using R Studio for quite some time, and I find View() function very helpful for viewing my datasets.

Is there a similar View() counterpart in Spyder?

答: (Spyder maintainer here) There's no function similar to view() in Spyder. To view the contents of a Dataframe, you need to double-click on it in the Variable Explorer.