问:
Configuring JanusGraph to use Lucene via Java
I am trying to connect to JanusGraph using the following code:

```<code>Graph graph = GraphFactory.open(new PropertiesConfiguration("janusgraph.propertes");
</code>```

Where my janusgraph.properties file is as follows:

```<code>gremlin.graph=org.janusgraph.core.JanusGraphFactory
storage.backend=hbase
storage.hostname=127.0.0.1

cache.db-cache = true
cache.db-cache-clean-wait = 20
cache.db-cache-time = 180000
cache.db-cache-size = 0.5

index.janusgraph-index.backend=lucene
</code>```

However, when I try to connect I get the following error:

```<code>Exception in thread "Thread-4" java.lang.RuntimeException: GraphFactory could not instantiate this Graph implementation [class org.janusgraph.core.JanusGraphFactory]
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:82)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:70)
    at uk.gov.nca.cdp.graphutils.server.controllers.MergeGraph.lambda$merge$0(MergeGraph.java:26)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:78)
    ... 3 more
Caused by: java.lang.IllegalArgumentException: Could not find implementation class: org.janusgraph.diskstorage.es.ElasticSearchIndex
    at org.janusgraph.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:61)
    at org.janusgraph.diskstorage.Backend.getImplementationClass(Backend.java:477)
    at org.janusgraph.diskstorage.Backend.getIndexes(Backend.java:464)
    at org.janusgraph.diskstorage.Backend.<init>(Backend.java:149)
    at org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.getBackend(GraphDatabaseConfiguration.java:1897)
    at org.janusgraph.graphdb.database.StandardJanusGraph.<init>(StandardJanusGraph.java:136)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:164)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:133)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:113)
    ... 8 more
Caused by: java.lang.ClassNotFoundException: org.janusgraph.diskstorage.es.ElasticSearchIndex
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:94)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.janusgraph.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:56)
    ... 16 more
</code>```

This sounds like it's trying to use Elasticsearch rather than Lucene. How do I correctly configure it to use Lucene?

答:
The problem you are running into is that your configuration does not define a storage.hbase.table so the default table name janusgraph is used (see the JanusGraph configuration reference). An HBase table named janusgraph must have been previously created with Elasticsearch for the indexing provider. JanusGraph stores its initial configuration in the HBase table, so when you connect to the janusgraph table, it is reading the old properties from the janusgraph table. You should either:

Drop the existing janusgraph HBase table. From the HBase shell: disable 'janusgraph'; drop 'janusgraph';

Use a different HBase table by setting storage.hbase.table=mygraph

As described in the JanusGraph Lucene documentation, the Lucene indexing backend requires two parameters in its configuration:

index.[X].backend=lucene

index.[X].directory=/data/searchindex

where [X] is the name of the index. You could set this to match the directory name, searchindex, or search as commonly found in examples, or janusgraph-index as in your question. Make sure you include both configuration properties.

Body:
I am trying to connect to JanusGraph using the following code:

Graph graph = GraphFactory.open(new PropertiesConfiguration("janusgraph.propertes");

Where my janusgraph.properties file is as follows:

gremlin.graph=org.janusgraph.core.JanusGraphFactory
storage.backend=hbase
storage.hostname=127.0.0.1

cache.db-cache = true
cache.db-cache-clean-wait = 20
cache.db-cache-time = 180000
cache.db-cache-size = 0.5

index.janusgraph-index.backend=lucene

However, when I try to connect I get the following error:

Exception in thread "Thread-4" java.lang.RuntimeException: GraphFactory could not instantiate this Graph implementation [class org.janusgraph.core.JanusGraphFactory]
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:82)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:70)
    at uk.gov.nca.cdp.graphutils.server.controllers.MergeGraph.lambda$merge$0(MergeGraph.java:26)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:78)
    ... 3 more
Caused by: java.lang.IllegalArgumentException: Could not find implementation class: org.janusgraph.diskstorage.es.ElasticSearchIndex
    at org.janusgraph.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:61)
    at org.janusgraph.diskstorage.Backend.getImplementationClass(Backend.java:477)
    at org.janusgraph.diskstorage.Backend.getIndexes(Backend.java:464)
    at org.janusgraph.diskstorage.Backend.<init>(Backend.java:149)
    at org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.getBackend(GraphDatabaseConfiguration.java:1897)
    at org.janusgraph.graphdb.database.StandardJanusGraph.<init>(StandardJanusGraph.java:136)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:164)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:133)
    at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:113)
    ... 8 more
Caused by: java.lang.ClassNotFoundException: org.janusgraph.diskstorage.es.ElasticSearchIndex
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:94)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.janusgraph.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:56)
    ... 16 more

This sounds like it's trying to use Elasticsearch rather than Lucene. How do I correctly configure it to use Lucene?


来源: stackexchange

问:
Caching using Spring Boot - What is ~keys in Redis key name?
When I tried to show the keys from redis-cli, the keys that generated from my application method generated cachename~keys, what is ~keys? I used Spring Boot @Cacheable annotation with custom keys and it showed those. I tried googling but there isn't any answer. Is it a wildcard of keys?? how can I show it all?? Thanks

答:
You need to set parameter "usePrefix" as true in your CacheManager bean. This will prepend cacheName in your keys.</p>

```<code><bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
 ...
 <property name="usePrefix"><value>true</value></property>
 ...
</bean>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You need to set parameter "usePrefix" as true in your CacheManager bean. This will prepend cacheName in your keys.

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
 ...
 <property name="usePrefix"><value>true</value></property>
 ...
</bean>


问:
Check if there is an object assigned to function in R
I have quite a simple problem that I am stuck on.

Lets say I have a function foo. I want it to behave differently depending on whether there is an object assigned to it i.e. foo() will print "Please assign an object to foo!" and data<-foo() will just assign a dataframe to the object data.

Is there a function that can check this so I can incorporate a logical test in foo? match.call doesn't tell if the output is being assigned to an object unfortunately.

答:
What you are asking for is not really in the spirit of how R works.

If you must do it anyways then a workaround would be instead of using the form:

```<code>output <- foo(input)
</code>```

pass the name of the output to foo as an argument.  Then we can do this:

```<code>foo <- function(name, input, envir = parent.frame()) {
  stopifnot(is.character(name))
  output <- input    # can replace this with complex transformation
  assign(name, output, envir)
}

# test it checking that abc was assigned to
foo("abc", 3)
abc
## [1] 3
</code>```

Body:
What you are asking for is not really in the spirit of how R works.

If you must do it anyways then a workaround would be instead of using the form:

output <- foo(input)

pass the name of the output to foo as an argument.  Then we can do this:

foo <- function(name, input, envir = parent.frame()) {
  stopifnot(is.character(name))
  output <- input    # can replace this with complex transformation
  assign(name, output, envir)
}

# test it checking that abc was assigned to
foo("abc", 3)
abc
## [1] 3


问:
SimplePosttool: FATAL: specifying either url or core/collection is mandatory
I'm new in solr and I want to start an example that is in the exampledocs folder , but when I try to start it using the windows prompt I have the error message in the title.
Someone can help me?</p>

答:
Start your Solr Admin

Create one core using following command:

```<code>solr create -c <name>
</code>```

Select core from core_selector dropdown

click on documents and then add data to be added in the core.Format of document can be specify by you.

OR

Type this command in solr-(versioname)\example\exampledocs

```<code>java -Dc=my_core -Dtype=text/csv -jar post.jar test.csv
</code>```

where my_core is corename,

      type is csv and

      test.csv is file to be imported.

Body:
Start your Solr Admin

Create one core using following command:

solr create -c <name>

Select core from core_selector dropdown

click on documents and then add data to be added in the core.Format of document can be specify by you.

OR

Type this command in solr-(versioname)\example\exampledocs

java -Dc=my_core -Dtype=text/csv -jar post.jar test.csv

where my_core is corename,

      type is csv and

      test.csv is file to be imported.


问:
How should I name my CSS classes?
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

```<code>.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)
</code>```

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

答:
I see the first approach a lot (the jQuery UI CSS framework uses it and I find it a very good example for good CSS).

I personally don't like camelcasing in class names from (2) and (3) because it is really easy to get it wrong (just write VotecountPost and it won't work).

(4), (5), (6) are not really a convention thing but rather different selectors as others pointed out already.

ContentLicense: CC BY-SA 2.5

Title: How should I name my CSS classes?

Body:
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?


问:
How to make a switch statement loop?
```<code>import java.util.LinkedList;
import java.util.Scanner;

public class Enrollment {
public static void main(String[] args) {
    LinkedList<Student> studentData = new LinkedList<Student>();
    LinkedList<Faculty> facultyData = new LinkedList<Faculty>();
    LinkedList<Course> courseData = new LinkedList<Course>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
    int userChoice = input.nextInt();
    input.nextLine();
    switch (userChoice) {

    case 1:
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

        System.out.println("Enter student address(only address number and street name) ");
        String sAddress = input.nextLine();

        System.out.println("Enter city, state, and zip code ");
        String sCityStateZip = input.nextLine();

        System.out.println("Enter student gender ");
        String sGender = input.nextLine();

        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }

        break;
    case 2:
        // code to add faculty
        System.out.println("Enter faculty name ");
        String fName = input.nextLine();

        System.out.println("Enter faculty age ");
        int fAge = input.nextInt();

        System.out.println("Enter faculty id ");
        int fID = input.nextInt();
        input.nextLine();

        System.out.println("Enter faculty degree ");
        String fDegree = input.nextLine();

        System.out.println("Enter faculty major ");
        String fMajor = input.nextLine();

        System.out.println("Enter faculty address ");
        String fAddress = input.nextLine();

        System.out.println("Enter faculty gender ");
        String fGender = input.nextLine();

        Faculty facultyInfo = new Faculty(fName, fAge, fID, fDegree, fMajor, fAddress, fGender);
        facultyData.add(facultyInfo);

        for (Faculty testClass : facultyData) {
            System.out.println(testClass);
        }
        break;
    case 3:
        // code to add course
        System.out.println("Enter course name ");
        String courseName = input.nextLine();

        System.out.println("Enter course ID ");
        int cID = input.nextInt();

        System.out.println("Enter number of credits ");
        int numOfCred = input.nextInt();

        System.out.println("Enter intstructor/faculty ID ");
        int instructorID = input.nextInt();

        System.out.println("Enter course year ");
        int year = input.nextInt();
        input.nextLine();

        System.out.println("Enter semester ");
        String semester = input.nextLine();

        System.out.println("Enter classroom size ");
        int size = input.nextInt();

        System.out.println("Enter course capacity ");
        int capacity = input.nextInt();

        Course courseInfo = new Course(courseName, cID, numOfCred, instructorID, year, semester, size, capacity);
        courseData.add(courseInfo);

        for (Course testClass : courseData) {
            System.out.println(testClass);
        }

        break;

    default:
        System.out.println("Invalid entry");
        break;
    }

}
</code>```

I am trying to make an enrollment system. Right now I have made the program so that it prompts the user to choose if they want to add a student, faculty, or course. Once the user picks an option and fills out the questions asked, the program ends. How can I make it loop so that after the user answers the questions, it brings them back to the first prompt where they are given the three choices of what they want to do?

答:
you can make </p>

```<code>while(userChoice!=4){.........your code.........
 System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
  userChoice = input.nextInt();
}
</code>```

Title: How to make a switch statement loop?

Body:
import java.util.LinkedList;
import java.util.Scanner;

public class Enrollment {
public static void main(String[] args) {
    LinkedList<Student> studentData = new LinkedList<Student>();
    LinkedList<Faculty> facultyData = new LinkedList<Faculty>();
    LinkedList<Course> courseData = new LinkedList<Course>();
    Scanner input = new Scanner(System.in);

    System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
    int userChoice = input.nextInt();
    input.nextLine();
    switch (userChoice) {

    case 1:
        System.out.println("Enter student full name ");
        String sName = input.nextLine();

        System.out.println("Enter student age ");
        int sAge = input.nextInt();

        System.out.println("Enter student id ");
        int sID = input.nextInt();
        input.nextLine();

        System.out.println("Enter student address(only address number and street name) ");
        String sAddress = input.nextLine();

        System.out.println("Enter city, state, and zip code ");
        String sCityStateZip = input.nextLine();

        System.out.println("Enter student gender ");
        String sGender = input.nextLine();

        Student studentInfo = new Student(sName, sAge, sID, sAddress, sCityStateZip, sGender);
        studentData.add(studentInfo);

        for (Student testClass : studentData) {
            System.out.println(testClass);
        }

        break;
    case 2:
        // code to add faculty
        System.out.println("Enter faculty name ");
        String fName = input.nextLine();

        System.out.println("Enter faculty age ");
        int fAge = input.nextInt();

        System.out.println("Enter faculty id ");
        int fID = input.nextInt();
        input.nextLine();

        System.out.println("Enter faculty degree ");
        String fDegree = input.nextLine();

        System.out.println("Enter faculty major ");
        String fMajor = input.nextLine();

        System.out.println("Enter faculty address ");
        String fAddress = input.nextLine();

        System.out.println("Enter faculty gender ");
        String fGender = input.nextLine();

        Faculty facultyInfo = new Faculty(fName, fAge, fID, fDegree, fMajor, fAddress, fGender);
        facultyData.add(facultyInfo);

        for (Faculty testClass : facultyData) {
            System.out.println(testClass);
        }
        break;
    case 3:
        // code to add course
        System.out.println("Enter course name ");
        String courseName = input.nextLine();

        System.out.println("Enter course ID ");
        int cID = input.nextInt();

        System.out.println("Enter number of credits ");
        int numOfCred = input.nextInt();

        System.out.println("Enter intstructor/faculty ID ");
        int instructorID = input.nextInt();

        System.out.println("Enter course year ");
        int year = input.nextInt();
        input.nextLine();

        System.out.println("Enter semester ");
        String semester = input.nextLine();

        System.out.println("Enter classroom size ");
        int size = input.nextInt();

        System.out.println("Enter course capacity ");
        int capacity = input.nextInt();

        Course courseInfo = new Course(courseName, cID, numOfCred, instructorID, year, semester, size, capacity);
        courseData.add(courseInfo);

        for (Course testClass : courseData) {
            System.out.println(testClass);
        }

        break;

    default:
        System.out.println("Invalid entry");
        break;
    }

}

I am trying to make an enrollment system. Right now I have made the program so that it prompts the user to choose if they want to add a student, faculty, or course. Once the user picks an option and fills out the questions asked, the program ends. How can I make it loop so that after the user answers the questions, it brings them back to the first prompt where they are given the three choices of what they want to do?

Body:
you can make

while(userChoice!=4){.........your code.........
 System.out.println("Enter 1 to add a student, 2 to add a faculty, 3 to add a course");
  userChoice = input.nextInt();
}


答:
You can do this as well using derive table or CTE as below</p>

```<code>WITH CTE AS(
     select t1.ID,
            t2.Invoice,
            t3.Payment,
            ROW_NUMBER() OVER (PARTITION BY t1.ID,t2.Invoice ORDER BY t1.ID ) RN
     from @Table1 t1
     join @Table2 t2 on t2.OrderID = t1.ID
     join @Table3 t3 on t3.OrderID = t1.ID
)
select ID,
       CASE WHEN RN > 1 THEN NULL ELSE Invoice END,
       Payment
FROM CTE
</code>```

Title: Replace duplicate results with blank

Body:
I am looking to omit duplicate lines of data from my results list.

declare @Table1 TABLE(
    ID int not null,
    OrderNo varchar(5) not null)

declare @Table2 TABLE(
    OrderID int not null,
    Invoice varchar(7) not null)

declare @Table3 TABLE(
    OrderID int not null,
    Payment varchar(7) not null)

insert into @Table1 values (1,'14598'),(2,'14599'),(3,'14600'),(4,'14601')
insert into @Table2 values (1,'35.01'),(1,'396.90'),(1,'79.00'),(2,'786.20'),(3,'40.00'),(3,'93.60'),(3,'43.60'),(4,'15.08')
insert into @Table3 values (1,'20.50'),(1,'180.00'),(2,'786.20'),(2,'15.20'),(2,'186.20'),(3,'40.00'),(3,'93.60'),(3,'43.60'),(4,'15.08')

select t1.ID, t2.Invoice, t3.Payment from @Table1 t1
join @Table2 t2 on t2.OrderID = t1.ID
join @Table3 t3 on t3.OrderID = t1.ID

Table data:

Table1
ID |  OrderNo
-------------
1  |  14598
2  |  14599
3  |  14600
4  |  14601

Table2
OrderID |  Invoice
------------------
1       |   35.01
1       |  396.90
1       |   79.00
2       |  786.20
3       |   40.00
3       |   93.60
3       |   43.60
4       |   15.08

Table3
OrderID | Payment
-----------------
1       |   20.50
1       |  180.00
2       |  786.20
2       |   15.20
2       |  186.20
3       |   40.00
3       |   93.60
3       |   43.60
4       |   15.08

When I try joining all three of these tables together, I get the following:

ID | Invoice | Payment
----------------------
1  | 35.01   | 20.50
1  | 35.01   |180.00
1  | 396.90  | 20.50
1  | 396.90  |180.00
1  | 79.00   | 20.50
1  | 79.00   |180.00
2  | 786.20  |786.20
2  | 786.20  | 15.20
2  | 786.20  |186.20
3  | 40.00   | 40.00
3  | 40.00   | 93.60
3  | 40.00   | 43.60
3  | 93.60   | 40.00
3  | 93.60   | 93.60
3  | 93.60   | 43.60
3  | 43.60   | 40.00
3  | 43.60   | 93.60
3  | 43.60   | 43.60
4  | 15.08   | 15.08

Now as you can see, order 2 only has a single invoice in Table2, however has 3 payments in Table3.  I do want to display 3 lines, with each of the Payments on a separate line, however I don't want it to repeat the single Invoice on each subsequent line.

Subsequently with order 1, there are 3 invoices in Table2, however only 2 payments in Table3.  Currently it is showing everything from Table3 for each entry in Table2, resulting in 6 lines instead of 3.

I only want to report on each amount once, with subsequent lines (if generated due to more than the number of results being in another table) showing blanks.  Selecting DISTINCT doesn't accomplish this.  Is there any way of achieving what I am after here?

ID | Invoice | Payment
----------------------
1  | 35.01   | 20.50
1  | 396.90  | 180.00
1  | 79.00   |
2  | 786.20  | 786.20
2  |         | 15.20
2  |         | 186.20

Body:
You can do this as well using derive table or CTE as below

WITH CTE AS(
     select t1.ID,
            t2.Invoice,
            t3.Payment,
            ROW_NUMBER() OVER (PARTITION BY t1.ID,t2.Invoice ORDER BY t1.ID ) RN
     from @Table1 t1
     join @Table2 t2 on t2.OrderID = t1.ID
     join @Table3 t3 on t3.OrderID = t1.ID
)
select ID,
       CASE WHEN RN > 1 THEN NULL ELSE Invoice END,
       Payment
FROM CTE


问:
javascript find and replace just whole words in a textarea
I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click.  How can I replace only the whole numbers and not parts of the other numbers.  For example, I have:

```<code>XI
XXI
XXXI
</code>```

and I get

```<code>11
X11
XX11
</code>```

but I want

```<code>11
XXI
XXXI
</code>```

The code I'm using is:

```<code>function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}
</code>```

I've seen various solutions with using \b but I can't figure out where to put it in my code.  Thanks.

答:
Here is another way , just split your textArea value by new line ('\n').

var val=["XI", "XXI", "XXXI"]; // $("textarea").val().split('\n');
var outPut = [];
$.each(val, function(index, object) {
 if(object.length == 2){
   outPut.push(object.replace("XI",'11'));
 }else{
    outPut.push(object);
}
 console.log(outPut[outPut.length-1]);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have a text area with a list of roman numerals that I want to convert to arabic digits with a button click.  How can I replace only the whole numbers and not parts of the other numbers.  For example, I have:

XI
XXI
XXXI

and I get

11
X11
XX11

but I want

11
XXI
XXXI

The code I'm using is:

function romanToArabic() {

  var str = document.getElementById("textArea").value;

  var mapObj = {
    XI:"11",
    V:"5"
  };

  var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
  str = str.replace(re, function(matched){
    return mapObj[matched];
  });

  document.getElementById("textArea").value = str;

}

I've seen various solutions with using \b but I can't figure out where to put it in my code.  Thanks.

Body:
Here is another way , just split your textArea value by new line ('\n').

var val=["XI", "XXI", "XXXI"]; // $("textarea").val().split('\n');
var outPut = [];
$.each(val, function(index, object) {
 if(object.length == 2){
   outPut.push(object.replace("XI",'11'));
 }else{
    outPut.push(object);
}
 console.log(outPut[outPut.length-1]);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Group custom post types by taxonomy in timber (Wordpress)
I'm having a hard time figuring out how to group a collection of post with the same taxonomy "year" attached to them in Wordpress, without using a separate archive template.

I Finally managed to get it to work with Wordpress, but now I want to translate this to timber, and I just can't seem to be able to do so. Can anyone give me some pointers?

This is the working wordpress code

```<code>$date_now = date('Y-m-d H:i:s');
$ex_terms = get_terms( 'exhibition-year','orderby=name&order=desc' );

foreach ( $ex_terms as $ex_term ) {
    $member_group_query = new WP_Query(
        array(
            'post_type' => 'exhibition',
            'tax_query' => array(
                array(
                'taxonomy' => 'exhibition-year',
                'field' => 'slug',
                'terms' => array( $ex_term->slug ),
                'operator' => 'IN'
                )
            ),
            'meta_query'        => array(
                array(
                'key'           => 'date_end',
                'compare'       => '<',
                'value'         => $date_now,
                'type'          => 'DATETIME'
                )
            )
        )
    );

    if($ex_term->slug <= date('Y')){
    ?>
        <h2><?php echo $ex_term->name; ?></h2>
        <ul>
        <?php
        if ( $member_group_query->have_posts() ) : while ( $member_group_query->have_posts() ) : $member_group_query->the_post(); ?>
            <li><?php echo the_title(); ?></li>
        <?php endwhile; endif; ?>
        </ul>
        <?php
        // Reset things, for good measure
        $member_group_query = null;
        wp_reset_postdata();
    }
}
</code>```

The desired outcome should look something similar to this, I'm only displaying the titles. But it should contain the entire postdata.

The desired outcome

I've looked into:

https://timber.github.io/docs/reference/timber-post/
https://timber.github.io/docs/reference/timber-postquery/
and
https://timber.github.io/docs/reference/timber/#get-terms

Please help, it's driving me insane :)

答:
@CKDT this is untested, but here's a drive-by re-write in Timber...

PHP

```<code>$date_now = date('Y-m-d H:i:s');
$ex_terms = Timber::get_terms( 'exhibition-year','orderby=name&order=desc' );

foreach ( $ex_terms as &$ex_term ) {
    $member_group_query = Timber::get_posts(
    array(
        'post_type' => 'exhibition',
        'tax_query' => array(
            array(
            'taxonomy' => 'exhibition-year',
            'field' => 'slug',
            'terms' => array( $ex_term->slug ),
            'operator' => 'IN'
            )
        ),
        'meta_query'        => array(
            array(
            'key'           => 'date_end',
            'compare'       => '<',
            'value'         => $date_now,
            'type'          => 'DATETIME'
            )
        )
    ));
    $ex_term->events = $member_group_query;
    if( $ex_term->slug <= date('Y') ){
        $ex_term->past = true;
    }
}
$context['ex_terms'] = $ex_terms;
Timber::render('my-file.twig', $context);
</code>```

Twig File

```<code>{% for term in ex_terms %}
    {% if term.past %}
        <h2>{{ term.name }}</h2>
        <ul>
        {% for post in term.events %}
            <li>{{ post.title }}</li>
        {% endfor %}
        </ul>
{% endfor %}
</code>```

Body:
I'm having a hard time figuring out how to group a collection of post with the same taxonomy "year" attached to them in Wordpress, without using a separate archive template.

I Finally managed to get it to work with Wordpress, but now I want to translate this to timber, and I just can't seem to be able to do so. Can anyone give me some pointers?

This is the working wordpress code

$date_now = date('Y-m-d H:i:s');
$ex_terms = get_terms( 'exhibition-year','orderby=name&order=desc' );

foreach ( $ex_terms as $ex_term ) {
    $member_group_query = new WP_Query(
        array(
            'post_type' => 'exhibition',
            'tax_query' => array(
                array(
                'taxonomy' => 'exhibition-year',
                'field' => 'slug',
                'terms' => array( $ex_term->slug ),
                'operator' => 'IN'
                )
            ),
            'meta_query'        => array(
                array(
                'key'           => 'date_end',
                'compare'       => '<',
                'value'         => $date_now,
                'type'          => 'DATETIME'
                )
            )
        )
    );

    if($ex_term->slug <= date('Y')){
    ?>

<?php echo $ex_term->name; ?>

        <?php
        if ( $member_group_query->have_posts() ) : while ( $member_group_query->have_posts() ) : $member_group_query->the_post(); ?>

<?php echo the_title(); ?>

        <?php endwhile; endif; ?>

        <?php
        // Reset things, for good measure
        $member_group_query = null;
        wp_reset_postdata();
    }
}

The desired outcome should look something similar to this, I'm only displaying the titles. But it should contain the entire postdata.

The desired outcome

I've looked into:

https://timber.github.io/docs/reference/timber-post/
https://timber.github.io/docs/reference/timber-postquery/
and
https://timber.github.io/docs/reference/timber/#get-terms

Please help, it's driving me insane :)

Body:
@CKDT this is untested, but here's a drive-by re-write in Timber...

PHP

$date_now = date('Y-m-d H:i:s');
$ex_terms = Timber::get_terms( 'exhibition-year','orderby=name&order=desc' );

foreach ( $ex_terms as &$ex_term ) {
    $member_group_query = Timber::get_posts(
    array(
        'post_type' => 'exhibition',
        'tax_query' => array(
            array(
            'taxonomy' => 'exhibition-year',
            'field' => 'slug',
            'terms' => array( $ex_term->slug ),
            'operator' => 'IN'
            )
        ),
        'meta_query'        => array(
            array(
            'key'           => 'date_end',
            'compare'       => '<',
            'value'         => $date_now,
            'type'          => 'DATETIME'
            )
        )
    ));
    $ex_term->events = $member_group_query;
    if( $ex_term->slug <= date('Y') ){
        $ex_term->past = true;
    }
}
$context['ex_terms'] = $ex_terms;
Timber::render('my-file.twig', $context);

Twig File

{% for term in ex_terms %}
    {% if term.past %}
        <h2>{{ term.name }}</h2>
        <ul>
        {% for post in term.events %}
            <li>{{ post.title }}</li>
        {% endfor %}
        </ul>
{% endfor %}


问:
Div tag's layering question
Suppose i am having two Div layer

```<code><div id="div1"> One </div>
<div id="div2"> Two </div>
</code>```

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

答:
overlapping can be done by setting position:relative to div1 and having div2 as the child of div1. And set position:absolute; top:0px; left:0px; width:100%; for div2.

```<code><div id="div1">
   <div id="div2"></div>
</div>
</code>```

javascript -

```<code>document.getElementById("div1").onclick = function(){
         //by "Div1 layer to go in the background" i assume you mean disappear or hide
         this.style.display = 'none';
         document.getElementById("div2").style.display = 'block';
};
</code>```

Title: Div tag's layering question

Body:
Suppose i am having two Div layer

 One

 Two

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

Body:
overlapping can be done by setting position:relative to div1 and having div2 as the child of div1. And set position:absolute; top:0px; left:0px; width:100%; for div2.

<div id="div1">
   <div id="div2"></div>
</div>

javascript -

document.getElementById("div1").onclick = function(){
         //by "Div1 layer to go in the background" i assume you mean disappear or hide
         this.style.display = 'none';
         document.getElementById("div2").style.display = 'block';
};


问:
how to get multiple values on ion-select
I am trying to make a simple create group page with ion-select and ion-option.

my html;

```<code><ion-item>
  <ion-label>Select Friends</ion-label>
  <ion-select [(ngModel)]="selectedFriendsArray" multiple="true" cancelText="cancel" okText="ok">
    <ion-option *ngFor="let friend of myFriendsArray; let i = index" value="{{friend.$value}}" selected="false">{{friend.fullName}} (@{{friend.$key}})</ion-option>
  </ion-select>
</ion-item>
</code>```

that's the code, I can successfully get myFriendsArray; that Array's structure is like that; (console.log(myFriendsArray))

```<code>0: {$value: "2MAHfzIraRO3lsYrlwhY6dlVUi52", fullName: "Walter White", userName: "wwhite", $key: "wwhite", $exists: ƒ}
1:{$value: "4TV40AiZb6a9IPNjhSGM7Q15EPz1", fullName: "Jesse Pinkman", userName: "test1", $key: "test1", $exists: ƒ}
2:{$value: "XKCk1bE0DvUKFTPTpFebkxLGI4J2", fullName: "Tony Soprano", userName: "test2", $key: "test2", $exists: ƒ}
3:{$value: "yICGapOLBaZae7EgdiRlGA4lmPF3", fullName: "Paulie", userName: "test4", $key: "test4", $exists: ƒ}
4: {$value: "JrdULejAG3ZXp3ws7foZAvhZb8w2", fullName: "Polat Alemdar", userName: "polat123", $key: "polat123", $exists: ƒ}
</code>```

when the user selects some friends to add, selectedFriendsArray logs in the console like this;

```<code>0: "4TV40AiZb6a9IPNjhSGM7Q15EPz1"
1: "XKCk1bE0DvUKFTPTpFebkxLGI4J2"
2: "yICGapOLBaZae7EgdiRlGA4lmPF3"
</code>```

but I don't want it like that, I want it exactly like this;

```<code>1:{$value: "4TV40AiZb6a9IPNjhSGM7Q15EPz1", userName: "test1"}
2:{$value: "XKCk1bE0DvUKFTPTpFebkxLGI4J2", userName: "test2"}
3:{$value: "yICGapOLBaZae7EgdiRlGA4lmPF3", userName: "test4"}
</code>```

because I want a data structure like this in my database;

groups>groupid>members>memberuid: "memberusername"

I really love ion-option but it writes only value="" input to the array, how can I do that?

thanks for reading assist me please..

答:
```<code><ion-item>
  <ion-label>Select Friends</ion-label>
  <ion-select [(ngModel)]="selectedFriendsArray" multiple="true" cancelText="cancel" okText="ok">
    <ion-option *ngFor="let friend of myFriendsArray; let i = index" value="{{friend.$value}}" selected="false" (ionSelect)="friedFun(friend)">{{friend.fullName}} (@{{friend.$key}})</ion-option>
  </ion-select>
</ion-item>
</code>```

ts file

```<code>friendFun(value){
    var myObj =  {value: value.value, userName:  value.userName};
}
</code>```

Body:
I am trying to make a simple create group page with ion-select and ion-option.

my html;

<ion-item>
  <ion-label>Select Friends</ion-label>
  <ion-select [(ngModel)]="selectedFriendsArray" multiple="true" cancelText="cancel" okText="ok">
    <ion-option *ngFor="let friend of myFriendsArray; let i = index" value="{{friend.$value}}" selected="false">{{friend.fullName}} (@{{friend.$key}})</ion-option>
  </ion-select>
</ion-item>

that's the code, I can successfully get myFriendsArray; that Array's structure is like that; (console.log(myFriendsArray))

0: {$value: "2MAHfzIraRO3lsYrlwhY6dlVUi52", fullName: "Walter White", userName: "wwhite", $key: "wwhite", $exists: ƒ}
1:{$value: "4TV40AiZb6a9IPNjhSGM7Q15EPz1", fullName: "Jesse Pinkman", userName: "test1", $key: "test1", $exists: ƒ}
2:{$value: "XKCk1bE0DvUKFTPTpFebkxLGI4J2", fullName: "Tony Soprano", userName: "test2", $key: "test2", $exists: ƒ}
3:{$value: "yICGapOLBaZae7EgdiRlGA4lmPF3", fullName: "Paulie", userName: "test4", $key: "test4", $exists: ƒ}
4: {$value: "JrdULejAG3ZXp3ws7foZAvhZb8w2", fullName: "Polat Alemdar", userName: "polat123", $key: "polat123", $exists: ƒ}

when the user selects some friends to add, selectedFriendsArray logs in the console like this;

0: "4TV40AiZb6a9IPNjhSGM7Q15EPz1"
1: "XKCk1bE0DvUKFTPTpFebkxLGI4J2"
2: "yICGapOLBaZae7EgdiRlGA4lmPF3"

but I don't want it like that, I want it exactly like this;

1:{$value: "4TV40AiZb6a9IPNjhSGM7Q15EPz1", userName: "test1"}
2:{$value: "XKCk1bE0DvUKFTPTpFebkxLGI4J2", userName: "test2"}
3:{$value: "yICGapOLBaZae7EgdiRlGA4lmPF3", userName: "test4"}

because I want a data structure like this in my database;

groups>groupid>members>memberuid: "memberusername"

I really love ion-option but it writes only value="" input to the array, how can I do that?

thanks for reading assist me please..

Body:
<ion-item>
  <ion-label>Select Friends</ion-label>
  <ion-select [(ngModel)]="selectedFriendsArray" multiple="true" cancelText="cancel" okText="ok">
    <ion-option *ngFor="let friend of myFriendsArray; let i = index" value="{{friend.$value}}" selected="false" (ionSelect)="friedFun(friend)">{{friend.fullName}} (@{{friend.$key}})</ion-option>
  </ion-select>
</ion-item>

ts file

friendFun(value){
    var myObj =  {value: value.value, userName:  value.userName};
}


问:
User registration form without Entity Framework
```<code>[HttpPost]
public ActionResult Create(UserModel userModel)
{

    using (SqlConnection sqlCon= new SqlConnection(connectionString))
    {
        sqlCon.Open();

        String query = "INSERT INTO User VALUES(@UserName, @UserPassword, @UserAddress)";

        SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

        sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
        sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
        sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

        sqlCmd.ExecuteNonQuery();
    }

    return RedirectToAction("Index");
}
</code>```

I'm learning C#. I tried to code CURD operations. In this code there is is a Open() method. I want to know why it used and explain line by line what is code  flow.

答:
If you are performing any database operation from external applications. You need to establish a connection between the database and your application.

To establish a connection between database and your application you must require database "ConnectionString" this connection string is mandatory for performing CRUD operation from any external application.

```<code>SqlConnection sqlCon= new SqlConnection(connectionString);
</code>```

To establish a database connection we are using

```<code>sqlCon.Open();
</code>```

It is better to mention your connection string in web.config file. Because it is highly secured.

Body:
[HttpPost]
public ActionResult Create(UserModel userModel)
{

    using (SqlConnection sqlCon= new SqlConnection(connectionString))
    {
        sqlCon.Open();

        String query = "INSERT INTO User VALUES(@UserName, @UserPassword, @UserAddress)";

        SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

        sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
        sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
        sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

        sqlCmd.ExecuteNonQuery();
    }

    return RedirectToAction("Index");
}

I'm learning C#. I tried to code CURD operations. In this code there is is a Open() method. I want to know why it used and explain line by line what is code  flow.

Body:
If you are performing any database operation from external applications. You need to establish a connection between the database and your application.

To establish a connection between database and your application you must require database "ConnectionString" this connection string is mandatory for performing CRUD operation from any external application.

SqlConnection sqlCon= new SqlConnection(connectionString);

To establish a database connection we are using

sqlCon.Open();

It is better to mention your connection string in web.config file. Because it is highly secured.


问:
How to make overflow-y scroll without changing overflow-x to auto?
I know this is a duplicated question.

And below link is the answer the most nearest with my question that I've found.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

In this link, the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as
  their specified values, except that some combinations with ‘visible’
  are not possible: if one is specified as ‘visible’ and the other is
  ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed
  value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if
  ‘overflow-y’ is the same; otherwise it is the pair of computed values
  of ‘overflow-x’ and ‘overflow-y’.

What I want to know is, are there any new solution of this.

The problem of mine is in this fiddle.

I made 'sidebar' class of 'BootStrap' simple in a fiddle of mine.

```<code>overflow-x: visible;
//overflow-y: scroll;
</code>```

You can see that I commented out 'overflow-y: scroll' of class '.panel' in css part.

In this case, 'hover' will work but 'scroll' won't.

When if I clear that comment out, 'hover' won't work but 'scroll' will.

What I wanna see is, 'hover' and 'scroll' working together.

Does anyone have any ways or ideas to fix this?

Or are there still no way to solve this problem?

答:
I've solved this by adding 'div' between 'div' and 'ul'.

And here's my final fiddle which works almost fitting with my intent.

```<code><div class="panel">         // added div
</code>```

I hope this working will be helpful for anybody. :)

Body:
I know this is a duplicated question.

And below link is the answer the most nearest with my question that I've found.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

In this link, the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as
  their specified values, except that some combinations with ‘visible’
  are not possible: if one is specified as ‘visible’ and the other is
  ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed
  value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if
  ‘overflow-y’ is the same; otherwise it is the pair of computed values
  of ‘overflow-x’ and ‘overflow-y’.

What I want to know is, are there any new solution of this.

The problem of mine is in this fiddle.

I made 'sidebar' class of 'BootStrap' simple in a fiddle of mine.

overflow-x: visible;
//overflow-y: scroll;

You can see that I commented out 'overflow-y: scroll' of class '.panel' in css part.

In this case, 'hover' will work but 'scroll' won't.

When if I clear that comment out, 'hover' won't work but 'scroll' will.

What I wanna see is, 'hover' and 'scroll' working together.

Does anyone have any ways or ideas to fix this?

Or are there still no way to solve this problem?

Body:
I've solved this by adding 'div' between 'div' and 'ul'.

And here's my final fiddle which works almost fitting with my intent.

<div class="panel">         // added div

I hope this working will be helpful for anybody. :)


问:
Firebase sorting data in descending order. (only half sorted.)
I am trying to sort my listview into descending order by the value. I have tried using Collections.reverse(list); but I dont know why only half the list is sorted into descending. The bottom half is in ascending order.

The Following is my Code:

```<code>com.firebase.client.Query Queryref = mRef.orderByValue().limitToLast(20);
Queryref.addChildEventListener(new com.firebase.client.ChildEventListener() {
    @Override
    public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
        String value = dataSnapshot.getValue(String.class);
        String boothname = dataSnapshot.getKey();
        list.add(new Booth(boothname, value));
        adapter.notifyDataSetChanged();

        Collections.reverse(list);
    }
</code>```

The Code above allow me to display the top 20 highest value in ascending.
But I want it to be in descending and tried using Collections.reverse();
But the output I received show only the first 10 data in descending. Please help :(

答:
An alternative to Doug's approach is to insert each child at the start of the list, instead of adding to the end of the list as you do now.

For example, if your list variable is an List you can insert at the start with add(index, value):

```<code>list.add(0, new Booth(boothname, value));
</code>```

Body:
I am trying to sort my listview into descending order by the value. I have tried using Collections.reverse(list); but I dont know why only half the list is sorted into descending. The bottom half is in ascending order.

The Following is my Code:

com.firebase.client.Query Queryref = mRef.orderByValue().limitToLast(20);
Queryref.addChildEventListener(new com.firebase.client.ChildEventListener() {
    @Override
    public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
        String value = dataSnapshot.getValue(String.class);
        String boothname = dataSnapshot.getKey();
        list.add(new Booth(boothname, value));
        adapter.notifyDataSetChanged();

        Collections.reverse(list);
    }

The Code above allow me to display the top 20 highest value in ascending.
But I want it to be in descending and tried using Collections.reverse();
But the output I received show only the first 10 data in descending. Please help :(

Body:
An alternative to Doug's approach is to insert each child at the start of the list, instead of adding to the end of the list as you do now.

For example, if your list variable is an List you can insert at the start with add(index, value):

list.add(0, new Booth(boothname, value));


问:
Node process.env.VARIABLE_NAME returning undefined
I'm using environment variables on my mac to store some sensitive credentials, and trying to access them through Node. I added them into my environment profile with

export VARIABLE_NAME=mySensitiveInfo

When I use echo $VARIABLE_NAME I receive the correct output (my sensitive info).

However, when I am trying to access this same variable in Node with process.env.VARIABLE_NAME and try to print it out on the console, I get an undefined.

Other environment variables appear to be okay though. For example, when I console.log(process.env.FACEBOOK_CALLBACK_URL), it prints the correct value to my console. I added FACEBOOK_CALLBACK_URL a few days ago.

Do I have to restart my machine or something? Does it take a certain time before environment variables become available in Node? The closest answer I've seen on SO is this post, but nobody was able to figure out why it was happening.

答:
I got a problem just now , and I use this solved it in webpack config</p>

```<code>const plugins = [
    new webpack.NoEmitOnErrorsPlugin(),
    // after compile global will defined `process.env` this Object
    new webpack.DefinePlugin({
      BUILD_AT : Date.now().toString(32),
      DEBUG: process.env.NODE_ENV !== 'production',
          'process.env': {
              'NODE_ENV': JSON.stringify(process.env.NODE_ENV || "development"),
              'VARIABLE_NAME': JSON.stringify(process.env.VARIABLE_NAME)
     }
   })
]
</code>```

Body:
I got a problem just now , and I use this solved it in webpack config

const plugins = [
    new webpack.NoEmitOnErrorsPlugin(),
    // after compile global will defined `process.env` this Object
    new webpack.DefinePlugin({
      BUILD_AT : Date.now().toString(32),
      DEBUG: process.env.NODE_ENV !== 'production',
          'process.env': {
              'NODE_ENV': JSON.stringify(process.env.NODE_ENV || "development"),
              'VARIABLE_NAME': JSON.stringify(process.env.VARIABLE_NAME)
     }
   })
]


问:
When analyzing the time complexity of an algorithm why do we drop the constant of the term with the largest degree
Suppose I have the following : T(n) = 5n^2 +2n
The asymtotic tight bound of this is theta n^2. I want to understand the reason behind dropping the 5. I understand why we ignore the lower order terms.</p>

答:
The constant is dropped because it does not affect which complexity class the function belongs to.

If you have two functions f(n) = c1 * n^2 and g(n) = c2 * n^3, where c1 and c2 are constants, it doesn't matter how large c1 is and how small c2 is, g(n) will ALWAYS overtake and outgrow f(n) at some value of n.


问:
access denied in lambda when trying to access file uploaded to s3 bucket
Following on from the great help I received on my original post

Uploading a file to an s3 bucket, triggering a lambda, which sends an email containing info on the file uploaded to s3 buket

I have tested previously sending the email so I know that works but when I try to include the data of the upload it fires error

```<code>Could not fetch object data:  { AccessDenied: Access Denied
at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/services/s3.js:577:35)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)
</code>```

I have found many q's related to this online regarding policies around roles etc..So I have added lambda to the s3 event, and added s3 permission to the role eg.

```<code>https://stackoverflow.com/questions/35589641/aws-lambda-function-getting-access-denied-when-getobject-from-s3
</code>```

Unfortunately none of these have helped. I noticed a comment however

```<code>Then the best solution is to allow S3FullAccess, see if it works. If it does, then remove one set of access at a time from the policy and find the least privileges required for your Lambda to work. If it does not work even after giving S3FullAccess, then the problem is elsewhere
</code>```

So how would I go about finding where the problem is?

Thank Y

```<code>   'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});
//var fileType = require('file-type');

console.log('Loading function2');

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

console.log('Loading function3');
//var textt = "";

exports.handler = function(event, context) {
    console.log("Incoming: ", event);

  //  textt = event.Records[0].s3.object.key;
   // var output = querystring.parse(event);

   //var testData = null;

   // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucket',
       Key: 'key',
    };

    s3.getObject(params, function(err, objectData) {
    if (err) {
        console.log('Could not fetch object data: ', err);
    } else {
        console.log('Data was successfully fetched from object');
        var eParams = {
            Destination: {
                ToAddresses: ["fake@fake.com"]
            },
            Message: {
                Body: {
                    Text: {
                        Data: objectData
                       // Data: textt
                    }
                },
                Subject: {
                    Data: "Email Subject!!!"
                }
            },
            Source: "fake@fake.com"
        };

        console.log('===SENDING EMAIL===');

        var email = ses.sendEmail(eParams, function(err, emailResult) {
            if (err) console.log('Error while sending email', err);
            else {
                console.log("===EMAIL SENT===");
                //console.log(objectData);
                console.log("EMAIL CODE END");
                console.log('EMAIL: ', emailResult);
                context.succeed(event);
            }
        });
    }
});

};
</code>```

UPDATE
I have added comments to the code and checked the logs...it doesnt go past this line

```<code>var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });
</code>```

Is this anyway related to access denied?

NOTE: ALL I WANT IN THE FILENAME OF THE UPLOADED FILE

UPDATE 2

iv replaced the line causing issue with var s3 = new aws.S3().getObject({ Bucket: this.awsBucketName, Key: 'keyName' }, function(err, data)
{
    if (!err)
        console.log(data.Body.toString());
});

but this is firing as TypeError: s3.getObject is not a function

Also tried...var s3 = new aws.S3();

this is back to the original error of Could not fetch object data:  { AccessDenied: Access Denied

答:
First of all region should be S3 bucket region and not lambda region. Next you need to verify your credentials and if they have access to S3 bucket you have defined. As you stated in one of the comment try attaching S3 full access Amazon managed policy to your IAM user which is associated with credentials you are using in Lambda. Next step would be use aws cli to see if you can access this bucket. Maybe something like -

```<code>aws s3 ls
</code>```

Having said above you should not use credentials at all. Since Lambda and S3 are amazon services you should use roles. Just give Lambda a role that gives it full access to S3 and do not use aws IAM credentials for this. And

```<code>var s3 = new AWS.S3();
</code>```

is sufficient.

Body:
Following on from the great help I received on my original post

Uploading a file to an s3 bucket, triggering a lambda, which sends an email containing info on the file uploaded to s3 buket

I have tested previously sending the email so I know that works but when I try to include the data of the upload it fires error

Could not fetch object data:  { AccessDenied: Access Denied
at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/services/s3.js:577:35)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)

I have found many q's related to this online regarding policies around roles etc..So I have added lambda to the s3 event, and added s3 permission to the role eg.

https://stackoverflow.com/questions/35589641/aws-lambda-function-getting-access-denied-when-getobject-from-s3

Unfortunately none of these have helped. I noticed a comment however

Then the best solution is to allow S3FullAccess, see if it works. If it does, then remove one set of access at a time from the policy and find the least privileges required for your Lambda to work. If it does not work even after giving S3FullAccess, then the problem is elsewhere

So how would I go about finding where the problem is?

Thank Y

   'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});
//var fileType = require('file-type');

console.log('Loading function2');

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

console.log('Loading function3');
//var textt = "";

exports.handler = function(event, context) {
    console.log("Incoming: ", event);

  //  textt = event.Records[0].s3.object.key;
   // var output = querystring.parse(event);

   //var testData = null;

   // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucket',
       Key: 'key',
    };

    s3.getObject(params, function(err, objectData) {
    if (err) {
        console.log('Could not fetch object data: ', err);
    } else {
        console.log('Data was successfully fetched from object');
        var eParams = {
            Destination: {
                ToAddresses: ["fake@fake.com"]
            },
            Message: {
                Body: {
                    Text: {
                        Data: objectData
                       // Data: textt
                    }
                },
                Subject: {
                    Data: "Email Subject!!!"
                }
            },
            Source: "fake@fake.com"
        };

        console.log('===SENDING EMAIL===');

        var email = ses.sendEmail(eParams, function(err, emailResult) {
            if (err) console.log('Error while sending email', err);
            else {
                console.log("===EMAIL SENT===");
                //console.log(objectData);
                console.log("EMAIL CODE END");
                console.log('EMAIL: ', emailResult);
                context.succeed(event);
            }
        });
    }
});

};

UPDATE
I have added comments to the code and checked the logs...it doesnt go past this line

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

Is this anyway related to access denied?

NOTE: ALL I WANT IN THE FILENAME OF THE UPLOADED FILE

UPDATE 2

iv replaced the line causing issue with var s3 = new aws.S3().getObject({ Bucket: this.awsBucketName, Key: 'keyName' }, function(err, data)
{
    if (!err)
        console.log(data.Body.toString());
});

but this is firing as TypeError: s3.getObject is not a function

Also tried...var s3 = new aws.S3();

this is back to the original error of Could not fetch object data:  { AccessDenied: Access Denied

Body:
First of all region should be S3 bucket region and not lambda region. Next you need to verify your credentials and if they have access to S3 bucket you have defined. As you stated in one of the comment try attaching S3 full access Amazon managed policy to your IAM user which is associated with credentials you are using in Lambda. Next step would be use aws cli to see if you can access this bucket. Maybe something like -

aws s3 ls

Having said above you should not use credentials at all. Since Lambda and S3 are amazon services you should use roles. Just give Lambda a role that gives it full access to S3 and do not use aws IAM credentials for this. And

var s3 = new AWS.S3();

is sufficient.


问:
How can I get the amounts of various characters from strings in C++?
I am trying to use a C++ program to get a string from the user, and calculate and output how many spaces the user used, how many letters, and how many digits from 1-9. This is my code:

```<code>    #include <stdio.h>
    #include <conio.h>
    #include <iostream>
    int main()
    {
        char instr[255];
        printf("Input characters, up to 255,  and Number of various
        characters \nwill be calculated and output.\nPress any key to
        continue.\n");
        scanf("%[^\n]%*c%c", &instr);
        getch();
        system("CLS");
        printf("String Value: %s\n", instr);
        getch();
        return 0;
   }
</code>```

The result: I can successfully input and output a string, however I am unaware of any ways of finding the character values.

答:
Perhaps you are looking forward something like this</p>

```<code> string a;
    getline(cin,a);
    cout<<a<<endl;
    int space=0,line=0,digit=0,letter=0;
    for(int i=0;i<a.size();i++)
    {
        if(a[i]==' ')
            space++;
        else if(a[i]>='A' && a[i]<='z')
            letter++;
        else if(a[i]>='0' && a[i]<='9') digit++;
        else;

    }
    cout<<space<<"  "<<letter<<"  "<<digit<<endl;
</code>```

Body:
I am trying to use a C++ program to get a string from the user, and calculate and output how many spaces the user used, how many letters, and how many digits from 1-9. This is my code:

    #include <stdio.h>
    #include <conio.h>
    #include <iostream>
    int main()
    {
        char instr[255];
        printf("Input characters, up to 255,  and Number of various
        characters \nwill be calculated and output.\nPress any key to
        continue.\n");
        scanf("%[^\n]%*c%c", &instr);
        getch();
        system("CLS");
        printf("String Value: %s\n", instr);
        getch();
        return 0;
   }

The result: I can successfully input and output a string, however I am unaware of any ways of finding the character values.

Body:
Perhaps you are looking forward something like this

 string a;
    getline(cin,a);
    cout<<a<<endl;
    int space=0,line=0,digit=0,letter=0;
    for(int i=0;i<a.size();i++)
    {
        if(a[i]==' ')
            space++;
        else if(a[i]>='A' && a[i]<='z')
            letter++;
        else if(a[i]>='0' && a[i]<='9') digit++;
        else;

    }
    cout<<space<<"  "<<letter<<"  "<<digit<<endl;


问:
Why my email sender does not update when I change the settings in env laravel on staging server?
I use laravel 5.3 and I change env on the staging server on the forge (https://forge.laravel.com)

I change like this :

```<code>#MAIL_HOST=smtp.gmail.com
#MAIL_PORT=587
#MAIL_USERNAME=mygmail@gmail.com
#MAIL_PASSWORD=secret
#MAIL_ENCRYPTION=tls

MAIL_HOST=mail.myshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@myshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls
</code>```

If I try send mail in my system, the email sender is mygmail@gmail.com

Should the email sender contact@myshop.id

How can I solve this problem?

答:
I’m hesitating between two possible issues..
First possibility: That might be because of the use of a cache by your artisan server if you are running your app with it.
So try to stop your artisan server and restart it
Second one: the email is set somewhere else. So check your config files (in config/ directory).

Hope this will help

Body:
I use laravel 5.3 and I change env on the staging server on the forge (https://forge.laravel.com)

I change like this :

#MAIL_HOST=smtp.gmail.com
#MAIL_PORT=587
#MAIL_USERNAME=mygmail@gmail.com
#MAIL_PASSWORD=secret
#MAIL_ENCRYPTION=tls

MAIL_HOST=mail.myshop.id
MAIL_PORT=587
MAIL_USERNAME=contact@myshop.id
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

If I try send mail in my system, the email sender is mygmail@gmail.com

Should the email sender contact@myshop.id

How can I solve this problem?


问:
How are data types interpreted, calculated, and/or stored?
In python, suppose the code is:</p>

```<code>import.math

a = math.sqrt(2.0)

if a * a == 2.0:
    x = 2
else:
    x = 1
</code>```

答:
Numbers with decimals are stored as floating point numbers and they can only be an approximation to the real number in some cases.

So your comparison needs to be not "are these two numbers exactly equal (==)" but "are they sufficiently close as to be considered equal".

Fortunately, in the math library, there's a function to do that conveniently. Using isClose(), you can compare with a defined tolerance. The function isn't too complicated, you could do it yourself.

```<code>math.isclose(a*a, 2, abs_tol=0.0001)
>> True
</code>```

Body:
In python, suppose the code is:

import.math

a = math.sqrt(2.0)

if a * a == 2.0:
    x = 2
else:
    x = 1

Body:
Numbers with decimals are stored as floating point numbers and they can only be an approximation to the real number in some cases.

So your comparison needs to be not "are these two numbers exactly equal (==)" but "are they sufficiently close as to be considered equal".

Fortunately, in the math library, there's a function to do that conveniently. Using isClose(), you can compare with a defined tolerance. The function isn't too complicated, you could do it yourself.

math.isclose(a*a, 2, abs_tol=0.0001)
>> True


问:
What is the correct way to remove resource images from a VS project?
I have imported images through the visual studio designer to the projects resource file. Some of these images are no longer used and I want to remove them.

However, I've tried to remove the resource images before by deleting the image file through the solution explorer and then removing the corresponding <data> element from the .resx file. However, this causes the VS designer to have a panic attack and start throwing exceptions saying it can't find the files I've just removed even though they are not referenced anywhere.

What is the a proper way of deleting images from the resource file?

答: You should select the resource in the resource grid and click Remove Resource, as described in this MSDN article.


问:
How to read two columns using python
How to read two columns the first of which contains letters and the second of the values.

```<code>C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979
</code>```

I often used this script below (it works for two or more columns), but not for this time !!

```<code>with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]
</code>```

Thanks for your help.

答:
You don't need any libraries at all, let alone pandas or re. Just read the file and use list comprehensions plus string methods to extract the data.

```<code>with open('file.csv', 'r') as f:
    data = f.readlines()

oX = [line.replace('\n', '').split(',')[0] for line in data]
oY = [float(line.replace('\n', '').split(',')[1]) for line in data]
</code>```

If you want each label paired with it's value you can zip them up.

```<code>paired = zip(ox, oY)
</code>```

Title: How to read two columns using python

Body:
How to read two columns the first of which contains letters and the second of the values.

C0      -0.158040
C1      -0.157117
C2      -0.143805
C3      -0.140561
S4      0.059175
H5      0.128940
H6      0.129007
H7      0.142421
H8      0.139979

I often used this script below (it works for two or more columns), but not for this time !!

with open('file.csv') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    oX=[x[0] for x in data]
    oY=[x[1] for x in data]

Thanks for your help.

Body:
You don't need any libraries at all, let alone pandas or re. Just read the file and use list comprehensions plus string methods to extract the data.

with open('file.csv', 'r') as f:
    data = f.readlines()

oX = [line.replace('\n', '').split(',')[0] for line in data]
oY = [float(line.replace('\n', '').split(',')[1]) for line in data]

If you want each label paired with it's value you can zip them up.

paired = zip(ox, oY)


问:
undefined reference to a pointer in c
I'm trying to run my program, but it keeps giving an error.

I have 3 files and will include the code from one of the 3 functions that are not working.

File: contacts.h

```<code>struct Name{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Contact{
    struct Name name;
};

// function prototype:
void getName(struct Name *);
</code>```

File: contacts.c

```<code>#include <stdio.h>
#include “contacts.h”

void getName(struct Name *name)
{
    printf(“Please enter the contact’s first name: “);
    scanf(“%30[&\n]”, name->firstName);
}
</code>```

File:a1ms4.c

```<code>#include <stdio.h>
#include “contacts.h”

int main(void)
{
    struct Contact contact = { {0} };
    getName(&contect.name);
    printf(“Contact first name: %s\n”, contact.name.firstName);

    return 0;
}
</code>```

Any idea why I'm getting this error:

```<code>a1ms4.c:(.text+0x53): undefined reference to `getName'
</code>```

答:
Probably you are compiling it the wrong way.
Try this
gcc -c a1ms4.c
gcc -c contacts.c
gcc -Wall a1ms4.o contacts.o -o contact</p>

Title: undefined reference to a pointer in c

Body:
I'm trying to run my program, but it keeps giving an error.

I have 3 files and will include the code from one of the 3 functions that are not working.

File: contacts.h

struct Name{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Contact{
    struct Name name;
};

// function prototype:
void getName(struct Name *);

File: contacts.c

#include <stdio.h>
#include “contacts.h”

void getName(struct Name *name)
{
    printf(“Please enter the contact’s first name: “);
    scanf(“%30[&\n]”, name->firstName);
}

File:a1ms4.c

#include <stdio.h>
#include “contacts.h”

int main(void)
{
    struct Contact contact = { {0} };
    getName(&contect.name);
    printf(“Contact first name: %s\n”, contact.name.firstName);

    return 0;
}

Any idea why I'm getting this error:

a1ms4.c:(.text+0x53): undefined reference to `getName'


问:
Spark SQL Dataframe API -build filter condition dynamically
I have two Spark dataframe's, df1 and df2:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| ramesh| 1212| 29|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+
```

<pre class="lang-none prettyprint-override"><code>+------+-----+---+-----+
| eName|  eNo|age| city|
+------+-----+---+-----+
|aarush|12121| 15|malmo|
|ramesh| 1212| 29|malmo|
+------+-----+---+-----+
</code>```

I need to get the non matching records from df1, based on a number of columns which is specified in another file.

For example, the column look up file is something like below:

df1col,df2col
name,eName
empNo, eNo
```

<p><strong>Expected output is:</strong></p>

<pre class="lang-none prettyprint-override"><code>+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+
</code>```

The idea is how to build a where condition dynamically for the above scenario, because the lookup file is configurable, so it might have 1 to n fields.

答:
If you're doing this from a SQL query I would remap the column names in the SQL query itself with something like Changing a SQL column title via query. You could do a simple text replace in the query to normalize them to the df1 or df2 column names.

Once you have that you can diff using something like
How to obtain the difference between two DataFrames?

If you need more columns that wouldn't be used in the diff (e.g. age) you can reselect the data again based on your diff results. This may not be the optimal way of doing it but it would probably work.

ContentLicense: CC BY-SA 4.0

Body:
I have two Spark dataframe's, df1 and df2:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| ramesh| 1212| 29|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+

+------+-----+---+-----+
| eName|  eNo|age| city|
+------+-----+---+-----+
|aarush|12121| 15|malmo|
|ramesh| 1212| 29|malmo|
+------+-----+---+-----+

I need to get the non matching records from df1, based on a number of columns which is specified in another file.

For example, the column look up file is something like below:

df1col,df2col
name,eName
empNo, eNo

Expected output is:

+-------+-----+---+
|   name|empNo|age|
+-------+-----+---+
|shankar|12121| 28|
| suresh| 1111| 30|
| aarush| 0707| 15|
+-------+-----+---+

The idea is how to build a where condition dynamically for the above scenario, because the lookup file is configurable, so it might have 1 to n fields.


问:
Spring KeyGenerator For Appending Cache name to the key
I am using spring cache with Redis for caching

I have the following methods:

```<code>    @CachePut(value ="DATA1", key = "#key1")
    public Object saveData1(long key1, Object obj) {
        return obj;
    }

    @CachePut(value ="DATA2", key = "#key1")
    public Object saveData2(long key1, Object obj) {
        return obj;
    }
</code>```

This is causing collisions in keys and the data is being overridden.

I want to generate the key with the cache name appended to it.

Like: DATA1-key1, DATA2-key1.

Is it possible?

I have seen a few examples which use class name and method name. But I want to use the cache name.

Thank you.

答:
You need to set parameter "usePrefix" as true in your CacheManager bean. This will prepend cacheName in your keys.</p>

```<code><bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    ...
     <property name="usePrefix"><value>true</value></property>
    ...
</bean>
</code>```

Body:
I am using spring cache with Redis for caching

I have the following methods:

    @CachePut(value ="DATA1", key = "#key1")
    public Object saveData1(long key1, Object obj) {
        return obj;
    }

    @CachePut(value ="DATA2", key = "#key1")
    public Object saveData2(long key1, Object obj) {
        return obj;
    }

This is causing collisions in keys and the data is being overridden.

I want to generate the key with the cache name appended to it.

Like: DATA1-key1, DATA2-key1.

Is it possible?

I have seen a few examples which use class name and method name. But I want to use the cache name.

Thank you.

Body:
You need to set parameter "usePrefix" as true in your CacheManager bean. This will prepend cacheName in your keys.

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    ...
     <property name="usePrefix"><value>true</value></property>
    ...
</bean>


问:
Load an image into a PictureBox on a different thread
I am trying to load a picture that is fetched on-demand from Google's Static Maps based against a (UK) Post Code.

Lets say I have a client and the clients has an address. One of the properties of client is PostCode. I have a form that loads clients. I feed the client ID to this form's constructor and then use LINQ 2 SQL to load all sorts of information including an address.

```<code>private void LoadBranchDetails() {
  Text_Update_BI_Name.Text = Branch.BranchNumber;
  Text_Update_BI_Manager.Text = String.Format("{0} {1}", Branch.PharmacyManager.FirstName, Branch.PharmacyManager.LastName);
  DropDownList_Update_BI_Coordinator.SelectedValue = Branch.CoordinatorID;
  DropDownList_Update_BI_ComputerSystem.SelectedValue = Branch.ComputerSystemID;
  Text_Update_BI_Phone.Text = Branch.PhoneNumber;
  Text_Update_BI_Fax.Text = Branch.FaxNumber;

  Address BranchAddress = Branch.Contact.Addresses.FirstOrDefault();
  Text_Update_AI_House.Text = BranchAddress.HouseNumber;
  Text_Update_AI_Street.Text = BranchAddress.Street;
  Text_Update_AI_Area.Text = BranchAddress.Area;
  Text_Update_AI_Post.Text = BranchAddress.PostCode;
  DropDownList_Update_AI_City.SelectedValue = BranchAddress.City.OID;

  MaskedText_Update_OI_NoPharmacist.Value = Branch.NumberOfPharmacists;
  MaskedText_Update_OI_NoDispensers.Value = Branch.NumberOfDispensers;
  MaskedText_Update_OI_NoMonFri.Value = Branch.NumberOfItemsMondayToFriday;
  MaskedText_Update_OI_NoSat.Value = Branch.NumberOfItemsSaturday;
  MaskedText_Update_OI_NoSun.Value = Branch.NumberOfItemsSunday;
  MaskedText_Update_OI_NoAddicts.Value = Branch.NumberOfAddicts;
  MaskedText_Update_OI_NoSupervised.Value = Branch.Supervised;
  MaskedText_Update_OI_NoUnsupervised.Value = Branch.Unsupervised;

  Check_Update_OI_ConfRoom.Checked = Branch.ConsultationRoom;

  try {
    PictureGoogleMaps.Image = GoogleAddressInfo.FetchMapInfo(Text_Update_AI_Post.Text).GoogleStaticMap;

  } catch (Exception) {
    PictureGoogleMaps.Image = Resources.DefaultGoogleMap;

  }
}
</code>```

The line that loads the image into the PictureGoogleMaps causes a hang in UI as the ".GoogleStaticMap" property generates the Google static image when called.

Upon searching the internet, i found this helpful example:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Declare a list of URLs and their respective picture boxes
        var items = new Dictionary<string, PictureBox>
        {
            { "http://www.google.com/logos/spring09.gif", new PictureBox() { Top = 0, Width = 300, Height = 80  } },
            { "http://www.google.com/logos/stpatricks_d4gwinner_eo09.gif", new PictureBox() { Top = 100, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/schiaparelli09.gif", new PictureBox() { Top = 200, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/drseuss09.gif", new PictureBox() { Top = 300, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/valentines09.gif", new PictureBox() { Top = 400, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/unix1234567890.gif", new PictureBox() { Top = 500, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/charlesdarwin_09.gif", new PictureBox() { Top = 600, Width = 300, Height = 80 } },
        };

        foreach (var item in items)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                // This function will be run on a background thread
                // spawned from the thread pool.
                using (var client = new WebClient())
                {
                    var pair = (KeyValuePair<string, PictureBox>)e.Argument;
                    e.Result = new KeyValuePair<PictureBox, byte[]>(pair.Value, client.DownloadData(pair.Key));
                }
            };
            worker.RunWorkerCompleted += (o, e) =>
            {
                // This function will be run on the main GUI thread
                var pair = (KeyValuePair<PictureBox, byte[]>)e.Result;
                using (var stream = new MemoryStream(pair.Value))
                {
                    pair.Key.Image = new Bitmap(stream);
                }
                Controls.Add(pair.Key);
            };
            worker.RunWorkerAsync(item);
        }
    }
}
</code>```

Now I just need to figure out how to remove the for loop and use this in my scenario. Any ideas?

The sample code comes from this link.

Thanks.

答: Is it that hard to remove the foreach loop? You only need to load a single picture so remove the foreach loop and pass the url of the picture and the target picturebox to the backgroundworker.</p>

Body:
I am trying to load a picture that is fetched on-demand from Google's Static Maps based against a (UK) Post Code.

Lets say I have a client and the clients has an address. One of the properties of client is PostCode. I have a form that loads clients. I feed the client ID to this form's constructor and then use LINQ 2 SQL to load all sorts of information including an address.

private void LoadBranchDetails() {
  Text_Update_BI_Name.Text = Branch.BranchNumber;
  Text_Update_BI_Manager.Text = String.Format("{0} {1}", Branch.PharmacyManager.FirstName, Branch.PharmacyManager.LastName);
  DropDownList_Update_BI_Coordinator.SelectedValue = Branch.CoordinatorID;
  DropDownList_Update_BI_ComputerSystem.SelectedValue = Branch.ComputerSystemID;
  Text_Update_BI_Phone.Text = Branch.PhoneNumber;
  Text_Update_BI_Fax.Text = Branch.FaxNumber;

  Address BranchAddress = Branch.Contact.Addresses.FirstOrDefault();
  Text_Update_AI_House.Text = BranchAddress.HouseNumber;
  Text_Update_AI_Street.Text = BranchAddress.Street;
  Text_Update_AI_Area.Text = BranchAddress.Area;
  Text_Update_AI_Post.Text = BranchAddress.PostCode;
  DropDownList_Update_AI_City.SelectedValue = BranchAddress.City.OID;

  MaskedText_Update_OI_NoPharmacist.Value = Branch.NumberOfPharmacists;
  MaskedText_Update_OI_NoDispensers.Value = Branch.NumberOfDispensers;
  MaskedText_Update_OI_NoMonFri.Value = Branch.NumberOfItemsMondayToFriday;
  MaskedText_Update_OI_NoSat.Value = Branch.NumberOfItemsSaturday;
  MaskedText_Update_OI_NoSun.Value = Branch.NumberOfItemsSunday;
  MaskedText_Update_OI_NoAddicts.Value = Branch.NumberOfAddicts;
  MaskedText_Update_OI_NoSupervised.Value = Branch.Supervised;
  MaskedText_Update_OI_NoUnsupervised.Value = Branch.Unsupervised;

  Check_Update_OI_ConfRoom.Checked = Branch.ConsultationRoom;

  try {
    PictureGoogleMaps.Image = GoogleAddressInfo.FetchMapInfo(Text_Update_AI_Post.Text).GoogleStaticMap;

  } catch (Exception) {
    PictureGoogleMaps.Image = Resources.DefaultGoogleMap;

  }
}

The line that loads the image into the PictureGoogleMaps causes a hang in UI as the ".GoogleStaticMap" property generates the Google static image when called.

Upon searching the internet, i found this helpful example:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // Declare a list of URLs and their respective picture boxes
        var items = new Dictionary<string, PictureBox>
        {
            { "http://www.google.com/logos/spring09.gif", new PictureBox() { Top = 0, Width = 300, Height = 80  } },
            { "http://www.google.com/logos/stpatricks_d4gwinner_eo09.gif", new PictureBox() { Top = 100, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/schiaparelli09.gif", new PictureBox() { Top = 200, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/drseuss09.gif", new PictureBox() { Top = 300, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/valentines09.gif", new PictureBox() { Top = 400, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/unix1234567890.gif", new PictureBox() { Top = 500, Width = 300, Height = 80 } },
            { "http://www.google.com/logos/charlesdarwin_09.gif", new PictureBox() { Top = 600, Width = 300, Height = 80 } },
        };

        foreach (var item in items)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (o, e) =>
            {
                // This function will be run on a background thread
                // spawned from the thread pool.
                using (var client = new WebClient())
                {
                    var pair = (KeyValuePair<string, PictureBox>)e.Argument;
                    e.Result = new KeyValuePair<PictureBox, byte[]>(pair.Value, client.DownloadData(pair.Key));
                }
            };
            worker.RunWorkerCompleted += (o, e) =>
            {
                // This function will be run on the main GUI thread
                var pair = (KeyValuePair<PictureBox, byte[]>)e.Result;
                using (var stream = new MemoryStream(pair.Value))
                {
                    pair.Key.Image = new Bitmap(stream);
                }
                Controls.Add(pair.Key);
            };
            worker.RunWorkerAsync(item);
        }
    }
}

Now I just need to figure out how to remove the for loop and use this in my scenario. Any ideas?

The sample code comes from this link.

Thanks.


问:
Add userAdmin in MongoDB Atlas
How to add a user with userAdmin role in Atlas?

The Cluster Security "Add New User" UI https://cloud.mongodb.com/v2/.....#clusters/security/users shows only limited set of built-in roles without any option to enter role name manually:

So I am a bit stuck here - there are no options in the UI, and non of the existing roles allow to add users in a shell.

None of the roles in the list have userAdmin privilege.

The most "powerful" atlasAdmin assigned to a user on Create Cluster page covers only:

readWriteAnyDatabase

readAnyDatabase

enableSharding

dbAdminAnyDatabase

clusterMonitor

and doesn't have enough privilege to execute db.createUser() command in the shell.

答:
You cannot grant this role. The only way to create new MongoDB users in Atlas is either via the UI or the API. See Add MongoDB Users for details and note that this page states:

Atlas rolls back any user modifications not made through the UI or API. You must use the Atlas UI or API to add, modify, or delete MongoDB users on Atlas clusters.

See Create a Database User for details on how to create MongoDB users via the API.

Title: Add userAdmin in MongoDB Atlas


问:
How do I stack bootstrap grid columns one below the other instead of one beside another?
I am just beginning to learn Bootstrap and I came across the grid system. I was playing around and noticed that the grid columns always start from the left and go towards the right, placing the divs one beside another. How do I make them appear one below the other?
Here's some sample code:

```<code><body>

<div class="container-fluid">
  <h2>Three Equal Columns</h2>
  <div class="row">
    <div class="col-4 bg-success">.col-1</div>
    <div class="col-4 bg-warning">.col-2</div>
    <div class="col-4 bg-success">.col-3</div>
  </div>
</div>

</body>
</code>```

Here's a fiddle.
https://jsfiddle.net/txdqjf8b/2/

How do I make col-1, col-2 and col-3 appear one below the other, so that later if I have a col-4, col-5 and col-6, I want them like this:

```<code>col-1    col-4    col-7
col-2    col-5    col-8
col-3    col-6    col-9
</code>```

答:
This will work for you. </p>

```<code><div class="row">
  <div class="col-4 bg-success">.col-1</div>
</div>
<div class="row">
  <div class="col-4 bg-warning">.col-2</div>
</div>
<div class="row">
  <div class="col-4 bg-success">.col-3</div>
</div>
</code>```

Body:
I am just beginning to learn Bootstrap and I came across the grid system. I was playing around and noticed that the grid columns always start from the left and go towards the right, placing the divs one beside another. How do I make them appear one below the other?
Here's some sample code:

Three Equal Columns

.col-1

.col-2

.col-3

Here's a fiddle.
https://jsfiddle.net/txdqjf8b/2/

How do I make col-1, col-2 and col-3 appear one below the other, so that later if I have a col-4, col-5 and col-6, I want them like this:

col-1    col-4    col-7
col-2    col-5    col-8
col-3    col-6    col-9

Body:
This will work for you.

<div class="row">
  <div class="col-4 bg-success">.col-1</div>
</div>
<div class="row">
  <div class="col-4 bg-warning">.col-2</div>
</div>
<div class="row">
  <div class="col-4 bg-success">.col-3</div>
</div>


问:
Trouble with comparing 2 dimensional arrays
I keep getting a false boolean value from the following comparison:

```<code>public boolean getHz1() {
    return board[0][0] == board[0][1]
           && board[0][1] == board[0][2]
           && board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null;
 }
</code>```

The relevant call in the driver class is:

```<code>do {
        System.out.println("Your turn: ");
        g1.play(s.nextInt(), s.nextInt(), s.next());
        System.out.println(g1.getHz1());
} while (g1.getHz1() == false)
</code>```

The "play" method takes 2 integers and a string value to put in the array, in this case "x".  When I print out the board[0][0], board[0][1] and board[0][2], all contain the string "x", but getHz1 still returns false.

答: "==" is only used for primitive types (ints, booleans, etc.). A string is an object, so using == is checking the object reference (if String 1 is the same object as String 2). When comparing strings, you need to use .equals(), which tests for equal values. </p>

Body:
I keep getting a false boolean value from the following comparison:

public boolean getHz1() {
    return board[0][0] == board[0][1]
           && board[0][1] == board[0][2]
           && board[0][0] != null
           && board[0][1] != null
           && board[0][2] != null;
 }

The relevant call in the driver class is:

do {
        System.out.println("Your turn: ");
        g1.play(s.nextInt(), s.nextInt(), s.next());
        System.out.println(g1.getHz1());
} while (g1.getHz1() == false)

The "play" method takes 2 integers and a string value to put in the array, in this case "x".  When I print out the board[0][0], board[0][1] and board[0][2], all contain the string "x", but getHz1 still returns false.


问:
Difference between Graph API and GraphQL
Is there a difference between Microsoft Azure Graph API in Cosmos DB and its GraphQL provided by FaceBook?</p>

答:
They are two very different things even though they share the keywords "graph" in them.

CosmosDB Graph API is a query language to manage and query "CosmosDB graph database". Graph database unlike traditional databases, store information in the form of a graph (i.e., vertices and edges).

GraphQL on the other hand is a query language for a user API. Let's say that you have a build stack (the underlying platform could be anything) that has a REST endpoint. However the rest APIs typically are simple and do not let you specify complex filtering conditions. GraphQL is a way (or replacement to tradition REST API) by which the developer of the stack can allow clients to avail these complex functionalities.


问:
How to make subcategory for the items located in vector list in java
I am making a java program which requires making a list which will be added in the vector class using vector.add() method. And then I want to make a subcategory for the list items which is located in vector list. Like this.

1. Drink
    a> Soda
    b> Tea
    c) Cofee
2. Grocery
    a> Item1
    b> Item2
    c) Item3

Drink and Grocery will be added to the vector list. Now how can I manage the subcategory list? Can we use Collection for this? If yes, then how?

**Please provide a useful method to tackle this problem** Thanks

答:
Define a class, for example with name Category, which contains category and list of items which belongs to this category.

```<code>class Category {
    String category;
    List<String> items;
    ...
}
</code>```

Now create list of categories using Vector

```<code>Collection<Category> categories = new Vector<Category>();
</code>```

Sample code:

```<code>import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Vector;

public class Test {

    public static void main(String[] args) {
        // Create a vector of categories
        Collection<Category> categories = new Vector<Category>();
        // Create drinks
        List<String> drinks = Arrays.asList("Soda", "Tea", "Cofee");
        // Add drinks to vector
        categories.add(new Category("Drink", drinks));
        // Create groceries
        List<String> groceries = Arrays.asList("Item1", "Item2", "Item3");
        // Add groceries to vector
        categories.add(new Category("Grocery", groceries));

    }

}

class Category {
    String category;
    List<String> items;
    public Category(String category, List<String> items) {
        if (category == null || items == null) {
            throw new IllegalArgumentException("Category and items cannot be null");
        }
        this.category = category;
        this.items = items;
    }
}
</code>```

Body:
Define a class, for example with name Category, which contains category and list of items which belongs to this category.

class Category {
    String category;
    List<String> items;
    ...
}

Now create list of categories using Vector

Collection<Category> categories = new Vector<Category>();

Sample code:

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Vector;

public class Test {

    public static void main(String[] args) {
        // Create a vector of categories
        Collection<Category> categories = new Vector<Category>();
        // Create drinks
        List<String> drinks = Arrays.asList("Soda", "Tea", "Cofee");
        // Add drinks to vector
        categories.add(new Category("Drink", drinks));
        // Create groceries
        List<String> groceries = Arrays.asList("Item1", "Item2", "Item3");
        // Add groceries to vector
        categories.add(new Category("Grocery", groceries));

    }

}

class Category {
    String category;
    List<String> items;
    public Category(String category, List<String> items) {
        if (category == null || items == null) {
            throw new IllegalArgumentException("Category and items cannot be null");
        }
        this.category = category;
        this.items = items;
    }
}


问:
Detect hardware button press while android device is locked
I'm trying to detect hardware button press, specially power button long press while the device is locked. I have created a BroadcastReceiver that starts when the device is locked & unlocked. but I'm stuck after that...
any solution?

My code sample:

```<code><receiver android:name=".Receivers.UnlockReceiver">
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.intent.action.SCREEN_ON" />
                <action android:name="android.intent.action.SCREEN_OFF" />
            </intent-filter>
        </receiver>
</code>```

Receiver class:

```<code>public class UnlockReceiver extends BroadcastReceiver {

        private String TAG = "UnlockReceiver";

        @Override
        public void onReceive(final Context context, Intent intent) {
            // Now I'm trying to detect power button
            // press & long press while the device is locked
        }

    }
</code>```

答:
```<code> @Override
 protected void onPause() {
 super.onPause();

PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
    boolean isScreenOn = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH)
      {
        if (powerManager != null)
          {
            isScreenOn = powerManager.isInteractive();
           }
    }
  else
       {
        if (powerManager != null)
        {
            isScreenOn = powerManager.isScreenOn();
        }
    }

    if (!isScreenOn) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
        }

        // The screen has been locked

    }
}
</code>```

Body:
I'm trying to detect hardware button press, specially power button long press while the device is locked. I have created a BroadcastReceiver that starts when the device is locked & unlocked. but I'm stuck after that...
any solution?

My code sample:

<receiver android:name=".Receivers.UnlockReceiver">
            <intent-filter>
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.intent.action.SCREEN_ON" />
                <action android:name="android.intent.action.SCREEN_OFF" />
            </intent-filter>
        </receiver>

Receiver class:

public class UnlockReceiver extends BroadcastReceiver {

        private String TAG = "UnlockReceiver";

        @Override
        public void onReceive(final Context context, Intent intent) {
            // Now I'm trying to detect power button
            // press & long press while the device is locked
        }

    }


问:
If else then execute another mysql query
I have a problem: I want to use result of this query in if clause

```<code>SELECT COUNT(*)
FROM user
WHERE userid = 1234 AND password = 1234;
</code>```

The concept is like this in my pseudocode - I don't know how to do it

```<code>if (count = 0) {
    SELECT logintattempt
    INTO @temp
    FROM user
    WHERE userid = 1234

    SELECT (@temp+1) INTO @temp
}

SELECT loginattempt
FROM user
WHERE userid = 1234;

if(loginattempt >= 3) {
     UPDATE user
     SET status = 'blocked'
     WHERE userid = 1234;
}
</code>```

If count 0 then login attempt will increase and when the login attempts is more than 3, it will be execute update status into blocked

答:
From my understanding, you want to know how to use the result from

```<code>SELECT COUNT(*) FROM user WHERE userid=1234 AND password=1234;
</code>```

into the if statement. Here's what you do:

```<code>SET @count:= (SELECT COUNT(*) FROM user WHERE userid=1234 AND password=1234);
SELECT @count;
</code>```

Does this help?

Body:
I have a problem: I want to use result of this query in if clause

SELECT COUNT(*)
FROM user
WHERE userid = 1234 AND password = 1234;

The concept is like this in my pseudocode - I don't know how to do it

if (count = 0) {
    SELECT logintattempt
    INTO @temp
    FROM user
    WHERE userid = 1234

    SELECT (@temp+1) INTO @temp
}

SELECT loginattempt
FROM user
WHERE userid = 1234;

if(loginattempt >= 3) {
     UPDATE user
     SET status = 'blocked'
     WHERE userid = 1234;
}

If count 0 then login attempt will increase and when the login attempts is more than 3, it will be execute update status into blocked

Body:
From my understanding, you want to know how to use the result from

SELECT COUNT(*) FROM user WHERE userid=1234 AND password=1234;

into the if statement. Here's what you do:

SET @count:= (SELECT COUNT(*) FROM user WHERE userid=1234 AND password=1234);
SELECT @count;

Does this help?