问:
Differences in string compare methods in C#
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?  </p>

```<code>string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code>```

<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>

答:
Not that performance usually matters with 99% of the times you need to do this, but if you had to do this in a loop several million times I would highly suggest that you use .Equals or == because as soon as it finds a character that doesn't match it throws the whole thing out as false, but if you use the CompareTo it will have to figure out which character is less than the other, leading to slightly worse performance time.

If your app will be running in different countries, I'd recommend that you take a look at the CultureInfo implications and possibly use .Equals. Since I only really write apps for the US (and don't care if it doesn't work properly by someone), I always just use ==.

OwnerDisplayName: Craig

Body:
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?

string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}

(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)

OwnerDisplayName: Jon von Gillern


来源: stackexchange

问:
Java - "no buffer space available" socket error cause?
I'm writing a networking program in Java. I use ServerSocket and Socket objects to send and receive messages using TCP. My program runs fine if run for a short time however if I run it for a longer time, I get the following error:

```<code>java.net.SocketException: No buffer space available (maximum connections reached?): connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
</code>```

I thought it might be because I do not close all sockets but I've changed my code: I have one class that I create when I want a new socket and have added a finalize method to close it. I also have a finalize method to close the ServerSocket so I don't know what the problem is.

Also after I get the error, if I run the program again straight away, it runs into the problem quicker than before. Then if I wait for a while and run it, it goes back to like the original time.

I really cannot work out the problem and I've been trying to figure it out for ages. Does anyone have any idea what the problem is?

Thanks in advance!

UPDATE:

So I've figured out where the error is coming from and it's really weird. I have the following code which is causing the problem:

```<code>try {
        sock = new Socket(InetAddress.getByName(ipaddr), port);
        sock.close();

        // os = sock.getOutputStream();
        // byte[] arr = s.getBytes();
        // os.write(arr);
        // os.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            sock.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

As you can see, the code should open a socket and write to it. However even when all the functional code is commented out as above, so the socket is just opened then immediately closed, I still get the "no buffer space" error.

I really cannot work out why this is. The program is multi threaded and each thread creates objects periodically with the above method in and call it. When the lines to create and close the socket are removed, I no longer get the error but when they are there, even though the socket is opened then closed immediately, I get the error.

Does anyone have any clue why this is happening?

Many thanks.

答:
Don't use finalize to close resources.  It won't work reliably.

(There is a chance that the resource objects won't be finalized soon enough and you will run out of resources.  You have no control of when the finalizers get run, and it is possible that they will never get run.)

What you should be doing is something like this:

```<code>    Resource resource = // allocate resource
    try {
        // Use the resource ...
    }
    catch (SomeException ...) {
        // Deal with errors from using the resource
    }
    finally {
        try {
            resource.close()}
        }
        catch (SomeException ...) {
            // Deal with errors from closing the resource
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a networking program in Java. I use ServerSocket and Socket objects to send and receive messages using TCP. My program runs fine if run for a short time however if I run it for a longer time, I get the following error:

java.net.SocketException: No buffer space available (maximum connections reached?): connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)

I thought it might be because I do not close all sockets but I've changed my code: I have one class that I create when I want a new socket and have added a finalize method to close it. I also have a finalize method to close the ServerSocket so I don't know what the problem is.

Also after I get the error, if I run the program again straight away, it runs into the problem quicker than before. Then if I wait for a while and run it, it goes back to like the original time.

I really cannot work out the problem and I've been trying to figure it out for ages. Does anyone have any idea what the problem is?

Thanks in advance!

UPDATE:

So I've figured out where the error is coming from and it's really weird. I have the following code which is causing the problem:

try {
        sock = new Socket(InetAddress.getByName(ipaddr), port);
        sock.close();

        // os = sock.getOutputStream();
        // byte[] arr = s.getBytes();
        // os.write(arr);
        // os.close();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            sock.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

As you can see, the code should open a socket and write to it. However even when all the functional code is commented out as above, so the socket is just opened then immediately closed, I still get the "no buffer space" error.

I really cannot work out why this is. The program is multi threaded and each thread creates objects periodically with the above method in and call it. When the lines to create and close the socket are removed, I no longer get the error but when they are there, even though the socket is opened then closed immediately, I get the error.

Does anyone have any clue why this is happening?

Many thanks.

Body:
Don't use finalize to close resources.  It won't work reliably.

(There is a chance that the resource objects won't be finalized soon enough and you will run out of resources.  You have no control of when the finalizers get run, and it is possible that they will never get run.)

What you should be doing is something like this:

    Resource resource = // allocate resource
    try {
        // Use the resource ...
    }
    catch (SomeException ...) {
        // Deal with errors from using the resource
    }
    finally {
        try {
            resource.close()}
        }
        catch (SomeException ...) {
            // Deal with errors from closing the resource
        }
    }


问:
Parallelizing loading data from MongoDB into python
All documents in my collection in MongoDB have the same fields. My goal is to load them into Python into pandas.DataFrame or dask.DataFrame.

I'd like to speedup the loading procedure by parallelizing it. My plan is to spawn several processes or threads. Each process would load a chunk of a collection, then these chunks would be merged together.

How do I do it correctly with MongoDB?

I have tried similar approach with PostgreSQL. My initial idea was to use SKIP and LIMIT in SQL queries. It has failed, since each cursor, opened for each particular query, started reading data table from the beginning and just skipped specified amount of rows. So I had to create additional column, containing record numbers, and specify ranges of these numbers in queries.

On the contrary, MongoDB assigns unique ObjectID to each document. However, I've found that it is impossible to subtract one ObjectID from another, they can be only compared with ordering operations: less, greater and equal.

Also, pymongo returns the cursor object, that supports indexing operation and has some methods, seeming useful for my task, like count, limit.

MongoDB connector for Spark accomplishes this task somehow. Unfortunately, I'm not familiar with Scala, therefore, it's hard for me to find out how they do it.

So, what is the correct way for parallel loading data from Mongo into python?

up to now, I've come to the following solution:

```<code>import pandas as pd
import dask.dataframe as dd
from dask.delayed import delayed

# import other modules.

collection = get_mongo_collection()
cursor = collection.find({ })

def process_document(in_doc):
    out_doc = # process doc keys and values
    return pd.DataFrame(out_doc)

df = dd.from_delayed( (delayed(process_document)(d) for d in cursor) )
</code>```

However, it looks like dask.dataframe.from_delayed internally creates a list from passed generator, effectively loading all collection in a single thread.

Update. I've found in docs, that skip method of pymongo.Cursor starts from beginning of a collection too, as PostgreSQL. The same page suggests using pagination logic in the application. Solutions, that I've found so far, use sorted _id for this. However, they also store last seen _id, that implies that they also work in a single thread.

Update2. I've found the code of the partitioner in the official MongoDb Spark connector: https://github.com/mongodb/mongo-spark/blob/7c76ed1821f70ef2259f8822d812b9c53b6f2b98/src/main/scala/com/mongodb/spark/rdd/partitioner/MongoPaginationPartitioner.scala#L32

Looks like, initially this partitioner reads the key field from all documents in the collection and calculates ranges of values.

Update3: My incomplete solution.

Doesn't work, gets the exception from pymongo, because dask seems to incorrectly treat the Collection object:

```<code>/home/user/.conda/envs/MBA/lib/python2.7/site-packages/dask/delayed.pyc in <genexpr>(***failed resolving arguments***)
     81         return expr, {}
     82     if isinstance(expr, (Iterator, list, tuple, set)):
---> 83         args, dasks = unzip((to_task_dask(e) for e in expr), 2)
     84         args = list(args)
     85         dsk = sharedict.merge(*dasks)

/home/user/.conda/envs/MBA/lib/python2.7/site-packages/pymongo/collection.pyc in __next__(self)
   2342
   2343     def __next__(self):
-> 2344         raise TypeError("'Collection' object is not iterable")
   2345
   2346     next = __next__

TypeError: 'Collection' object is not iterable
</code>```

What raises the exception:

```<code>def process_document(in_doc, other_arg):
    # custom processing of incoming records
    return out_doc

def compute_id_ranges(collection, query, partition_size=50):
    cur = collection.find(query, {'_id': 1}).sort('_id', pymongo.ASCENDING)
    id_ranges = [cur[0]['_id']]
    count = 1
    for r in cur:
        count += 1
        if count > partition_size:
            id_ranges.append(r['_id'])
            count = 0
    id_ranges.append(r['_id'])
    return zip(id_ranges[:len(id_ranges)-1], id_ranges[1: ])

def load_chunk(id_pair, collection, query={}, projection=None):
    q = query
    q.update( {"_id": {"$gte": id_pair[0], "$lt": id_pair[1]}} )
    cur = collection.find(q, projection)

    return pd.DataFrame([process_document(d, other_arg) for d in cur])

def parallel_load(*args, **kwargs):
    collection = kwargs['collection']
    query = kwargs.get('query', {})
    projection = kwargs.get('projection', None)

    id_ranges = compute_id_ranges(collection, query)

    dfs = [ delayed(load_chunk)(ir, collection, query, projection) for ir in id_ranges ]
    df = dd.from_delayed(dfs)
    return df

collection = connect_to_mongo_and_return_collection_object(credentials)

# df = parallel_load(collection=collection)

id_ranges = compute_id_ranges(collection)
dedf = delayed(load_chunk)(id_ranges[0], collection)
</code>```

load_chunk perfectly runs when called directly. However, call delayed(load_chunk)( blah-blah-blah ) fails with exception, mentioned above.

答:
"Read the mans, thery're rulez" :)

pymongo.Collection has method parallel_scan that returns a list of cursors.

UPDATE. This function can do the job, if the collection does not change too often, and queries are always the same (my case). One could just store query results in different collections and run parallel scans.

ContentLicense: CC BY-SA 3.0

Body:
All documents in my collection in MongoDB have the same fields. My goal is to load them into Python into pandas.DataFrame or dask.DataFrame.

I'd like to speedup the loading procedure by parallelizing it. My plan is to spawn several processes or threads. Each process would load a chunk of a collection, then these chunks would be merged together.

How do I do it correctly with MongoDB?

I have tried similar approach with PostgreSQL. My initial idea was to use SKIP and LIMIT in SQL queries. It has failed, since each cursor, opened for each particular query, started reading data table from the beginning and just skipped specified amount of rows. So I had to create additional column, containing record numbers, and specify ranges of these numbers in queries.

On the contrary, MongoDB assigns unique ObjectID to each document. However, I've found that it is impossible to subtract one ObjectID from another, they can be only compared with ordering operations: less, greater and equal.

Also, pymongo returns the cursor object, that supports indexing operation and has some methods, seeming useful for my task, like count, limit.

MongoDB connector for Spark accomplishes this task somehow. Unfortunately, I'm not familiar with Scala, therefore, it's hard for me to find out how they do it.

So, what is the correct way for parallel loading data from Mongo into python?

up to now, I've come to the following solution:

import pandas as pd
import dask.dataframe as dd
from dask.delayed import delayed

# import other modules.

collection = get_mongo_collection()
cursor = collection.find({ })

def process_document(in_doc):
    out_doc = # process doc keys and values
    return pd.DataFrame(out_doc)

df = dd.from_delayed( (delayed(process_document)(d) for d in cursor) )

However, it looks like dask.dataframe.from_delayed internally creates a list from passed generator, effectively loading all collection in a single thread.

Update. I've found in docs, that skip method of pymongo.Cursor starts from beginning of a collection too, as PostgreSQL. The same page suggests using pagination logic in the application. Solutions, that I've found so far, use sorted _id for this. However, they also store last seen _id, that implies that they also work in a single thread.

Update2. I've found the code of the partitioner in the official MongoDb Spark connector: https://github.com/mongodb/mongo-spark/blob/7c76ed1821f70ef2259f8822d812b9c53b6f2b98/src/main/scala/com/mongodb/spark/rdd/partitioner/MongoPaginationPartitioner.scala#L32

Looks like, initially this partitioner reads the key field from all documents in the collection and calculates ranges of values.

Update3: My incomplete solution.

Doesn't work, gets the exception from pymongo, because dask seems to incorrectly treat the Collection object:

/home/user/.conda/envs/MBA/lib/python2.7/site-packages/dask/delayed.pyc in <genexpr>(***failed resolving arguments***)
     81         return expr, {}
     82     if isinstance(expr, (Iterator, list, tuple, set)):
---> 83         args, dasks = unzip((to_task_dask(e) for e in expr), 2)
     84         args = list(args)
     85         dsk = sharedict.merge(*dasks)

/home/user/.conda/envs/MBA/lib/python2.7/site-packages/pymongo/collection.pyc in __next__(self)
   2342
   2343     def __next__(self):
-> 2344         raise TypeError("'Collection' object is not iterable")
   2345
   2346     next = __next__

TypeError: 'Collection' object is not iterable

What raises the exception:

def process_document(in_doc, other_arg):
    # custom processing of incoming records
    return out_doc

def compute_id_ranges(collection, query, partition_size=50):
    cur = collection.find(query, {'_id': 1}).sort('_id', pymongo.ASCENDING)
    id_ranges = [cur[0]['_id']]
    count = 1
    for r in cur:
        count += 1
        if count > partition_size:
            id_ranges.append(r['_id'])
            count = 0
    id_ranges.append(r['_id'])
    return zip(id_ranges[:len(id_ranges)-1], id_ranges[1: ])

def load_chunk(id_pair, collection, query={}, projection=None):
    q = query
    q.update( {"_id": {"$gte": id_pair[0], "$lt": id_pair[1]}} )
    cur = collection.find(q, projection)

    return pd.DataFrame([process_document(d, other_arg) for d in cur])

def parallel_load(*args, **kwargs):
    collection = kwargs['collection']
    query = kwargs.get('query', {})
    projection = kwargs.get('projection', None)

    id_ranges = compute_id_ranges(collection, query)

    dfs = [ delayed(load_chunk)(ir, collection, query, projection) for ir in id_ranges ]
    df = dd.from_delayed(dfs)
    return df

collection = connect_to_mongo_and_return_collection_object(credentials)

# df = parallel_load(collection=collection)

id_ranges = compute_id_ranges(collection)
dedf = delayed(load_chunk)(id_ranges[0], collection)

load_chunk perfectly runs when called directly. However, call delayed(load_chunk)( blah-blah-blah ) fails with exception, mentioned above.


问:
Best Practices to Store Only Year In SQL in PHP
I am Saving Student Passing Year Into Database.

I am Little confuse about how do I save YEAR  Into SQL.
I am using Codeigniter Framework.

Here is my HTML Input code:

```<code> <input type="text" name="passing_year" id="passing_year" required />
</code>```

I lookup some suggestion but not get it properly.
So the Problem is:

What should I use in SQL datatype.
Integer or Data

Why?

I have tried to convert the year into date but I get Current Data in that process. Here is the code.

```<code>$sqlDataFormate = date('Y-m-d', strtotime($year));
</code>```

In this code the problem is that, if send any year (2010, 2011, etc) I get 2017-06-05

Is it possible that if i select "2010" from year then I can save it like "2010-01-01" ? by using strtotime.

Here is the picture of my html input datepiker.

答:
You can get year by passing only year parameter to function like this

```<code>$sqlDataFormate = date('Y', strtotime($year));
</code>```

Body:
I am Saving Student Passing Year Into Database.

I am Little confuse about how do I save YEAR  Into SQL.
I am using Codeigniter Framework.

Here is my HTML Input code:

 <input type="text" name="passing_year" id="passing_year" required />

I lookup some suggestion but not get it properly.
So the Problem is:

What should I use in SQL datatype.
Integer or Data

Why?

I have tried to convert the year into date but I get Current Data in that process. Here is the code.

$sqlDataFormate = date('Y-m-d', strtotime($year));

In this code the problem is that, if send any year (2010, 2011, etc) I get 2017-06-05

Is it possible that if i select "2010" from year then I can save it like "2010-01-01" ? by using strtotime.

Here is the picture of my html input datepiker.

Body:
You can get year by passing only year parameter to function like this

$sqlDataFormate = date('Y', strtotime($year));


问:
java.lang.ClassNotFoundException in Maven project, while trying to load listener from web.xml
I have converted existing web project into Maven, technologies used are : Struts 2, Hibernate. A listener extends  javax.servlet.ServletContextListener, which has a entry in web.xml as follows:

```<code><listener>
    <listener-class>com.tcs.weserv.util.Listener</listener-class>
  </listener>
</code>```

Maven project build successfully, but when I try to start server, it throw an exception:

```<code>java.lang.ClassNotFoundException: package.util.Listener
</code>```

All dependencies are defined properly in pom.xml, listener is available at given location, still it throws ClassNotFoundException.

答:
Thanks all for your valuable comments. It helped to debug the problem. The actual problem is, Maven Project structure was wrong. When I created a Maven project by selecting archtype as webapp, the project structure contains only src/main/resources.

Since I am new to Maven, I thought this is actual project structure, and I copied all resources as well as java files into this folder. As a result, It was able to build the project without any error, but while deploying it on server, It is showing ClassNotFoundException.

ContentLicense: CC BY-SA 4.0

Body:
I have converted existing web project into Maven, technologies used are : Struts 2, Hibernate. A listener extends  javax.servlet.ServletContextListener, which has a entry in web.xml as follows:

<listener>
    <listener-class>com.tcs.weserv.util.Listener</listener-class>
  </listener>

Maven project build successfully, but when I try to start server, it throw an exception:

java.lang.ClassNotFoundException: package.util.Listener

All dependencies are defined properly in pom.xml, listener is available at given location, still it throws ClassNotFoundException.


问:
Running maven job inside another maven job
I have 2 Java projects where project2 depends on project1's jar. Bot are Maven projects. At the moment this is what I do to create a jar from project2:

```<code>c:\eclipse\workspace\project1> mvn install
c:\eclipse\workspace\project2> mvn package
</code>```

Could I somehow "include" the mvn install command inside projects2's pom.xml so that only the last command would be enough to create the jar?

答:
You have described a basic use case of Maven Reactor (i.e. Maven's fancy name for multi-project/module build).
In this respect, you'd have your two projects alongside a parent pom (which would be the predecessor of both project1 and project2).
Within a Maven multi-module build, modules are allowed to depend one on another; so in your case you'd specify project1 as a dependency of project2's just like you do with any other dependency. Then, when you run package (on the parent pom) Maven will see the dependency, build project1 first and then use the built jar for project2.</p>

Body:
I have 2 Java projects where project2 depends on project1's jar. Bot are Maven projects. At the moment this is what I do to create a jar from project2:

c:\eclipse\workspace\project1> mvn install
c:\eclipse\workspace\project2> mvn package

Could I somehow "include" the mvn install command inside projects2's pom.xml so that only the last command would be enough to create the jar?


问:
JQuery Event Bubbling Issue
JSFiddle: https://jsfiddle.net/3v2qav58/

having an issue with a dropdown menu.

The issue my sub category list item has a ul/dropdown inside it, so I've grabbed the list item and used '.find()' to get the dropdown and then try slideToggle it.

The issue is I have 3 list items and when I click on the other ones they also open and close the other list items for e.g There is only the dropdown on the first list item but if you click the 2nd/3rd they also toggle.

I think it's to do with event bubbling because I thought '.find()' only traversed down and not up?

Could some explain why this is happening who the event bubbling occurs and how to resolve it?

Cheers

HTML

```<code><ul class="dropdown">
  <li class="dropdown-item">
    <a href="">Cat 1</a>
    <ul class="sub-dropdown">
      <li class="dropdown-sub-item">
        <a href="#">Sub Cat 1</a>
        <ul class="sub-dropdown-child">
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 1</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 2</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 3</a></li>
        </ul>
      </li>
</code>```

CSS

```<code>.sub-dropdown,
.sub-dropdown-child {
  display: none;
}
</code>```

JQuery

```<code>var dropdownItem = $(".dropdown-item");
var dropdownSubItem = $(".sub-dropdown");
var DropdownSubItem = $(".dropdown-sub-item");
var subDropdownChild = $(".sub-dropdown-child");

// Open
dropdownItem.on("click", function(e) {
  e.preventDefault();
  dropdownSubItem.show();

  // Open sub cat
  dropdownSubItem.on("click", function(e) {
    e.stopPropagation();
    $(this).find(subDropdownChild).slideToggle();
  });
});
</code>```

答:
Change your JS to the following:

$(".dropdown-item").on("click", function(e) {
  e.preventDefault();
  $(this).find(".sub-dropdown").toggle();
});
$(".sub-dropdown").on("click", function(e) {
  e.stopPropagation();
  $(this).find(".sub-dropdown-child").slideToggle();
});
$(".sub-dropdown-child").on("click", function(e) {
  e.stopPropagation();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sub-dropdown,
.sub-dropdown-child {
  display: none;
}</code>```

    Cat 1

        Sub Cat 1

Sub Cat Child 1

Sub Cat Child 2

Sub Cat Child 3

    Cat 2

        Sub Cat 2

Sub Cat Child 1

Sub Cat Child 2

Sub Cat Child 3

```
</div>
</div>
</p>

<p>The problem with your code is that you where showing ALL sub-items, and not just the sub-items of the clicked one:</p>

```dropdownSubItem.show(); //This shows all sub-items
```

<p>I replaced that with this:</p>

```$(this).find(".sub-dropdown").toggle();
```

<p>Also, you did the event-binding multiple times for sub-items when clicking on a root-item:</p>

```dropdownItem.on("click", function(e) {
  ...
  dropdownSubItem.on("click", function(e) {
    ...
  });
  ...
});
```

Which results in event-binding on each click.

Title: JQuery Event Bubbling Issue

Body:
JSFiddle: https://jsfiddle.net/3v2qav58/

having an issue with a dropdown menu.

The issue my sub category list item has a ul/dropdown inside it, so I've grabbed the list item and used '.find()' to get the dropdown and then try slideToggle it.

The issue is I have 3 list items and when I click on the other ones they also open and close the other list items for e.g There is only the dropdown on the first list item but if you click the 2nd/3rd they also toggle.

I think it's to do with event bubbling because I thought '.find()' only traversed down and not up?

Could some explain why this is happening who the event bubbling occurs and how to resolve it?

Cheers

HTML

    Cat 1

        Sub Cat 1

Sub Cat Child 1

Sub Cat Child 2

Sub Cat Child 3

CSS

.sub-dropdown,
.sub-dropdown-child {
  display: none;
}

JQuery

var dropdownItem = $(".dropdown-item");
var dropdownSubItem = $(".sub-dropdown");
var DropdownSubItem = $(".dropdown-sub-item");
var subDropdownChild = $(".sub-dropdown-child");

// Open
dropdownItem.on("click", function(e) {
  e.preventDefault();
  dropdownSubItem.show();

  // Open sub cat
  dropdownSubItem.on("click", function(e) {
    e.stopPropagation();
    $(this).find(subDropdownChild).slideToggle();
  });
});

Body:
Change your JS to the following:

$(".dropdown-item").on("click", function(e) {
  e.preventDefault();
  $(this).find(".sub-dropdown").toggle();
});
$(".sub-dropdown").on("click", function(e) {
  e.stopPropagation();
  $(this).find(".sub-dropdown-child").slideToggle();
});
$(".sub-dropdown-child").on("click", function(e) {
  e.stopPropagation();
});

.sub-dropdown,
.sub-dropdown-child {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown">
  <li class="dropdown-item">
    <a href="">Cat 1</a>
    <ul class="sub-dropdown">
      <li class="dropdown-sub-item">
        <a href="#">Sub Cat 1</a>
        <ul class="sub-dropdown-child">
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 1</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 2</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 3</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li class="dropdown-item">
    <a href="">Cat 2</a>
    <ul class="sub-dropdown">
      <li class="dropdown-sub-item">
        <a href="#">Sub Cat 2</a>
        <ul class="sub-dropdown-child">
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 1</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 2</a></li>
          <li class="sub-dropdown-child-item"><a href="#">Sub Cat Child 3</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

The problem with your code is that you where showing ALL sub-items, and not just the sub-items of the clicked one:

dropdownSubItem.show(); //This shows all sub-items

I replaced that with this:

$(this).find(".sub-dropdown").toggle();

Also, you did the event-binding multiple times for sub-items when clicking on a root-item:

dropdownItem.on("click", function(e) {
  ...
  dropdownSubItem.on("click", function(e) {
    ...
  });
  ...
});

Which results in event-binding on each click.


问:
Running R from Mac OSX terminal
I've searched the web, and I'm still unclear on how to run R from the Mac terminal.  I have Rstudio and the standalone R app installed.  I thought I could just type "R" from the command line as I do with "python", but that doesn't work.  Is it necessary to edit the PATH in my bash profile?  If so, how do I give the correct location of R?

Thanks for any help

Edits after receiving comments

So, I'm running Sierra, and when I type "r" or "R" at the terminal, I get "-bash: R: command not found."  If I type, "which R" in the terminal I do not get any output.

Here is the output from "echo $PATH": /usr/local/heroku/bin:/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Users/samuelcolon/anaconda/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/Users/samuelcolon/.rvm/gems/ruby-2.1.0/bin:/Users/samuelcolon/.rvm/gems/ruby-2.1.0@global/bin:/Users/samuelcolon/.rvm/rubies/ruby-2.1.0/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/samuelcolon/.rvm/bin:/Users/samuelcolon/.rvm/bin

As for the installation, I believe I downloaded it directly from cran.r-project.org a while ago.  I can locate the GUI in my applications and open it--
I have version 3.13.  Is it possible, I only have R.app installed but not R?  Perhaps that's the reason I'm getting the 'command not found' when typing "R" into the terminal?

Generally, I've been working in RStudio, but I'd still like to access R from the terminal and also to find where things are located.  I'm fine with removing and re-installing R if it's easiest to start from square one.  I hope the extra detail helps, and I appreciate the responses.

答:
An answer for those not that familiar with Terminal and Bash.

I have done a fresh update install of R from the R.org cran site as part of seeking an answer to your question.

I found this latest install version 3.4.0 installs R for access in Terminal, and also installs R.app as part of the package.

To my understanding, reading support docs, if you have an older version of R it will update that. However it will not update an installation of R installed by the anaconda package.

Where are the R files stored?

I can only assume that with a fresh install of the latest R, R will work for you in Terminal.

To learn where the R files are that are being accessed - in Terminal after starting R, and in R.app, type:

>R.home()

In my case as example:

In R.app - the R version 3.4.0 is accessed in the top directory (not my user folder):

```<code>R.home()
[1] "/Library/Frameworks/R.framework/Resources"
</code>```

In Terminal - the R version 3.3.2 is accessed in the Anaconda package, again in the top level directory.

```<code>R.home()
[1] "/anaconda/lib/R"
</code>```

So I have two different versions of R, and Terminal accesses a different version to R.app.

How can I ensure I access the same version in Terminal as I do in the R.app?

For someone familiar with bash, and how the whole bash command system works I am sure there is a well constructed command. All the same here are some novice solutions.

-

• First Solution:

I could update the anaconda version, however, I would prefer not to as as other elements of the anaconda package my depend on this older version of R. For those not yet familiar with Terminal and bash, not such a novice solution.

-

• Second Solution:

This solution came from mko.  It provides a single use solution.  From the result above, and checking the directory structure a little further to find this R file.

Finding the significant R file enables me to edit an extension of the above path shown in the R.app. So add /bin/R to enter

```<code>/Library/Frameworks/R.framework/Resources/bin/R
</code>```

Entering and pressing return will start R from this version.

Alternatively, one can find this file and icon in the GUI Finder, lead by the above result, and just double click on it, and it will open Terminal and a session with R running for you. Easy!

One could also make an alias of it and put it on your desktop for easy future starts.

-

• Third Solution:

My last solution I think may be best, adding to mko's solution. Make an alias.

Being in my home directory in Terminal I open .bash_profile using the nano text editor. (If you do not already know how to do this, then best not use this solution.)

I then add the line in this env file.

```<code>alias Rv340='/Library/Frameworks/R.framework/Resources/bin/R'
</code>```

I then save the changes and exit this terminal session.  I then open a new Terminal window. (This is so the changes to the env above are incorporated in the new terminal session).

Then when I enter the alias:

```<code>Rv340
</code>```

The version of R I want opens.

You can choose a different alias name to "Rv340".

-

• Fourth Solution:

A second more permanent solution for opening the same version of R in Terminal is as follows.

Copy the path as showing in R.app in response to the R.home() command above, and add that path to PATH in your .bash_profile. (If you do not know already how to do this, then ignore this solution.) Do so as follows.

```<code>export PATH="/Library/Frameworks/R.framework/Resources:$PATH"
</code>```

To my understanding, this ensures that bash looks here for R (and anything else), then moves on to the other paths in PATH. Since this adds this path to the beginning of $PATH, an env variable, bash looks here first where it finds the newer version first, and stops looking.

When it comes to understanding PATH in the env set up in .bash_profile the following two links were helpful.

About PATH.

How to correctly add a path to PATH.

This solution may muck with anaconda's invocation of R. I have yet to check this.

Title: Running R from Mac OSX terminal

Body:
An answer for those not that familiar with Terminal and Bash.

I have done a fresh update install of R from the R.org cran site as part of seeking an answer to your question.

I found this latest install version 3.4.0 installs R for access in Terminal, and also installs R.app as part of the package.

To my understanding, reading support docs, if you have an older version of R it will update that. However it will not update an installation of R installed by the anaconda package.

Where are the R files stored?

I can only assume that with a fresh install of the latest R, R will work for you in Terminal.

To learn where the R files are that are being accessed - in Terminal after starting R, and in R.app, type:

>R.home()

In my case as example:

In R.app - the R version 3.4.0 is accessed in the top directory (not my user folder):

R.home()
[1] "/Library/Frameworks/R.framework/Resources"

In Terminal - the R version 3.3.2 is accessed in the Anaconda package, again in the top level directory.

R.home()
[1] "/anaconda/lib/R"

So I have two different versions of R, and Terminal accesses a different version to R.app.

How can I ensure I access the same version in Terminal as I do in the R.app?

For someone familiar with bash, and how the whole bash command system works I am sure there is a well constructed command. All the same here are some novice solutions.

-

• First Solution:

I could update the anaconda version, however, I would prefer not to as as other elements of the anaconda package my depend on this older version of R. For those not yet familiar with Terminal and bash, not such a novice solution.

-

• Second Solution:

This solution came from mko.  It provides a single use solution.  From the result above, and checking the directory structure a little further to find this R file.

Finding the significant R file enables me to edit an extension of the above path shown in the R.app. So add /bin/R to enter

/Library/Frameworks/R.framework/Resources/bin/R

Entering and pressing return will start R from this version.

Alternatively, one can find this file and icon in the GUI Finder, lead by the above result, and just double click on it, and it will open Terminal and a session with R running for you. Easy!

One could also make an alias of it and put it on your desktop for easy future starts.

-

• Third Solution:

My last solution I think may be best, adding to mko's solution. Make an alias.

Being in my home directory in Terminal I open .bash_profile using the nano text editor. (If you do not already know how to do this, then best not use this solution.)

I then add the line in this env file.

alias Rv340='/Library/Frameworks/R.framework/Resources/bin/R'

I then save the changes and exit this terminal session.  I then open a new Terminal window. (This is so the changes to the env above are incorporated in the new terminal session).

Then when I enter the alias:

Rv340

The version of R I want opens.

You can choose a different alias name to "Rv340".

-

• Fourth Solution:

A second more permanent solution for opening the same version of R in Terminal is as follows.

Copy the path as showing in R.app in response to the R.home() command above, and add that path to PATH in your .bash_profile. (If you do not know already how to do this, then ignore this solution.) Do so as follows.

export PATH="/Library/Frameworks/R.framework/Resources:$PATH"

To my understanding, this ensures that bash looks here for R (and anything else), then moves on to the other paths in PATH. Since this adds this path to the beginning of $PATH, an env variable, bash looks here first where it finds the newer version first, and stops looking.

When it comes to understanding PATH in the env set up in .bash_profile the following two links were helpful.

About PATH.

How to correctly add a path to PATH.

This solution may muck with anaconda's invocation of R. I have yet to check this.


问:
Make protected inner class public
I have the following class:

```<code>class A
{
protected:
    class InnerA {};
};
</code>```

Now I need to gain access to InnerA class in the tests.
Theoretically I could create a test class derived from A and make some parts of A class public. I could do this with fields of course, but not with inner classes.

Is there a way to see the protected InnerA class from outside of A class hierarchy (all classes derived from A)? I would like to be able to write:

```<code>Test(MyTest, InnerATest)
{
    TestA::InnerA x;
    x.DoSth();
}
</code>```

答:
You can inherit and publicize the class, as a matter of fact.

```<code>class A
{
protected:
    class InnerA {};
};

struct expose : A {
    using A::InnerA;
};

int main() {

    expose::InnerA ia;

    return 0;
}
</code>```

As you would any other protected member of the base. This is standard C++.

Title: Make protected inner class public

Body:
I have the following class:

class A
{
protected:
    class InnerA {};
};

Now I need to gain access to InnerA class in the tests.
Theoretically I could create a test class derived from A and make some parts of A class public. I could do this with fields of course, but not with inner classes.

Is there a way to see the protected InnerA class from outside of A class hierarchy (all classes derived from A)? I would like to be able to write:

Test(MyTest, InnerATest)
{
    TestA::InnerA x;
    x.DoSth();
}

Body:
You can inherit and publicize the class, as a matter of fact.

class A
{
protected:
    class InnerA {};
};

struct expose : A {
    using A::InnerA;
};

int main() {

    expose::InnerA ia;

    return 0;
}

As you would any other protected member of the base. This is standard C++.


问:
How can I allow owner of document in Library to manage permission on that document?
When a user uploads a document, I need them to be able to manage permissions on that particular document, but only have Contributor access to other documents.  Ideas on how to do that?  If there is a patch already out there, that would be nice.

My Ideas

Write a feature that hooks the upload or check-in event, then gives Created By user full control.

答: I support your idea you can write a Item event reciever and on itemadded event make the creator of the document as the owner of the document you might have to use spelevated privalages to provide him the same permissions</p>


问:
Checking if directory in HDFS is empty or not
Is there any command in HDFS to check whether a directory is empty or not</p>

答:
```<code>isEmpty=$(hdfs dfs -count /some/path | awk '{print $2}')
if [[ $isEmpty -eq 0 ]];then
    echo "Given Path is empty"
    #Do some operation
else
    echo "Given Path is not empty"
    #Do some operation
fi
</code>```


问:
Why is there no "declared but never used" warning for user-defined classes?
In C#, when you declare but don't use a built-in class or struct you get a "declared but never used" warning, even if the variable is assigned to, such as in this code:

```<code>string myStr;
myStr = "foo";
return;
</code>```

However you don't get the same warning for a user-defined class or struct:

```<code>Bar myBar;
myBar = new Bar();
return;
</code>```

Why is there no warning in the latter case?  If there are side effects to the constructor, you can just say new Bar(); and the only way there would be side effects to the assignment is if the assignment operator is overloaded.  However Visual Studio could check for this and issue the warning if the operator isn't overloaded, yet it doesn't.  Is there a technical reason why it doesn't do this?

答:
Resharper will show the issue - see Value assigned is not used in any execution path - C# .

Code Analysis will also show the issue - https://msdn.microsoft.com/library/ms182278.aspx .

As to why it doesn't show it to you now (without Code Analysis or Resharper), see https://stackoverflow.com/a/10629031/34092 and https://github.com/dotnet/roslyn/issues/15695 (basically it is 'by design').

Body:
In C#, when you declare but don't use a built-in class or struct you get a "declared but never used" warning, even if the variable is assigned to, such as in this code:

string myStr;
myStr = "foo";
return;

However you don't get the same warning for a user-defined class or struct:

Bar myBar;
myBar = new Bar();
return;

Why is there no warning in the latter case?  If there are side effects to the constructor, you can just say new Bar(); and the only way there would be side effects to the assignment is if the assignment operator is overloaded.  However Visual Studio could check for this and issue the warning if the operator isn't overloaded, yet it doesn't.  Is there a technical reason why it doesn't do this?


问:
Inserting a list to mysql
Hai, there, i got this huge list 5k in notepad delimited with new line, i want to insert this to a mysql table is there a way to do that, like a single query or like a antomated way to generate INSERT into bla bla bla..for all of them?</p>

答:
Check the following link on how to import data into MySQL from a flat file:
http://dev.mysql.com/doc/refman/4.1/en/mysqlimport.html

There are also some fancy applications which can help you do this like SQLYog

Title: Inserting a list to mysql


问:
"Cannot find build.xml" error building Android SDK sample
The log is:

BUILD FAILED

/Users/xxx/sample/build.xml:114: Cannot find /Users/xxx/Library/Android/Library/Android/sdk/tools/ant/build.xml imported from /Users/xxx/sample/build.xml

I can confirm that sdkdir is right.

I found there is not an ant directory in /Users/xxx/Library/Android/Library/Android/sdk/tools/.

I found someone saying it is automatically generated. How can I make this build.xml in tools/ant? I use a Mac.

答:
You have to install an old Android Sdk version. The latest ones doesn't have tools\ant folder.

You can download older version here. Download archive and replace tools folder of your sdk.


问:
Is this possible to make a JS request with limited bandwidth?
I would like to use a JS to simulate a slow connection vs fast connection to client, is this possible to limited the AJAX call bandwidth in JS? thanks. </p>

答:
...is this possible to limited the AJAX call bandwidth in JS?

No. But as deceze said, you can use your browser's dev tools to emulate a slow connection.


问:
R Colorize departments of a france map according to the values of a vector
Hi how can i do a map like that with R?

The code that gives this map but i dont have the data :

```<code> library(RColorBrewer)
 library(classInt)
 library(maptools)
 plotvar <- fecondite$fecond1524
 nclr <- 4
 plotclr <- brewer.pal(nclr,"PuOr")
 plotclr <- plotclr[nclr:1] # r´eordonne les couleurs
 class <- classIntervals(plotvar, nclr, style="equal")
 colcode <- findColours(class, plotclr)
 plot(departements,col=colcode)
 locator(n=1) #sert `a trouver les coordonn´ees
 du point o`u vous souhaitez placer la l´egende
 legend(166963,6561753,legend=names(attr(colcode,"table")),
 fill=attr(colcode, "palette"), cex=0.6, bty="n")
</code>```

In fact i want to know : for example with a vector that contains numbers from 1 to 1000 that are relate to the departements how to assign differents color for each intervals [1 , 100] , [100, 500] , [500 , 1000 ] ?

答:
Is that what you're looking for?

```<code>library(raster)

fr <- getData(country='France',level=2)
#plot(fr)

# random terrain colors
fr$col <- terrain.colors(256)[floor(runif(length(fr),0,255))]

# less random
#fr$col <- terrain.colors(length(fr))

plot(fr,col=fr$col)
</code>```

Edit:

You can access the Department names under fr$NAME_2 and then assign your colors accordingly:

```<code>color_df <- data.frame(Dep=fr$NAME_2,color=sample(colors(distinct=T),length(fr),replace = F))

fr$col <- color_df$color

plot(fr,col=fr$col)

print(color_df)
</code>```

This example is a bit silly, since it's again random colors. But you could assign a gradient or any other color value you want to each Department.

Edit 2: Highlight single Department

```<code>library(raster)

fr <- getData(country='France',level=2)

fr$col[fr$NAME_2 == 'Hautes-Alpes'] <- 'red'

plot(fr,col=fr$col)
</code>```

Edit 3: Plot by fake fertility groups

```<code>library(raster)

fr <- getData(country='France',level=2)

# fertility classes
classes <- c('0-1.4','1.4-2.4','2.5-3')

#fake data
fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

# assign groups
fr$fertgroups <- round(fr$fertility)

# assign corresponding colors (red = low, yellow = mid, green = high)
fr$cols <- c('red','yellow','green')[fr$fertgroups]

#plot
plot(fr,col=fr$cols)
</code>```

Or with 4 classes:

```<code>library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)
</code>```

Body:
Hi how can i do a map like that with R?

The code that gives this map but i dont have the data :

 library(RColorBrewer)
 library(classInt)
 library(maptools)
 plotvar <- fecondite$fecond1524
 nclr <- 4
 plotclr <- brewer.pal(nclr,"PuOr")
 plotclr <- plotclr[nclr:1] # r´eordonne les couleurs
 class <- classIntervals(plotvar, nclr, style="equal")
 colcode <- findColours(class, plotclr)
 plot(departements,col=colcode)
 locator(n=1) #sert `a trouver les coordonn´ees
 du point o`u vous souhaitez placer la l´egende
 legend(166963,6561753,legend=names(attr(colcode,"table")),
 fill=attr(colcode, "palette"), cex=0.6, bty="n")

In fact i want to know : for example with a vector that contains numbers from 1 to 1000 that are relate to the departements how to assign differents color for each intervals [1 , 100] , [100, 500] , [500 , 1000 ] ?

Body:
Is that what you're looking for?

library(raster)

fr <- getData(country='France',level=2)
#plot(fr)

# random terrain colors
fr$col <- terrain.colors(256)[floor(runif(length(fr),0,255))]

# less random
#fr$col <- terrain.colors(length(fr))

plot(fr,col=fr$col)

Edit:

You can access the Department names under fr$NAME_2 and then assign your colors accordingly:

color_df <- data.frame(Dep=fr$NAME_2,color=sample(colors(distinct=T),length(fr),replace = F))

fr$col <- color_df$color

plot(fr,col=fr$col)

print(color_df)

This example is a bit silly, since it's again random colors. But you could assign a gradient or any other color value you want to each Department.

Edit 2: Highlight single Department

library(raster)

fr <- getData(country='France',level=2)

fr$col[fr$NAME_2 == 'Hautes-Alpes'] <- 'red'

plot(fr,col=fr$col)

Edit 3: Plot by fake fertility groups

library(raster)

fr <- getData(country='France',level=2)

# fertility classes
classes <- c('0-1.4','1.4-2.4','2.5-3')

#fake data
fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

# assign groups
fr$fertgroups <- round(fr$fertility)

# assign corresponding colors (red = low, yellow = mid, green = high)
fr$cols <- c('red','yellow','green')[fr$fertgroups]

#plot
plot(fr,col=fr$cols)

Or with 4 classes:

library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)


问:
Installing OpenSceneGraph Visual 2015
I have some trouble installing OpenSceneGraph with Visual Studio 2015.

I followed this old tutorial : How to build OpenSceneGraph from source and third party dependencies? and it fails at some point

Here is what I've done so far :

Download OSG 3.4 from this link : https://github.com/openscenegraph/OpenSceneGraph/tree/OpenSceneGraph-3.4.0

Build with CMake (I am not sure here, I set the compiler to Visual Studio 14 2015 Win 64, I haven't try with just Visual Studio 14 2015)

Build ALL_BUILD, after that I had a lot of warning : declaration of 'xxx' hides previous local declaration

And then when I try to build INSTALL it fails after this error :

```<code>Error   MSB3073 The command "setlocal
"C:\Program Files\CMake\bin\cmake.exe" -DBUILD_TYPE=Debug -P cmake_install.cmake
if %errorlevel% neq 0 goto :cmEnd
:cmEnd
endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd
:VCEnd" exited with code 1. INSTALL C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets  133
</code>```

What am I doing wrong ?

Thank you

答: It is asking for admin rights to install. Change the location in CMAKE_INSTALL_PREFIX in the CMake GUI.</p>

Title: Installing OpenSceneGraph Visual 2015

Body:
I have some trouble installing OpenSceneGraph with Visual Studio 2015.

I followed this old tutorial : How to build OpenSceneGraph from source and third party dependencies? and it fails at some point

Here is what I've done so far :

Download OSG 3.4 from this link : https://github.com/openscenegraph/OpenSceneGraph/tree/OpenSceneGraph-3.4.0

Build with CMake (I am not sure here, I set the compiler to Visual Studio 14 2015 Win 64, I haven't try with just Visual Studio 14 2015)

Build ALL_BUILD, after that I had a lot of warning : declaration of 'xxx' hides previous local declaration

And then when I try to build INSTALL it fails after this error :

Error   MSB3073 The command "setlocal
"C:\Program Files\CMake\bin\cmake.exe" -DBUILD_TYPE=Debug -P cmake_install.cmake
if %errorlevel% neq 0 goto :cmEnd
:cmEnd
endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd
:VCEnd" exited with code 1. INSTALL C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets  133

What am I doing wrong ?

Thank you


问:
jQuery - trigger("click") & .click working in console but not working in script
Here is what i try in console:

```<code>$("#element a:eq(0)").click();
</code>```

And it is working perfectly.
Here is what i try in script:

```<code>$(document).ready(function () {
    console.log($("#element a:eq(0)"));
    $("#element a:eq(0)").click();
    $("#element a:eq(0)").trigger("click");
});
</code>```

Then when i refresh the page i can see in the console log that the element is perfectly selected, however there is no click triggered. Do you see any possible reason of why this is not working ?

答:
Your event is perfectly triggerd , it shows nothing because there is no event listener defined on the click event , So if you define the click event you'll see that the event will trigger twise (.click() and .trigger('click')) ,

Also if you want to trigger the redirect to href just add location.href = this.href and the click + redirection will fire .

Please see below snippet :

$(document).ready(function () {
    console.log($("#element a:eq(0)"));

    $("#element a:eq(0)").click(function() {
      alert("#element a:eq(0) clicked");
      //if you want to redirect to href page just incomment the below line
      //location.href = this.href;
    });

    $("#element a:eq(0)").click();

    $("#element a:eq(0)").trigger("click");
});```
<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>
<div id="element" >
  1
  2
  3
</div></code>```

Body:
Here is what i try in console:

$("#element a:eq(0)").click();

And it is working perfectly.
Here is what i try in script:

$(document).ready(function () {
    console.log($("#element a:eq(0)"));
    $("#element a:eq(0)").click();
    $("#element a:eq(0)").trigger("click");
});

Then when i refresh the page i can see in the console log that the element is perfectly selected, however there is no click triggered. Do you see any possible reason of why this is not working ?

Body:
Your event is perfectly triggerd , it shows nothing because there is no event listener defined on the click event , So if you define the click event you'll see that the event will trigger twise (.click() and .trigger('click')) ,

Also if you want to trigger the redirect to href just add location.href = this.href and the click + redirection will fire .

Please see below snippet :

$(document).ready(function () {
    console.log($("#element a:eq(0)"));

    $("#element a:eq(0)").click(function() {
      alert("#element a:eq(0) clicked");
      //if you want to redirect to href page just incomment the below line
      //location.href = this.href;
    });

    $("#element a:eq(0)").click();

    $("#element a:eq(0)").trigger("click");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element" >
  <a href="https://stackoverflow.com/questions/44364289/jquery-triggerclick-click-working-in-console-but-not-working-in-script" >1</a>
  <a href="#2" >2</a>
  <a href="#3" >3</a>
</div>


问:
compare multiple columns in a row in oracle
I have a question from HackerRank :
Sample Input:

```<code>select * from triangle;
A   B   C
20  20  23
20  20  20
20  21  22
13  14  30
</code>```

Sample Output should be :

```<code>Isosceles
Equilateral
Scalene
Not a triangle (as sum of two sides not greater than the third side)
</code>```

I have tried it with Case ,But it becomes messy as I have added lots of conditions there

```<code>select
case
when ((A+B) > C ) or ((B+C)>A) or ((C+A)>B)then
 case when (A=B) and (B=C) then 'equilateral'
 when (A=B ) or (B=C) or (C=A) then 'isosceles'
when (A!=B) and (B!=C) and (C!=A) then 'scalene'

end
else 'not triangle'
end Name from triangle;
</code>```

I am aware of decode ,But decode will not work here ,I guess.
Is there any better way this code can be build instead of using CASE?

答:
```<code>select a, b, c,
       case when a + b < c or a + c < b or b + c < a then 'Not a triangle'
            when a = b and b = c then 'Equilateral'
            when a = b or a = c or b = c then 'Isosceles'
            else 'Scalene'
       end description
  from triangle
</code>```

Output:

```<code>         A          B          C DESCRIPTION
---------- ---------- ---------- --------------
        20         20         23 Isosceles
        20         20         20 Equilateral
        20         21         22 Scalene
        13         14         30 Not a triangle
</code>```

Body:
I have a question from HackerRank :
Sample Input:

select * from triangle;
A   B   C
20  20  23
20  20  20
20  21  22
13  14  30

Sample Output should be :

Isosceles
Equilateral
Scalene
Not a triangle (as sum of two sides not greater than the third side)

I have tried it with Case ,But it becomes messy as I have added lots of conditions there

select
case
when ((A+B) > C ) or ((B+C)>A) or ((C+A)>B)then
 case when (A=B) and (B=C) then 'equilateral'
 when (A=B ) or (B=C) or (C=A) then 'isosceles'
when (A!=B) and (B!=C) and (C!=A) then 'scalene'

end
else 'not triangle'
end Name from triangle;

I am aware of decode ,But decode will not work here ,I guess.
Is there any better way this code can be build instead of using CASE?

Body:
select a, b, c,
       case when a + b < c or a + c < b or b + c < a then 'Not a triangle'
            when a = b and b = c then 'Equilateral'
            when a = b or a = c or b = c then 'Isosceles'
            else 'Scalene'
       end description
  from triangle

Output:

         A          B          C DESCRIPTION
---------- ---------- ---------- --------------
        20         20         23 Isosceles
        20         20         20 Equilateral
        20         21         22 Scalene
        13         14         30 Not a triangle


问:
Google map not showing in android activity?
In my android app I want to have a MainActivity with a google map occupying the entire screen.

My problem is that the google map does not display a map, only the google logo in the bottom left corner:

Here are the relevant parts of the main activity where the map should be displayed:

```<code>public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener {

    private GoogleMap mMap;

    private FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setupLayout();

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
</code>```

Here is the xml for the content of the main activity which holds the google map fragment:

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.purringcat.stray.view.activity.MainActivity"/>
</code>```

Here is the manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.purringcat.stray">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:name=".Stray"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".view.activity.SignUpActivity">
        </activity>
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

    </application>

</manifest>
</code>```

答:
I just checked with google map like yours.

Just compare your code with mine.

MainActivity.java

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
</code>```

}

And Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

Note: You have to create a project in google

click here to visit the google console

Replace your Key value in the google_maps_api

```<code><resources>

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">Your Key</string>
</code>```

Hope this works for you.

PS:  you can generate google map activity from android studio.

Body:
In my android app I want to have a MainActivity with a google map occupying the entire screen.

My problem is that the google map does not display a map, only the google logo in the bottom left corner:

Here are the relevant parts of the main activity where the map should be displayed:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener {

    private GoogleMap mMap;

    private FragmentManager mFragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setupLayout();

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

Here is the xml for the content of the main activity which holds the google map fragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.purringcat.stray.view.activity.MainActivity"/>

Here is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.purringcat.stray">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:name=".Stray"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".view.activity.SignUpActivity">
        </activity>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

    </application>

</manifest>

Body:
I just checked with google map like yours.

Just compare your code with mine.

MainActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

}

And Manifest

<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Note: You have to create a project in google

click here to visit the google console

Replace your Key value in the google_maps_api

<resources>

<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">Your Key</string>

Hope this works for you.

PS:  you can generate google map activity from android studio.


问:
Azure free storage
hello
is there free storage on Azure so i can test my program ?if there how can i access it?

and if there are example n it i hope to guide me

答: Check out the "Introductory Special" http://www.microsoft.com/windowsazure/offers/ It is essentially a free account. You have to go through the whole process and sign up, but once set up you get to use it free as long as you don't go past the limits. When/if you do then you just pay for what you use above the free usage.</p>

Title: Azure free storage


问:
How to extract string from complex string?
My start string is:

```<code>$grp = DL-Test1-Test2-RW"
</code>```

My goal is to have

```<code>$grp = "Test1\Test2"
</code>```

So i need to keep string between first and last "-" character. And replace - by \

UPDATED
I tried this:

```<code>$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion
</code>```

答:
just do it:

```<code>$grp = "DL-test1-test2-RW"
$arraygrp=$grp.Split("-")
$arraygrp[1..($arraygrp.Count -2)] -join "\"
</code>```

or this

```<code>$grp.Substring($grp.IndexOf('-') +1, $grp.LastIndexOf('-')-$grp.IndexOf('-')-1 ).Replace('-', '\')
</code>```

Body:
My start string is:

$grp = DL-Test1-Test2-RW"

My goal is to have

$grp = "Test1\Test2"

So i need to keep string between first and last "-" character. And replace - by \

UPDATED
I tried this:

$grp = "DL-test1-test2-RW"
$Descritpion = $grp.Split("-") #Split - to have an array
$Descritpion = $Descritpion.Split($Descritpion[0]) #Cut first element
$Descritpion = $Descritpion.Split($Descritpion[-1]) # Cut last element
#Here replace ?
Write-Host "Description:"$Descritpion

Body:
just do it:

$grp = "DL-test1-test2-RW"
$arraygrp=$grp.Split("-")
$arraygrp[1..($arraygrp.Count -2)] -join "\"

or this

$grp.Substring($grp.IndexOf('-') +1, $grp.LastIndexOf('-')-$grp.IndexOf('-')-1 ).Replace('-', '\')


问:
How to use 2to3 in Python Shell?
I want to import 2to3.py in the shell, but it keeps saying SyntaxError.

```<code>>>> site.addsitedir('/Python27/Tools/Scripts/')
>>> sys.path
['C:\\Senti\\ltpservice', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\Tools\\Scripts']
>>> import 2to3
SyntaxError: invalid syntax
</code>```

What should I do?

答: To use 2to3, all you to do if you are a windows user is to go to- \python27\2.7\Tools\Scripts> on DOS command prompt. At the prompt, type: "python 2to3.py", "-w", then the directory where the file(s) is/are located. For example: C:\Users\Leeman\python27\2.7\Tools\Scripts>python 2to3.py c:/practice/py2folder/py2file.py. If you add 2to3.py to environment variables' path, the typing may be shorten to simply: python 2to3.py -w c:/practice/py2folder/py2file.py. And in case you want to convert entire folder and sub folders, you type: python 2to3.py -w c:/practice/py2folder/.</p>

Title: How to use 2to3 in Python Shell?

Body:
I want to import 2to3.py in the shell, but it keeps saying SyntaxError.

>>> site.addsitedir('/Python27/Tools/Scripts/')
>>> sys.path
['C:\\Senti\\ltpservice', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\Tools\\Scripts']
>>> import 2to3
SyntaxError: invalid syntax

What should I do?


答:
If you want to expose a non-public part of class A for another class or function, you can try with friend keyword:

```<code>class A
{
protected:
    friend class B;
    friend void f();
    int x;
};

class B
{
public:
    void sayX()
    {
        A a;
        a.x = 12;
        std::cout << a.x << std::endl;
    }
};

void f()
{
    A a;
    a.x = 11;
    std::cout << a.x << std::endl;
}
</code>```

If you want to expose that field to everyone, then I think we're better to put that field to public, or have get/set function for it.

Title: Make protected inner class public

Body:
If you want to expose a non-public part of class A for another class or function, you can try with friend keyword:

class A
{
protected:
    friend class B;
    friend void f();
    int x;
};

class B
{
public:
    void sayX()
    {
        A a;
        a.x = 12;
        std::cout << a.x << std::endl;
    }
};

void f()
{
    A a;
    a.x = 11;
    std::cout << a.x << std::endl;
}

If you want to expose that field to everyone, then I think we're better to put that field to public, or have get/set function for it.


问:
Putting values into a collection for different date ranges
I am writing a PL/SQL procedure which gives the count of a query based on date range values. I want to get the date range dynamically and I have written a cursor for that.

I am using a collection and getting the counts of each month, the problem I am facing is that collection is populated with the count of the last month alone. I want to get the count of all months. Can anyone help?

This is the procedure I have written:

```<code>create or replace
Procedure Sample As
    Cursor C1 Is
        With T As (
            select  to_date('01-JAN-17') start_date,
                Last_Day(Add_Months(Sysdate,-1)) end_date from dual
        )
        Select To_Char(Add_Months(Trunc(Start_Date,'mm'),Level - 1),'DD-MON-YY') St_Date,
            to_char(add_months(trunc(start_date,'mm'),level),'DD-MON-YY') ed_date
        From T
        Connect By Trunc(End_Date,'mm') >= Add_Months(Trunc(Start_Date,'mm'),Level - 1);

    Type T_count_Group_Id Is Table Of number;
    V_count_Group_Id T_count_Group_Id;
Begin
    For I In C1
    Loop
        Select Count(Distinct c1) bulk collect Into V_Count_Group_Id From T1
        Where C2 Between I.St_Date And I.Ed_Date;
    End Loop;
    For J In V_Count_Group_Id.First..V_Count_Group_Id.Last
    Loop
        Dbms_Output.Put_Line(V_Count_Group_Id(J));
    end loop;
END SAMPLE;
</code>```

答:
Your bulk collect query is replacing the contents of the collection each time around the loop; it doesn't append to the collection (if that's what you expected). So after your loop you are only seeing the result of the last bulk collect, which is the latest month from your cursor.

You're also apparently comparing dates as string, which isn't a good idea (unless c2 is stored as a string - which is even worse). And as between is inclusive, you risk including data for the first day of each month in two counts, if the stored time portion is midnight. It's safer to use equality checks for date ranges.

You don't need to use a cursor to get the dates and then individual queries inside that cursor, you can just join your current cursor query to the target table - using an outer join to allow for months with no matching data. Your cursor seems to be looking for all months in the current year, up to the start of the current year, so that could perhaps be simplified to:

```<code>with t as (
  select add_months(trunc(sysdate, 'YYYY'), level - 1) as st_date,
    add_months(trunc(sysdate, 'YYYY'), level) as ed_date
  from dual
  connect by level < extract(month from sysdate)
)
select t.st_date, t.ed_date, count(distinct t1.c1)
from t
left join t1 on t1.c2 >= t.st_date and t1.c2 < t.ed_date
group by t.st_date, t.ed_date
order by t.st_date;
</code>```

You can use that to populate your collection:

```<code>declare
  type t_count_group_id is table of number;
  v_count_group_id t_count_group_id;
begin
  with t as (
    select add_months(trunc(sysdate, 'YYYY'), level - 1) as st_date,
      add_months(trunc(sysdate, 'YYYY'), level) as ed_date
    from dual
    connect by level < extract(month from sysdate)
  )
  select count(distinct t1.c1)
  bulk collect into v_count_group_id
  from t
  left join t1 on t1.c2 >= t.st_date and t1.c2 < t.ed_date
  group by t.st_date, t.ed_date
  order by t.st_date;

  for j in v_count_group_id.first..v_count_group_id.last
  loop
    dbms_output.put_line(v_count_group_id(j));
  end loop;
end;
/
</code>```

although as it only stores/shows the counts, without saying which month they belong to, that might not ultimately be what you really need. As the counts are ordered, you at least know that the first element in the collection represents January, i suppose.

Body:
I am writing a PL/SQL procedure which gives the count of a query based on date range values. I want to get the date range dynamically and I have written a cursor for that.

I am using a collection and getting the counts of each month, the problem I am facing is that collection is populated with the count of the last month alone. I want to get the count of all months. Can anyone help?

This is the procedure I have written:

create or replace
Procedure Sample As
    Cursor C1 Is
        With T As (
            select  to_date('01-JAN-17') start_date,
                Last_Day(Add_Months(Sysdate,-1)) end_date from dual
        )
        Select To_Char(Add_Months(Trunc(Start_Date,'mm'),Level - 1),'DD-MON-YY') St_Date,
            to_char(add_months(trunc(start_date,'mm'),level),'DD-MON-YY') ed_date
        From T
        Connect By Trunc(End_Date,'mm') >= Add_Months(Trunc(Start_Date,'mm'),Level - 1);

    Type T_count_Group_Id Is Table Of number;
    V_count_Group_Id T_count_Group_Id;
Begin
    For I In C1
    Loop
        Select Count(Distinct c1) bulk collect Into V_Count_Group_Id From T1
        Where C2 Between I.St_Date And I.Ed_Date;
    End Loop;
    For J In V_Count_Group_Id.First..V_Count_Group_Id.Last
    Loop
        Dbms_Output.Put_Line(V_Count_Group_Id(J));
    end loop;
END SAMPLE;

Body:
Your bulk collect query is replacing the contents of the collection each time around the loop; it doesn't append to the collection (if that's what you expected). So after your loop you are only seeing the result of the last bulk collect, which is the latest month from your cursor.

You're also apparently comparing dates as string, which isn't a good idea (unless c2 is stored as a string - which is even worse). And as between is inclusive, you risk including data for the first day of each month in two counts, if the stored time portion is midnight. It's safer to use equality checks for date ranges.

You don't need to use a cursor to get the dates and then individual queries inside that cursor, you can just join your current cursor query to the target table - using an outer join to allow for months with no matching data. Your cursor seems to be looking for all months in the current year, up to the start of the current year, so that could perhaps be simplified to:

with t as (
  select add_months(trunc(sysdate, 'YYYY'), level - 1) as st_date,
    add_months(trunc(sysdate, 'YYYY'), level) as ed_date
  from dual
  connect by level < extract(month from sysdate)
)
select t.st_date, t.ed_date, count(distinct t1.c1)
from t
left join t1 on t1.c2 >= t.st_date and t1.c2 < t.ed_date
group by t.st_date, t.ed_date
order by t.st_date;

You can use that to populate your collection:

declare
  type t_count_group_id is table of number;
  v_count_group_id t_count_group_id;
begin
  with t as (
    select add_months(trunc(sysdate, 'YYYY'), level - 1) as st_date,
      add_months(trunc(sysdate, 'YYYY'), level) as ed_date
    from dual
    connect by level < extract(month from sysdate)
  )
  select count(distinct t1.c1)
  bulk collect into v_count_group_id
  from t
  left join t1 on t1.c2 >= t.st_date and t1.c2 < t.ed_date
  group by t.st_date, t.ed_date
  order by t.st_date;

  for j in v_count_group_id.first..v_count_group_id.last
  loop
    dbms_output.put_line(v_count_group_id(j));
  end loop;
end;
/

although as it only stores/shows the counts, without saying which month they belong to, that might not ultimately be what you really need. As the counts are ordered, you at least know that the first element in the collection represents January, i suppose.


问:
Autocomplete extender for multiple textbox using Javascript
I want to apply one autocomplete extender for multiple textbox having same name attribute, For eg.

I just want to apply same autocomplete extender to all having name="txtQtyPkgs". How I can do this?
My html

```<code><table cellspacing="0" cellpadding="0" border="0" style="" id="flex1">
        <tbody>
            <tr id="rowGH03013">
                <td align="Left" class="sorted">
                    <div style="text-align: left; width: 150px;">
                        GH03013</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 150px;">
                        999</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 161px;">
                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19523"></div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 446px;">
                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19523"></div>
                </td>
            </tr>
            <tr class="erow" id="rowGH03011">
                <td align="Left" class="sorted">
                    <div style="text-align: left; width: 150px;">
                        GH03011</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 150px;">
                        999</div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 161px;">
                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19521"></div>
                </td>
                <td align="Left">
                    <div style="text-align: left; width: 446px;">
                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19521"></div>
                </td>
            </tr>
        </tbody>
    </table>
</code>```

my xml data

```<code><table>
  <userid>23</userid>
  <userdispname>GUJARAT PACKERS LTD</userdispname>
  <usercode>GTPL</usercode>
</table>

<table>
  <userid>26</userid>
  <userdispname>Lipton India Limited</userdispname>
  <usercode>Lipton</usercode>
</table>
<table>
  <userid>27</userid>
  <userdispname>TOSH LTD.</userdispname>
  <usercode>ATosh</usercode>
</table>
<table>
  <userid>28</userid>
  <userdispname>SERVICES INDIA PVT. LTD.</userdispname>
  <usercode>TSI</usercode>
</table>
<table>
  <userid>29</userid>
  <userdispname>Parekh Company</userdispname>
  <usercode>Parekh</usercode>
</table>
<table>
  <userid>30</userid>
  <userdispname>SHREE BALAJI CO.</userdispname>
  <usercode>Balaji</usercode>
</table>
<table>
  <userid>31</userid>
  <userdispname>Kesaria Company</userdispname>
  <usercode>Kesaria</usercode>
</table>
</code>```

my javascript

```<code>$(document).ready(function () {
            AuctoCmplBuyer();
            $(".auto").autocomplete({ source: [AuctoCmpData] });
        });
 function AuctoCmplBuyer() {
            $.ajax({
                type: "POST",
                url: "../service/WebService.asmx/XmlData",
                data: "{strData:'BuyerList'}",
                contentType: "application/json; charset=UTF-8",
                dataType: "xml",
                success: function (msg) {
                    $(msg).find('Table').each(function () {
                        if (StrData.length != 0) {
                            StrData = StrData + ",";
                        }
                        StrData = '{"id":"' + $(this).find('UserID').text() + '","label":"' + $(this).find('UserDispName').text() + '","value":"' + $(this).find('UserDispName').text() + '"}';
                    });
                }
            });
            AuctoCmpData = StrData;
        }
</code>```

答:
```<code>    $(document).ready(function () {
            AuctoCmplBuyer();
Auctocomplete functionality to each textbox
            $(".auto").autocomplete({ source: AuctoCmpData });
        });

function AuctoCmplBuyer() {
            $.ajax({
                type: "POST",
                url: "../service/TWWebService.asmx/XmlData",
                data: "{strData:'BuyerList'}",
                contentType: "application/json; charset=UTF-8",
                dataType: "xml",
                success: function (msg) {
                    $(msg).find('Table').each(function () {
                        rowObj = new Object();
                        rowObj.col1 = $(this).find('UserDispName').text() + '-' + $(this).find('UserID').text();
                        AuctoCmpData.push(rowObj);
                    });
                }
            });
        }
</code>```

i am doing in this way ...i am not getting the way you said "harie"

Body:
I want to apply one autocomplete extender for multiple textbox having same name attribute, For eg.

I just want to apply same autocomplete extender to all having name="txtQtyPkgs". How I can do this?
My html

                        GH03013

                        999

                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19523">

                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19523">

                        GH03011

                        999

                        <input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
                            id="QtyPkgs19521">

                        <input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
                            id="Buyer19521">

my xml data

  <userid>23</userid>
  <userdispname>GUJARAT PACKERS LTD</userdispname>
  <usercode>GTPL</usercode>

  <userid>26</userid>
  <userdispname>Lipton India Limited</userdispname>
  <usercode>Lipton</usercode>

  <userid>27</userid>
  <userdispname>TOSH LTD.</userdispname>
  <usercode>ATosh</usercode>

  <userid>28</userid>
  <userdispname>SERVICES INDIA PVT. LTD.</userdispname>
  <usercode>TSI</usercode>

  <userid>29</userid>
  <userdispname>Parekh Company</userdispname>
  <usercode>Parekh</usercode>

  <userid>30</userid>
  <userdispname>SHREE BALAJI CO.</userdispname>
  <usercode>Balaji</usercode>

  <userid>31</userid>
  <userdispname>Kesaria Company</userdispname>
  <usercode>Kesaria</usercode>

my javascript

$(document).ready(function () {
            AuctoCmplBuyer();
            $(".auto").autocomplete({ source: [AuctoCmpData] });
        });
 function AuctoCmplBuyer() {
            $.ajax({
                type: "POST",
                url: "../service/WebService.asmx/XmlData",
                data: "{strData:'BuyerList'}",
                contentType: "application/json; charset=UTF-8",
                dataType: "xml",
                success: function (msg) {
                    $(msg).find('Table').each(function () {
                        if (StrData.length != 0) {
                            StrData = StrData + ",";
                        }
                        StrData = '{"id":"' + $(this).find('UserID').text() + '","label":"' + $(this).find('UserDispName').text() + '","value":"' + $(this).find('UserDispName').text() + '"}';
                    });
                }
            });
            AuctoCmpData = StrData;
        }

Body:
    $(document).ready(function () {
            AuctoCmplBuyer();
Auctocomplete functionality to each textbox
            $(".auto").autocomplete({ source: AuctoCmpData });
        });

function AuctoCmplBuyer() {
            $.ajax({
                type: "POST",
                url: "../service/TWWebService.asmx/XmlData",
                data: "{strData:'BuyerList'}",
                contentType: "application/json; charset=UTF-8",
                dataType: "xml",
                success: function (msg) {
                    $(msg).find('Table').each(function () {
                        rowObj = new Object();
                        rowObj.col1 = $(this).find('UserDispName').text() + '-' + $(this).find('UserID').text();
                        AuctoCmpData.push(rowObj);
                    });
                }
            });
        }

i am doing in this way ...i am not getting the way you said "harie"


问:
Where are WildFly Openshift Image Streams
when loading my image streams with:

```<code>oc get is -n openshift
</code>```

I can see sometimes the Wildfly image stream is not included in the list. Not sure if it's a temporary network issue or not.
In any case, I wanted to ask if the wildfly image stream available somewhere on github, so that I can force reloading it with:

```<code>oc process -f [stream].json
</code>```

Thanks

答:
The Wildfly image streams are a part of:

https://raw.githubusercontent.com/openshift/origin/master/examples/image-streams/image-streams-centos7.json

As an admin, you can load that if not already loaded using:

```<code>oc create -f https://raw.githubusercontent.com/openshift/origin/master/examples/image-streams/image-streams-centos7.json -n openshift
</code>```

or use:

```<code>oc apply -f https://raw.githubusercontent.com/openshift/origin/master/examples/image-streams/image-streams-centos7.json -n openshift
</code>```

if not sure if present if for some reason you accidentally deleted some but not all.

Once loaded they should not disappear unless you are working in the 'openshift' namespace by mistake and delete them. You should never work in the 'openshift' namespace except to load image streams or templates you want accessible to all projects.

Body:
when loading my image streams with:

oc get is -n openshift

I can see sometimes the Wildfly image stream is not included in the list. Not sure if it's a temporary network issue or not.
In any case, I wanted to ask if the wildfly image stream available somewhere on github, so that I can force reloading it with:

oc process -f [stream].json

Thanks

Body:
The Wildfly image streams are a part of:

https://raw.githubusercontent.com/openshift/origin/master/examples/image-streams/image-streams-centos7.json

As an admin, you can load that if not already loaded using:

oc create -f https://raw.githubusercontent.com/openshift/origin/master/examples/image-streams/image-streams-centos7.json -n openshift

or use:

oc apply -f https://raw.githubusercontent.com/openshift/origin/master/examples/image-streams/image-streams-centos7.json -n openshift

if not sure if present if for some reason you accidentally deleted some but not all.

Once loaded they should not disappear unless you are working in the 'openshift' namespace by mistake and delete them. You should never work in the 'openshift' namespace except to load image streams or templates you want accessible to all projects.