text:
Q: apache-camel 3.4.0 - Error executing command: No matching features for camel-catalog/0 Expected behaviour with camel version 2.15.2/2.24.1

*

*Below url has feature as "camel-catalog"
https://repo1.maven.org/maven2/org/apache/camel/karaf/apache-camel/2.15.2/apache-camel-2.15.2-features.xml
<feature name="camel-catalog" version="2.15.2" resolver="(obr)" start-level="50">
<feature version="2.15.2">camel-core
mvn:org.apache.camel.karaf/camel-karaf-commands-catalog/2.15.2

Exception while deploying feature ="camel-catalog" on Karaf Container with camel 3.x-
karaf@root()> feature:install camel-catalog
Error executing command: No matching features for camel-catalog/0
Query -
Upgraded camel version 3.4.0 now feature ="camel-catalog" is not there and but it require to install in Karaf container So what we can do to resolve this.
https://repo1.maven.org/maven2/org/apache/camel/karaf/apache-camel/3.4.0/apache-camel-3.4.0-features.xml
Any help/suggestion is most welcome.

A: The camel-catalog feature is not available as a feature in Camel 3, you dont need to install it, you get catalog installed via installing camel - features:install camel.
See the migration 2.x to 3.x guides: https://camel.apache.org/manual/latest/camel-3x-upgrade-guide.html


text:
Q: Get weekdays based on timezone and current time I am having below table structure where day_index 0 = Monday, 1 = Tuesday and 6 = Sunday. Here start_time and end_time is UTC Time.
day_index  hour_string          start_time  end_time
        0  05:30 AM - 05:30 PM  07:30 PM    07:30 AM
        1  10:00 AM - 08:00 PM  12:00 AM    10:00 AM
        2  07:30 AM - 11:30 PM  09:30 PM    01:30 PM
        3  09:00 AM - 02:30 PM  11:00 PM    04:30 AM
        4  09:00 AM - 04:00 PM  11:00 PM    06:00 AM
        5  08:30 AM - 03:30 PM  10:30 PM    05:30 AM
        6  08:30 AM - 11:00 PM  10:30 PM    01:00 PM

Now based on today's time i need whole weekday like today we have 22-07-2020 so it would be 20-07-2020,21-07-2020 and last one is 27-07-2020.
Also if today times is over ( end_time with timezone ) i need next available day with start_time.
Example : In today's case we have 1.30 PM UTC +  5.30 = 6.30. So we have next opening time would be 11.00 PM UTC + 5.30 = 4.30 AM In Morning.

A: Are you familiar with CONVERT_TZ?  That is how you convert a datetime to another timezone.  You cannot convert a time without the date to a timezone.
Here are some variables to set before running the query;
SET @last_monday = DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY);
SET @local_timezone = 'US/Eastern';

This query will give you the date for each day of the week, the start and end time in UTC, and the start and end time in the local timezone:
SELECT DATE_ADD(@last_monday, INTERVAL day_index DAY) date_dayofweek,
TIMESTAMP(CONCAT(DATE_ADD(@last_monday, INTERVAL day_index DAY),' ',start_time)) startDateTimeUTC,
TIMESTAMP(CONCAT(DATE_ADD(@last_monday, INTERVAL day_index DAY),' ',end_time)) endDateTimeUTC,
CONVERT_TZ(TIMESTAMP(CONCAT(DATE_ADD(@last_monday, INTERVAL day_index DAY),' ',start_time)),'UTC',@local_timezone) startDateTimeLocal,
CONVERT_TZ(TIMESTAMP(CONCAT(DATE_ADD(@last_monday, INTERVAL day_index DAY),' ',end_time)),'UTC',@local_timezone) endDateTimeLocal
FROM table_name ;

Using the answer here to get last Monday -
MYSQL: How can I find 'last monday's date' (performance Issue)
You can also use variables within the query to make this query much more readable, as there is a lot of repetition.  I'm not sure if that would be confusing for you, but I'm happy to provide you with a query if you would need it.

A: This was a tricky mysql query but with the help of another answer it is quite staightforward to answear.
SELECT
    DATE_ADD(DATE_ADD(CURDATE(),
            INTERVAL - WEEKDAY(CURDATE()) DAY),
        INTERVAL day_index DAY)
FROM
    schedule

redpajama_set_name: RedPajamaStackExchange


text:
Q: TransitionEnd Firing Too Soon I'm trying to sequence some animations using jQuery and css transitions. It seems like the container width should animate until after the widget is done transitioning from the 'top' css change, but they are firing together.
Why does
        widget.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(i) {

            widget.css({'top': top});

            widget.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(i) {

                container.css({'width': "19%"})

            });

        });

Animate in the same sequence as this?
        widget.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(i) {

            widget.css({'top': top});

        });

        widget.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(i) {

            container.css({'width': "19%"})

        });

A: In your first example you need to set the css before adding the transitionEnd event.  I believe this is where you are going wrong.
widget.css({
    'top': '200px'
}).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (i) {

    widget.css({
        'top': '0px'
    }).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (i) {

        container.css({
            'width': "300px"
        }).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (i) {

            container.css({
                'width': "50px"
            }).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function (i) {

                widget.css({
                    'width': "400px"
                })

            });
        });

    });

});

Chaining transitions works fine as long as you use one instead of on with jQuery.
See this jsFiddle:
http://jsfiddle.net/gordyr/NSCd5/3/
I'm not sure if you're doing something different, but hopefully this will help.
Though personally I would wrap this up into a helper function to avoid writing so much browser specific code... Something like this (not tested):
$.fn.transition = function(props, callback){
              $(this).css(props).one('webkitTransitionEnd otransitionend oTransitionEndmsTransitionEnd transitionend', function (i) {
                    if(typeof callback == 'function'){
                            callback();
                    }
              });
        return this;
});

Used like so:
$(element).transition({top:'0px'}, function(){
      $(this).transition({top:'100px'}, function(){
          $(this).transition({top:'400px'}, function(){
               //Do something else
          });
    });
});

Though with cached elements rather than taking the hit of $(this) everytime of course...


text:
Q: How do I iterate though a list to see if any value in the list matches part of a value in another cell? I have a list of US states from the US library. I am trying to then loop through a column in an excel file, to see if any cells in that column contain any US states. If it does, then I will delete those rows.
excel_file = pd.read_excel('file.xlsx', sheet_name = 'sheet')

states = us.states.STATES

for i in range(len(excel_file['Column Label'])):
    if any(states) in excel_file['Column Label'][i]:
        print(i)

Right now I have a print statement in the loop just to see which indexes pop up, but the loop itself isn't working. I am receiving this error.

TypeError: 'in ' requires string as left operand, not bool

A: This isn't what any() does. any() loops over an iterable and returns True if any of the things in that iterable result in True.
For example:
any([False, False, False]) => False
any([False, True, False])  => True

To more easily read what you're trying to do, I switched to an enumerate() loop instead of range. This returns the index and the current value we're iterating over. For each entry in the sheet, we can then check if that entry is within your list of states.
The print() statement here prints both the i value and your entry that matched.
for i, entry in enumerate(excel_file['Column Label']):
  if entry in states:
    print(i, entry)

Note: Python hides the fact that this exercise requires a nested loop. The top for loop is obvious, but the in keyword here is creating a loop of its own. It is comparing entry to each item in states, at least until it finds a match.

A: Try this code below,The any() function returns True if any item in an iterable are true, otherwise it returns False:
any(state in excel_file['Column Label'][i] for state in states)


text:
Q: Tomcat Service stops on undeplyment I have a web application which internally starts a server socket and listens to the incoming messages. When I am undeploying my web application it stops tomcat server also.
Can I know are there any settings that I need to update to handle this situation ?
My Environment : Currently I am using the default settings which comes from the installation. My tomcat version is "Apache Tomcat/7.0.10", JVM version is "1.6.0_24-b24", OS i am using is "Linux"
Error in server logs shows :
SEVERE: The web application [/sampleApp] appears to have started a thread named [Thread-4] but has failed to stop it. This is very likely to create a memory leak.

A: Not sure why undeploying the application is causing Tomcat itself to stop, maybe looking some more at the logs and increasing the log level will shed some light. However your approach of creating a server socket within Tomcat is quite strange (I question why does it need to be in a webapp in the first place if its implementing its own socket protocol rather than HTTP).
The Servlet API explicitly recommends against creating new threads while handling HTTP servlet requests. Tomcat tracks its thread pools and resources associated with each webapp, and when you're creating a new Thread you're effectively going out of its model, which is what is creating that SEVERE: error. This is happening most probably when your ServerSocket gets a new client connection and you initialise a new Thread to handle it.
If you need to implement any multi-threading it should be in a ContextListener, which gets initialised when the webapp is loaded. The servlets then communicate to it if they need to offload any work to other threads. Never create new threads directly from a Servlet. You can also put the ServerSocket in the ContextListener, however you might want to rethink why you are handling your own protocol and HTTP (maybe using Jetty makes more sense in your case?)


text:
Q: Sharing internet without wifi How can I use the Internet on two computers when I only have one Ethernet cable connected to the switch in my hostels's server room which is further connected to central sever room which is further connected to NIC optical fiber cable Network? I cannot use WiFi because my IBM Thinkpad laptop does not have wireless.
My college network (LAN + Internet) has a proxy server and routers in a central server room then switches in each hostel. The Ethernet cable is coming from one of those switches.
I have tried LAN splitter but it did not work.

A: It sounds like from that description that you need a switch which would be plugged into the patch port in your room and then plugged into both computers. An alternative would be to get WiFi but on the Thinkpad you could either get a USB WiFi adapter or create a bridged connection between the two computers.
Hope this helped


text:
Q: With BreezeJs how do you handle updating cache for user1 after user2 has made changes? Trying to find the proper solution for breezejs, if user1/device1 has a cached list of projects and user2/device2 updates one of those records, user1 still sees stale data unless they manually refresh.
What are the solutions to make sure User1 gets the new upated data? Is there something I can do on save of entity to remove it from everyone's cache? Is the cache based per user?

A: The Breeze EntityManager cache is a client side cache, so each user/device/application will have its own data.  There is no simple way to keep these caches in sync except by requerying. Optimistic concurrency, providing you are using it, does guarantee that you do not update newer data with older data, but the stale data issue is still very real.
We along with several other Breeze users have investigated using SignalR with Breeze to let Breeze know when and what to refresh, but right now these solutions are all custom. Please add your vote to the Breeze User Voice ( https://breezejs.uservoice.com/forums/173093-1-breezejs-feature-suggestions) on this topic if you want to see either examples or tighter integration between Breeze & SignalR.

A: I would maybe recommend firebase if you need real time data sync in your application


text:
Q: Error 28: Expression must have a constant value I have a section of c++ code in keil uvision5 that is getting error 28: expression must have a constant value.  I am trying to figure out how to fix it.
this is the line (inside of a function) that it is happening on:
osPoolDef_t pool_def = { queue_def->queue_sz,  queue_def->item_sz};

it does not like the variables queue_sz or item_sz.
here is the definition of osPoolDef_t:
typedef const struct os_pool_def  {
  uint32_t                 pool_sz;    /*  number of items (elements) in the pool */
  uint32_t                 item_sz;    /*  size of an item */
  void                     *pool;      /*  pointer to memory for pool */
} osPoolDef_t;

and queue_def is a pointer to osMailQDef_t shown below:
typedef const struct os_mailQ_def  {
  uint32_t                queue_sz;    /*  number of elements in the queue */
  uint32_t                 item_sz;    /*  size of an item */
  struct os_mailQ_cb **cb;
} osMailQDef_t;

hopefully that is enough information.
It seems that the problem is that I am not using c99 anymore, but the code worked fine for that file when I used c99.  Is there a way to force the compilation of just that file to be done with c99?

A: You can force the armcc compiler to use C99 with the --c99 option.


text:
Q: How can I print one to many relationship result in php? I am getting below table as result for my query.
id     name   celebrity
------------------------
1      A       X
1      A       Y
1      A       Z
2      B       M
2      B       N

I want to print this table result as below using php.
1->A->X,Y,z

2->B->M,N

I am getting above table as associative array after querying with mysql database. Can anyone help me to write a logic to print the table result as above. Thanks in advance.

A: You can make it by mysql
select id, name, group_concat(celebrity)
   from te table
 group by id, name


text:
Q: Sending data to two different fields using foreign key I am using foreign key of a model person using both its field in other other model company. But while inserting data in company I am not getting last name, output is employee and last are both the same.
Class Person (models.Model):
first_name = models.CharField(max_length=30,null=True)
last_name = models.CharField(max_length=30,null=True)

def __str__(self):
    return str(self.first_name)

Class Company (models.Model):
name=models.CharField(max_length=20,null=True)
employee=models.ForeignKey(Person,on_delete=models.CASCADE,related_name='first',null=True)
last=models.ForeignKey(Person,on_delete=models.CASCADE,related_name='second',null=True)

def __str__(self):
    return str(self.name)

ViewSet
class CompanyViewset(viewsets.ViewSet):
def create(self,request):
    name=request.data.get('name')
    employee=request.data.get('employee')
    last=request.data.get('last')
    user=Company()
    user.name=name
    user.employee=Person.objects.get(first_name=employee)
    user.last=Person.objects.get(last_name=last)

    #print(user.last)
    #user.last=use.last_name

    print(user.last.last_name)
    user.save()

    return Response({'Successfully saved'})


text:
Q: Can deep belief networks be applied to sparse feature vectors/classification problems? I am trying to beat the performance of an SVM classifier in a text classification task.
Input is a bag of words model of sentences with 1 representing presence and 0 representing absence. Output is 1 of 4 possible labels. Are DBNs directly applicable to this class of problems? I get an error of 0.38 on the test set and I could not make it any better.
Please refer me to papers/posts where I can find similar problems/applications.

A: Although you could in principle directly apply a DBN to your data to learn new feature representations, a more promising approach in my view would be to look for models tailored more closely to your problem. Hugo Larochelle, for example, has used and extended RBMs to model both documents and classification problems. Maybe you can find something useful on his website:
http://www.dmi.usherb.ca/~larocheh/projects_classrbm.html

A: In addition to Lucas' answer, this paper might be interesting for you:
Semantic Hashing. A DBN is used to create a bit code for each document based on a bag of words representation. This can serve as features for a subsequent classifier or similarty search.


text:
Q: UISearchDisplayController - Method for when cancel button is clicked I have a UISearchDisplayController that shows the cancel button.  I would like to call a method when a user clicks the cancel button.  Is there a way to do this?

A: You can use the following  searchbar delegate method,
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
     // DO ur operations
}

A: For UISearchDisplayController, the following 2 methods can be considered.
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@"WillEndSearch");
}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@"DidEndSearch");
}


text:
Q: What comes after sorting eigenvalues in PCA? I'm a student, I have to build PCA from scratch using Matlab on iris data. Iris data have 4 features, I want to reduce them to 2. I reached the sorting of eigenvalues step. What is the next step?

A: Choose the two largest eigenvalues and find their corresponding eigenvectors. Then make a matrix that has these eigenvectors as columns. Use that matrix to project your original data.


text:
Q: Get var out of jQuery.get nested function   function getUserHours(tyPe, tarGet){
    $.get('/activities/search', { 'type': tyPe },
    function(data){
     var hourResultData = jQuery.parseJSON(data);
     var registeredHours = 0;
     for (var i in hourResultData.activities){
      registeredHours += parseFloat(hourResultData.activities[i].hours);
     }
     $(tarGet).empty().append(registeredHours);
     return registeredHours;
   });

  }

I want:
alert( getUserHours('r', '#reg-hours'));

to alert registeredHours

A: Returning data directly will only work if you turn the asynchronous GET for AJAX off:
$.ajax({
    type: 'GET',
    url: '/activities/search',
    data: { 'type': tyPe },
    async : false,
    success : function() { }
 });

This is not recommended, because the browser will block until you request is finished. Instead you should continue to follow the asynchronous programming model by using function callback:
$.ajax({
    type: 'GET',
    url: '/activities/search',
    data: { 'type': tyPe },
    async : false,
    success : function() { }
 });

function getUserHours(tyPe, tarGet, callback)
{
    $.get('/activities/search', { 'type': tyPe },
    function(data)
    {
        var hourResultData = jQuery.parseJSON(data);
        var registeredHours = 0;
        for (var i in hourResultData.activities){
            registeredHours += parseFloat(hourResultData.activities[i].hours);
        }
        $(tarGet).empty().append(registeredHours);
        if($.isFunction(callback))
            callback(registeredHours);
    });
}

getUserHours('r', '#reg-hours', function(hours) {
    alert(hours);
});

A: The callback function you're trying to return from is called when the data is ready, meaning the data is sent asyncronously.
This means you can't return the data directly from your getUserHours function. You need a callback function to fire when the data is ready.
Something like this:
  function getUserHours(tyPe, tarGet, callback){
    $.get('/activities/search', { 'type': tyPe },
    function(data){
     var hourResultData = jQuery.parseJSON(data);
     var registeredHours = 0;
     for (var i in hourResultData.activities){
      registeredHours += parseFloat(hourResultData.activities[i].hours);
     }
     $(tarGet).empty().append(registeredHours);

     callback(registeredHours); // callback, send back data to callback function
   });

  }

Then send an anonymous function as a parameter in getUserHours.
  getUserHours('r', '#reg-hours', function(data) {
    alert(data);
  });


text:
Q: Why do sequential GUID keys perform faster than sequential INT keys in my test case? After asking this question comparing sequential and non-sequential GUIDs, I tried to compare the INSERT performance on 1) a table with a GUID primary key initialized sequentially with newsequentialid(), and 2) a table with an INT primary key initialized sequentially with identity(1,1). I would expect the latter to be fastest because of the smaller width of integers, and it also seems simpler to generate a sequential integer than a sequential GUID. But to my surprise, INSERTs on the table with the integer key were significantly slower than the sequential GUID table.
This shows the average time usage (ms) for the test runs:
NEWSEQUENTIALID()  1977
IDENTITY()         2223

Can anyone explain this?
The following experiment was used:
SET NOCOUNT ON

CREATE TABLE TestGuid2 (Id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))

CREATE TABLE TestInt (Id Int NOT NULL identity(1,1) PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))

DECLARE @BatchCounter INT = 1
DECLARE @Numrows INT = 100000

WHILE (@BatchCounter <= 20)
BEGIN
BEGIN TRAN

DECLARE @LocalCounter INT = 0

    WHILE (@LocalCounter <= @NumRows)
    BEGIN
    INSERT TestGuid2 (SomeDate,batchNumber) VALUES (GETDATE(),@BatchCounter)
    SET @LocalCounter +=1
    END

SET @LocalCounter = 0

    WHILE (@LocalCounter <= @NumRows)
    BEGIN
    INSERT TestInt (SomeDate,batchNumber) VALUES (GETDATE(),@BatchCounter)
    SET @LocalCounter +=1
    END

SET @BatchCounter +=1
COMMIT
END

DBCC showcontig ('TestGuid2')  WITH tableresults
DBCC showcontig ('TestInt')  WITH tableresults

SELECT batchNumber,DATEDIFF(ms,MIN(SomeDate),MAX(SomeDate)) AS [NEWSEQUENTIALID()]
FROM TestGuid2
GROUP BY batchNumber

SELECT batchNumber,DATEDIFF(ms,MIN(SomeDate),MAX(SomeDate)) AS [IDENTITY()]
FROM TestInt
GROUP BY batchNumber

DROP TABLE TestGuid2
DROP TABLE TestInt

UPDATE:
Modifying the script to perform the insertions based on a TEMP table, like in the examples by by Phil Sandler, Mitch Wheat and Martin below, I also find that IDENTITY is faster as it should be. But that is not the conventional way of inserting rows, and I still do not understand why the experiment went wrong at first:
even if I omit GETDATE() from my original example, IDENTITY() is still way slower. So it seems that the only way to make IDENTITY() outperform NEWSEQUENTIALID() is to prepare the rows to insert in a temporary table and perform the many insertions as a batch-insert using this temp table. All in all, I don't think we have found an explanation to the phenomenon, and IDENTITY() still seems to be slower for most practical usages. Can anyone explain this?

A: Quite simple: with GUID, it is cheaper to generate the next number in the line than it is for IDENTITY (The current value of the GUID does not have to be stored, the IDENTITY has to be). This is true even for NEWSEQUENTIALGUID.
You could make the test more fair and use a SEQUENCER with a large CACHE - which is cheaper than IDENTITY.
But as M.R. says, there are some major advantages to GUIDs. As a matter of fact, they are MUCH more scalable than IDENTITY columns (but only if they are NOT sequential).
See: http://blog.kejser.org/2011/10/05/boosting-insert-speed-by-generating-scalable-keys/

A: I'm fascinated by this type of question.  Why did you have to post it on a Friday night?  :)
I think even if your test is ONLY intended to measure INSERT performance, you (may) have introduced a number of factors that could be misleading (looping, a long-running transaction, etc.)
I'm not completely convinced my version proves anything, but identity does perform better than the GUIDs in it (3.2 seconds vs 6.8 seconds on a home PC):
SET NOCOUNT ON

CREATE TABLE TestGuid2 (Id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))

CREATE TABLE TestInt (Id Int NOT NULL identity(1,1) PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))

DECLARE @Numrows INT = 1000000

CREATE TABLE #temp (Id int NOT NULL Identity(1,1) PRIMARY KEY, rowNum int)

DECLARE @LocalCounter INT = 0

--put rows into temp table
WHILE (@LocalCounter < @NumRows)
BEGIN
    INSERT INTO #temp(rowNum) VALUES (@LocalCounter)
    SET @LocalCounter += 1
END

--Do inserts using GUIDs
DECLARE @GUIDTimeStart DateTime = GETDATE()
INSERT INTO TestGuid2 (SomeDate, batchNumber)
SELECT GETDATE(), rowNum FROM #temp
DECLARE @GUIDTimeEnd  DateTime = GETDATE()

--Do inserts using IDENTITY
DECLARE @IdTimeStart DateTime = GETDATE()
INSERT INTO TestInt (SomeDate, batchNumber)
SELECT GETDATE(), rowNum FROM #temp
DECLARE @IdTimeEnd DateTime = GETDATE()

SELECT DATEDIFF(ms, @IdTimeStart, @IdTimeEnd) AS IdTime
SELECT DATEDIFF(ms, @GUIDTimeStart, @GUIDTimeEnd) AS GuidTime

DROP TABLE TestGuid2
DROP TABLE TestInt
DROP TABLE #temp

A: I ran your sample script several times making a few tweaks to batch count and size (and thank you very much for providing it).
First I'll say that you're only measuring once aspect of the keys' performance - INSERT speed. So unless you're specifically concerned only with getting data into the tables as quickly as possible there's much more to this animal.
My findings were in general similar to yours. However, I would mention that variance in INSERT speed between GUID and IDENTITY (int) is slightly larger with GUID than with IDENTITY - maybe +/- 10% between runs. The batches that used IDENTITY varied less than 2 - 3% each time.
Also to note, my test box is clearly less powerful than yours so I had to use smaller row counts.

A: I modified @Phil Sandler's code to remove the effect of calling GETDATE() (there may be hardware effects/interrupts involved??), and made rows the same length.
[There have been several articles since SQL Server 2000 relating to timing issues and high-resolution timers, so I wanted to minimise that effect.]
In simple recovery model with data and log file both sized way over what is required, here are the timings (in seconds): (Updated with new results based on exact code below)
       Identity(s)  Guid(s)
       ---------    -----
       2.876        4.060
       2.570        4.116
       2.513        3.786
       2.517        4.173
       2.410        3.610
       2.566        3.726
       2.376        3.740
       2.333        3.833
       2.416        3.700
       2.413        3.603
       2.910        4.126
       2.403        3.973
       2.423        3.653
    -----------------------
Avg    2.650        3.857
StdDev 0.227        0.204

The code used:
SET NOCOUNT ON

CREATE TABLE TestGuid2 (Id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(88))

CREATE TABLE TestInt (Id Int NOT NULL identity(1,1) PRIMARY KEY,
SomeDate DATETIME, batchNumber BIGINT, FILLER CHAR(100))

DECLARE @Numrows INT = 1000000

CREATE TABLE #temp (Id int NOT NULL Identity(1,1) PRIMARY KEY, rowNum int, adate datetime)

DECLARE @LocalCounter INT = 0

--put rows into temp table
WHILE (@LocalCounter < @NumRows)
BEGIN
    INSERT INTO #temp(rowNum, adate) VALUES (@LocalCounter, GETDATE())
    SET @LocalCounter += 1
END

--Do inserts using GUIDs
DECLARE @GUIDTimeStart DateTime = GETDATE()
INSERT INTO TestGuid2 (SomeDate, batchNumber)
SELECT adate, rowNum FROM #temp
DECLARE @GUIDTimeEnd  DateTime = GETDATE()

--Do inserts using IDENTITY
DECLARE @IdTimeStart DateTime = GETDATE()
INSERT INTO TestInt (SomeDate, batchNumber)
SELECT adate, rowNum FROM #temp
DECLARE @IdTimeEnd DateTime = GETDATE()

SELECT DATEDIFF(ms, @IdTimeStart, @IdTimeEnd) AS IdTime, DATEDIFF(ms, @GUIDTimeStart, @GUIDTimeEnd) AS GuidTime

DROP TABLE TestGuid2
DROP TABLE TestInt
DROP TABLE #temp
GO

After reading @Martin's investigation, I re-ran with the suggested TOP(@num) in both cases, i.e.
...
--Do inserts using GUIDs
DECLARE @num INT = 2147483647;
DECLARE @GUIDTimeStart DATETIME = GETDATE();
INSERT INTO TestGuid2 (SomeDate, batchNumber)
SELECT TOP(@num) adate, rowNum FROM #temp;
DECLARE @GUIDTimeEnd DATETIME = GETDATE();

--Do inserts using IDENTITY
DECLARE @IdTimeStart DateTime = GETDATE()
INSERT INTO TestInt (SomeDate, batchNumber)
SELECT TOP(@num) adate, rowNum FROM #temp;
DECLARE @IdTimeEnd DateTime = GETDATE()
...

and here are the timing results:
       Identity(s)  Guid(s)
       ---------    -----
       2.436        2.656
       2.940        2.716
       2.506        2.633
       2.380        2.643
       2.476        2.656
       2.846        2.670
       2.940        2.913
       2.453        2.653
       2.446        2.616
       2.986        2.683
       2.406        2.640
       2.460        2.650
       2.416        2.720

    -----------------------
Avg    2.426        2.688
StdDev 0.010        0.032

I wasn't able to get the actual execution plan, as the query never returned! It seems a bug is likely. (Running Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64))

A: On a fresh database in simple recovery model with the data file sized at 1GB and the log file at 3GB (laptop machine, both files on the same drive) and recovery interval set to 100 minutes (to avoid a checkpoint skewing the results) I see similar results to you with the single row inserts.
I tested three cases: For each case I did 20 batches of inserting 100,000 rows individually into the following tables. The full scripts can be found in this answer's revision history.
CREATE TABLE TestGuid
  (
     Id          UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
     SomeDate    DATETIME, batchNumber BIGINT, FILLER CHAR(100)
  )

CREATE TABLE TestId
  (
     Id          Int NOT NULL identity(1, 1) PRIMARY KEY,
     SomeDate    DATETIME, batchNumber BIGINT, FILLER CHAR(100)
  )

CREATE TABLE TestInt
  (
     Id          Int NOT NULL PRIMARY KEY,
     SomeDate    DATETIME, batchNumber BIGINT, FILLER  CHAR(100)
  )

For the third table the test inserted rows with an incrementing Id value but this was self calculated by incrementing the value of a variable in a loop.
Averaging the time taken across the 20 batches gave the following results.
NEWSEQUENTIALID() IDENTITY()  INT
----------------- ----------- -----------
1999              2633        1878

Conclusion
So it definitely appears to be overhead of the identity creation process that is responsible for the results. For the self calculated incrementing integer then the results are much more in-line with what would be expected to see when considering only the IO cost.
When I put the insert code described above into stored procedures and review sys.dm_exec_procedure_stats it gives the following results
proc_name      execution_count      total_worker_time    last_worker_time     min_worker_time      max_worker_time      total_elapsed_time   last_elapsed_time    min_elapsed_time     max_elapsed_time     total_physical_reads last_physical_reads  min_physical_reads   max_physical_reads   total_logical_writes last_logical_writes  min_logical_writes   max_logical_writes   total_logical_reads  last_logical_reads   min_logical_reads    max_logical_reads
-------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- --------------------
IdentityInsert 20                   45060360             2231067              2094063              2645079              45119362             2234067              2094063              2660080              0                    0                    0                    0                    32505                1626                 1621                 1626                 6268917              315377               276833               315381
GuidInsert     20                   34829052             1742052              1696051              1833055              34900053             1744052              1698051              1838055              0                    0                    0                    0                    35408                1771                 1768                 1772                 6316837              316766               298386               316774

So in those results total_worker_time is about 30% higher. This represents

Total amount of CPU time, in
  microseconds, that was consumed by
  executions of this stored procedure
  since it was compiled.

So it simply appears as though the code that generates the IDENTITY value is more CPU intensive than that which generates the NEWSEQUENTIALID() (The difference between the 2 figures is 10231308 which averages out at about 5µs per insert.) and that for this table definition this fixed CPU cost was sufficiently high to outweigh the additional logical reads and writes incurred due to the greater width of the key. (NB: Itzik Ben Gan did similar testing here and found a 2µs penalty per insert)
So why is IDENTITY more CPU intensive than UuidCreateSequential?
I believe this is explained in this article. For every tenth identity value generated, SQL Server has to write the change to the system tables on disk
What about MultiRow Inserts?
When the 100,000 rows are inserted in a single statement I found the difference disappeared with still perhaps a slight benefit to the GUID case but nowhere near as clear cut results. The average for 20 batches in my test was
NEWSEQUENTIALID() IDENTITY()
----------------- -----------
1016              1088

The reason that it doesn't have the penalty apparent in Phil's code and Mitch's first set of results is because it so happened that the code I used to do the multi row insert used SELECT TOP (@NumRows). This prevented the optimiser from correctly estimating the number of rows that will be inserted.
This seems to be of benefit as there is a certain tipping point at which it will add an additional sort operation for the (supposedly sequential!) GUIDs.

This sort operation is not required from the explanatory text in BOL.

Creates a GUID that is greater than
  any GUID previously generated by this
  function on a specified computer since
  Windows was started. After restarting
  Windows, the GUID can start again from
  a lower range, but is still globally
  unique.

So it seemed to me a bug or missing optimisation that SQL Server does not recognise that the output of the compute scalar will already be pre-sorted as it apparently already does for the identity column. (Edit I reported this and the unnecessary sort issue is now fixed in Denali )

A: I'm going to refer back to another conv on stackoverflow for this same topic - https://stackoverflow.com/questions/170346/what-are-the-performance-improvement-of-sequential-guid-over-standard-guid
One thing I do know is that having sequential GUIDs is that the index usage is better due to very little leaf movement, and therefore reducing HD seek. I would think because of this, the inserts would be faster, too, as it doesn't have to distribute the keys over a large number of pages.
My personal experience is that when you are implementing a large high traffic DB, it is better to use GUIDs, because it makes it much more scalable for integration with other systems. That goes for replication, specifically, and int/bigint limits.... not that you would run out of bigints, but eventually you will, and cycle back.


text:
Q: Calculating $ d \Phi^{*} \omega$ and $ \Phi^{*} d\omega$ Let $\omega \in \Omega^2(\mathbb{R}^3)$ as follow: $\omega = x dy\land dz + y dz \land dx + z dx \land dy $.
Let $\Phi: \Bbb R^3\to \Bbb R^3$ be given by
$$\Phi(r, \phi, \psi) = (r\cos\phi \cos\psi, r\sin \phi \cos\psi, r\sin \psi) .$$
I can not figure out how to calculate $d\Phi^{*}\omega $ and $ \Phi^{*} d\omega$.
Are they supposed to be equal?

A: The computation is very long and mechanical, I am only doing it for the first term, the rest is left for you to try.
$$\Phi^* (x \,dy\wedge dz) = (x\circ\Phi)\big|_{(r,\phi,\psi)} d(y\circ\Phi)\big|_{(r,\phi,\psi)}\wedge d(z\circ\Phi)\big|_{(r,\phi,\psi)}.\tag{1}$$
First term:
$$
(x\circ\Phi)\big|_{(r,\phi,\psi)} = r\cos\psi \cos\phi.
$$
Second term:
$$
d(y\circ\Phi)\big|_{(r,\phi,\psi)} = d(r\cos\psi \sin\phi)
\\
= \cos\psi \sin\phi\, dr -  r\sin\psi \sin\phi\, d\psi + r\cos\psi \cos\phi\,d\phi.
$$
Third term:
$$
d(z\circ\Phi)\big|_{(r,\phi,\psi)} = d(r\sin\psi) = \sin\psi\,dr + r\cos\psi\,d\psi.
$$
Therefore (1) is:
$$
(r\cos\psi \cos\phi)(\cos\psi \sin\phi\, dr -  r\sin\psi \sin\phi\, d\psi + r\cos\psi \cos\phi\,d\phi)\wedge (\sin\psi\,dr + r\cos\psi\,d\psi),
$$
make use of $dr\wedge dr = 0$ and $d\psi\wedge d\psi = 0$, $dr\wedge d\psi = -d\psi\wedge dr$  we have:
$$
\Phi^* (x \,dy\wedge dz) = \\
r^2 \cos\psi \cos\phi \sin\phi \,dr\wedge d\psi
\\
+ r^2 \cos^2\psi \sin \psi \cos^2 \phi \,dr\wedge d\phi
\\
+ r^3 \cos^3\psi \cos^2\phi \,d\phi\wedge d\psi.
$$
When taking exterior derivative, notice
$$
d( \cos\psi \cos\phi \sin\phi \,dr\wedge d\psi) =
\\
\color{\red}{ \frac{\partial }{\partial r}\cos\psi \cos\phi \sin\phi \,dr\wedge (dr\wedge d\psi)}
\\
+ \color{\red}{\frac{\partial }{\partial \psi}\cos\psi \cos\phi \sin\phi \,d\psi\wedge (dr\wedge d\psi) }
\\
+  \color{\green}{\frac{\partial }{\partial \phi}\cos\psi \cos\phi \sin\phi \,d\phi\wedge (dr\wedge d\psi)},
$$
red terms are gone, only green term left.
$$
d\Phi^* (x \,dy\wedge dz) = \\
\frac{\partial }{\partial \phi} r^2 \cos\psi \cos\phi \sin\phi \,d\phi\wedge (dr\wedge d\psi)
\\
+ \frac{\partial }{\partial \psi}r^2 \cos^2\psi \sin \psi \cos^2 \phi \,d\psi\wedge(dr\wedge d\phi)
\\
+ \frac{\partial }{\partial r}r^3 \cos^3\psi \cos^2\phi \,dr\wedge(d\phi\wedge d\psi).
$$
Then we can combine these terms by:
$$
dr \wedge d\psi\wedge d\phi = d\phi\wedge (dr\wedge d\psi) = -d\psi\wedge(dr\wedge d\phi) =-dr\wedge(d\phi\wedge d\psi).
$$
Do the same for the other two terms (left for you to try):
$$
d\Phi^* \omega = d\Phi^* (x \,dy\wedge dz) + d\Phi^* (y \,dz\wedge dx) + d\Phi^* (z \,dx\wedge dy).
$$

For $d\omega = 3\,dx\wedge dy\wedge dz$, we can use (1) again:
$$\Phi^* d\omega =   d(x\circ\Phi)\big|_{(r,\phi,\psi)} \wedge d(y\circ\Phi)\big|_{(r,\phi,\psi)}\wedge d(z\circ\Phi)\big|_{(r,\phi,\psi)}.$$
The computation is similar as above.


text:
Q: how can we remove extra message in log files i have a simple logging program ie:
public class LoggingExample1 {
 public static void main(String args[]) {
try {
  LogManager lm = LogManager.getLogManager();
  Logger logger;
  FileHandler fh = new FileHandler("log_test.txt");

  logger = Logger.getLogger("LoggingExample1");
  lm.addLogger(logger);
  logger.setLevel(Level.INFO);

  fh.setFormatter(new SimpleFormatter());

  logger.addHandler(fh);
  // root logger defaults to SimpleFormatter. We don't want messages
  // logged twice.
  //logger.setUseParentHandlers(false);

  logger.log(Level.INFO, "test 1");
  logger.log(Level.INFO, "test 2");
  logger.log(Level.INFO, "test 3");
  fh.close();
} catch (Exception e) {
  System.out.println("Exception thrown: " + e);
  e.printStackTrace();
}
}
}

i get this log:
Aug 1, 2011 5:36:37 PM LoggingExample1 main
INFO: test 1
Aug 1, 2011 5:36:37 PM LoggingExample1 main
INFO: test 2
Aug 1, 2011 5:36:37 PM LoggingExample1 main
INFO: test 3

but i want to remove the messages like: LoggingExample1 main and INFO
and only keep the data that are logged by code.
what can i do???

A: This is because you are using a SimpleFormatter which always logs the class name, method name etc. If you don't want this information, you can write your own formatter. Here is a simple example of a formatter which just outputs the log level and the log message:
import java.util.logging.*;

class MyFormatter extends Formatter{

    /* (non-Javadoc)
     * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
     */
    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();
        sb.append(record.getLevel()).append(':');
        sb.append(record.getMessage()).append('\n');
        return sb.toString();
    }
}

Use this formatter in your file handler:
fh.setFormatter(new MyFormatter());

This will output:
INFO:test 1
INFO:test 2
INFO:test 3

A: Extend your class with formatter class as below:
public class MyFormatter extends SimpleFormatter{

@Override

public synchronized String format(LogRecord record){

    record.setSourceClassName(MyFormatter.class .getName());
    return String.format(
            " [%1$s] :%2$s\n",
            record.getLevel().getName(), formatMessage(record));

    }
}

Then in you main class, set console handler and filehandler format as your class format object.
In my case ,it is consoleHandler.format(new MyFormatter);
filehandler.format(new Myformatter);
Most imp thing is you have to set
logger.setUseParentHandler(false);
now you are good to go!

A: If I understand you correctly, you want to remove INFO and only have test 1 and so on?
If that is the case, I don't think its possible. The reason is that you need to know what type of message this is.
ERROR
WARNING
INFO
DEBUG
TRACE

You can change the level to only display WARNING and up if you want.

A: Here is how I do this, simplified version of SimpleFormatter
package org.nibor.git_merge_repos;

import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public class CustomLogFormatter extends Formatter {

    private final Date dat = new Date();

    private static final String seperator = " : ";

    public synchronized String format(LogRecord record) {
        dat.setTime(record.getMillis());
        return dat + seperator + record.getLevel().getName() + seperator + record.getMessage() + "\n";

    }
}


text:
Q: The method sign.setline is not working im haveing a problem running a setline command
witch i want to set the line of a sign with..
it isn't doing anything
This is the part of the code that has the setline method in it it will run with a few other things when the player will give the input (the "if (SignEvent.isNumericArray(times))" is true for sure and the code is running i did check that )
  if (SignEvent.isNumericArray(times)){

                double uses = Double.parseDouble(times);
                uses = uses -1;

                sign.setLine(2 , uses + "/" + str[1] + parts[1]);

                if (uses <= 0){
                sign.setLine(0, ChatColor.STRIKETHROUGH + "StartPayment");
                }
            }

i did check a few things :

*

*no errors in console or eclipse error list

*object sign is type Sign imported from import org.bukkit.block.Sign

*object sign is the right sign (checked by doing  e.getPlayer().sendMessage(sign.getLine(0)); it worked..

*no matter what the string is it isn't working

*no matter where i put this line of code its not working

*the this line is running

i just have no idea what could i do to fix it i tried a lot of things and im pretty sure the problem is in the
sign.setLine(2 , uses + "/" + str[1] + parts[1]); line
any one have any idea for what did i do wrong ?
Note: no matter where in this method i put the setline method or with what string/lineIndex ,it isn't doing anything

A: I think you have to execute sign.update(); after a modification to apply changes.


text:
Q: Issue Upgrading DNN 6.x to 7.4 I am stuck with upgrading DNN from Version 6.x to version 7.4
I am using Ifnity URL Master V2.4.4 with DNN 6. Before upgrading DNN to 7.4, I have first upgraded Ifinity URL Master from 2.4 to 2.8.3 and then upgraded DNN to 7.4. while doing so I am getting below error on Default.aspx load.
 500 Internal Server Error
    The requested Url does not return any valid content.

    Administrators
    Change this message by configuring a specific 404 Error Page or Url for this website.

    Exception:
    Object reference not set to an instance of an object.

    Stack Trace:

at DotNetNuke.Common.Globals.IsEditMode() at
  DotNetNuke.Entities.Tabs.TabModulesController.GetModules(TabInfo tab)
  at DotNetNuke.Entities.Tabs.TabModulesController.GetTabModules(TabInfo
  tab) at DotNetNuke.Entities.Tabs.TabInfo.get_Modules() at
  iFinity.DNN.Modules.UrlMaster.Entities.TabInfoEx.Clone(TabInfo tab) at
  iFinity.DNN.Modules.UrlMaster.Data.SqlDataProvider.GetTabs(Int32
  portalId, Boolean includeAdminTabs, Boolean includeHostTabs,
  Dictionary`2& customAliasTabs) at
  iFinity.DNN.Modules.UrlMaster.UrlMasterController.GetTabs(Int32
  portalId, Boolean includeStdUrls, PortalSettings portalSettings,
  FriendlyUrlSettings settings, Dictionary2& customAliasTabsForPortal)
  at iFinity.DNN.Modules.UrlMaster.UrlMasterController.GetTabs(Int32
  portalId, Boolean includeStdUrls, FriendlyUrlSettings settings,
  Dictionary2& customAliasTabs) at
  iFinity.DNN.Modules.UrlMaster.TabDictController.BuildTabDictionary(PathSizes&
  pathSizes, FriendlyUrlSettings settings, Int32 buildPortalId,
  ThreadSafeDictionary2 tabDict, Hashtable& homePageSkins,
  ThreadSafeDictionary2& portalTabPathDictionary, Guid parentTraceId)
  at
  iFinity.DNN.Modules.UrlMaster.TabDictController.FetchTabDictionaryLockable(Int32
  portalId, Int32& minTabPathDepth, Int32& maxTabPathDepth, Int32&
  minAliasPathDepth, Int32& maxAliasPathDepth, FriendlyUrlSettings
  settings, Boolean forceRebuild, Boolean bypassCache, Guid
  parentTraceId) at
  iFinity.DNN.Modules.UrlMaster.TabDictController.FetchTabDictionary(Int32
  portalId, Int32& minTabPathDepth, Int32& maxTabPathDepth, Int32&
  minAliasPathDepth, Int32& maxAliasPathDepth, FriendlyUrlSettings
  settings, Boolean forceRebuild, Boolean bypassCache, Guid
  parentTraceId) at
  iFinity.DNN.Modules.UrlMaster.RewriteController.GetTabFromDictionary(String
  url, FriendlyUrlSettings settings, UrlAction result, Guid
  parentTraceId) at
  iFinity.DNN.Modules.UrlMaster.RewriteController.IdentifyByTabPathEx(String
  absoluteUri, String queryString, UrlAction result, FriendlyUrlSettings
  settings, Guid parentTraceId) at
  iFinity.DNN.Modules.UrlMaster.UrlRewriteModule.CheckForRewrite(String
  fullUrl, String querystring, UrlAction result, Boolean
  useFriendlyUrls, NameValueCollection queryStringCol,
  FriendlyUrlSettings settings, Boolean& isPhysicalResource, Guid
  parentTraceId) at
  iFinity.DNN.Modules.UrlMaster.UrlRewriteModule.ProcessRequest(HttpContext
  context, HttpRequest request, HttpServerUtility Server, HttpResponse
  response, Boolean useFriendlyUrls, String requestType, Uri requestUri,
  UrlAction result, NameValueCollection queryStringCol,
  FriendlyUrlSettings settings, Boolean allowSettingsChange, Guid
  parentTraceId)

I am not sure cause of this error and not sure how to forward in this. Please help me resolve this issue.

A: I was using IFinity URL Master 2.4 as well and upgrade from 2.4 to 2.8.3 so I could upgrade DNN to 7.4.2.  I got the same problem you have.
The only way I was able to fix it was to remove IFinity URL Master completely and then upgrade to DNN 7.4.2.
In DNN 7.4.2 they have integrated IFinity URL Master into it.  Then you have to change your web.config file to use the proper URLFormat results you are looking for.  Try opening your web.config file and doing a search for URLFormat make sure it either has a value of URLFormat="humanfriendly" or URLFormat="advanced" depending on the results you wish to get.


text:
Q: Confused about Landau-notation and inequality
Let $f$ be a real valued function and $|f(x)| \le x^2\cdot C + o(x^3)$ as $x\to 0$, where $C \ge 0$ is a constant independent of x. Is it true that there is a $x_0$ such that for all $x\in [0,x_0]$ : $|f(x)| \le x^2\cdot \hat C$ for a constant $\hat C$?

My answer is yes. Since by definition we have for all $g\in o(x^3): \lim_{x\to0}g(x)/x^3 = 0$ thus also $\lim_{x\to0} g(x)/x^2 = 0$ (by product of limits) which means $g\in o(x^2)$. Now $g\in o(x^2)$ implies there is a $x_0 \gt 0$ such that for all $x \le x_0: g(x) \le x^2$ (else the limit $\lim_{x\to0} g(x)/x^2 \ne 0$ or wouldn't exist). Then for all $x\in [0,x_0]: |f(x)| \le x^2\cdot C + o(x^3)\le x^2\cdot C + x^2 \le x^2(1+C) =: x^2 \hat C$. Is my reasoning correct?


text:
Q: PHP carousel only shows top of video? I have this carousel on my php site with a video in it (and two pictures), but it only shows the top of the video? Can I get it to take the center of the video instead of the top?

            <video autoplay class="embed-responsive-item">
                <source src="media/Videologo.mp4">


text:
Q: Ruby `require': cannot load such file -- fcgi Dreamhost When trying to run a ruby script ruby dispatch.fcgi I get the error
/pathtorvm/.rvm/rubies/ruby-2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- fcgi (LoadError)
from /pathtorvm/.rvm/rubies/ruby-2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from dispatch.fcgi:8:in `<main>'

I am trying to follow Dreamhost's Rvm/Rails install guide as well as multiple blog posts:
Configuring Rails projects with FastCGI for Dreamhost shared hosting
RAILS 4.0.0 WITH RUBY 2.0 ON A DREAMHOST SHARED SERVER
I am using rvm => 1.26.11, ruby => 2.2.0, rails 4.2.2 successfully and have even tried ruby 2.0.0. I have tried to point all of my env_vars to the proper place but I am not 100% sure the $PATH var is setup properly.
I am using the bundler gem to install my gems and have require 'fcgi' inside of the Gemfile. Also I have removed the Gemfile.lock file and tried to run bundle install again. I thought maybe ruby-2.2.0 is causing problems but ruby-2.0.0 produced the same result & RAILS 4.0.0 WITH RUBY 2.0 ON A DREAMHOST SHARED SERVER clearly shows it working with ruby-2.0.0
dispatch.fcgi
#!/pathtorvm/.rvm/rubies/ruby-2.2.0/bin/ruby

# Dreamhost clears environment variables when calling dispatch.fcgi, set again
ENV['RAILS_ENV'] = 'production'
ENV['HOME'] ||= `echo ~`.strip
ENV['GEM_HOME'] = File.expand_path('~/.gems')
ENV['GEM_PATH'] = File.expand_path('~/.gems')
require 'fcgi'
require '/pathtoapplication'sfile/config/boot.rb'
require '/pathtoapplication'sfile/config/environment.rb'

class Rack::PathInfoRewriter
        def initialize(app)
                @app = app
        end

        def call(env)
                env.delete('SCRIPT_NAME')
            parts = env['REQUEST_URI'].split('?')
            env['PATH_INFO'] = parts[0]
            env['QUERY_STRING'] = parts[1].to_s
            @app.call(env)
        end
end

#Rack::Handler::FastCGI.run Rack::PathInfoRewriter.new(ApplicationNamefoundin~../config/application.rb::Application)

A: The reason is because I am using rvm. In dispatch.fcgi
ENV['GEM_HOME'] = File.expand_path('~/.gems')
ENV['GEM_PATH'] = File.expand_path('~/.gems')

should be instead (notice /gems/ not /.gems/ -it will default to Dreamhost's ruby instead of my custom install)
ENV['GEM_HOME'] = File.expand_path('~/.rvm/gems/ruby-2.2.0')
ENV['GEM_PATH'] = File.expand_path('~/.rvm/gems/ruby-2.2.0')

Thanks Dreamhost for the help

A: The above actually did not help me at all. I had to add this:
require 'rubygems'
Gem.clear_paths
require 'fcgi'


text:
Q: How to read one drive file using node,js? I want to read one drive file using Azure OAuth 2.0 in node.js using passport  strategy for Azure Ad 2.0 please help me out with precise solution. I  have tried reading the microsoft blog  "https://learn.microsoft.com/en-us/onedrive/developer/rest-api/resources/drive?view=odsp-graph-online" it didn't help me though any other way to read the file form one drive using node.js will work for me.
Thank you soo much for your generous replies.


text:
Q: Why was set theory inadequate as a foundation to the emerging new fields and why category theory isn't? I'm reading this Wikipedia article on the foundations of mathematics, in the end of the this topic, there is:

Toward the middle of the 20th century it turned out that set theory (ZFC or otherwise) was inadequate as a foundation for some of the
  emerging new fields, such as homological algebra, and category theory
  was proposed as an alternative foundation by Samuel Eilenberg and
  others.

So why was set theory inadequate as a foundation to the emerging new fields and why category theory isn't?

A: It is not that set theory is inadequate for some aspects of homological algebra, but rather that the language provided by category theory is very powerful and very expressive for the purposes of some areas in mathematics, in particular homological algebra. Logically speaking set theory is perfectly adequate since all of homological algebra can be stated in $ZFC$. But, just like some programming languages are better suited for certain tasks then others (but ultimately they are all equivalent to machine code) so is it in mathematics that the choice of base language may be suited to certain things more than to others.
Traditional set theory, since Cantor, serves as a very rigorous foundations and provides a strong and consistent common language to discuss mathematics. But, it is centered on sets and so everything in set theory is (warning: getting into philosophy now) static. Even the notion of a function as a relation satisfying a condition is a very static view of what a function is.
In category theory in (philosophical) contrast the emphasis is on the morphisms. These are the undefined terms and the resulting language is very powerful in expressing the interrelations between structures and between constructions in mathematics.
This does not say that one is good and the other is bad or that one is adequate and the other is not. It is to say that for certain things one formalism may be better suited than the other. Without a doubt the category theory formalism is superior when considering homological algebra (or algebraic topology more generally). In other areas of mathematics (such as, to the best of my knowledge, combinatorics) there seems to be little to gain from the categorical formalism.
Now, it was discovered that category theory can be used also as a foundation for logic and there are many differences between categorical logic and classical logic. Here again one formalism may be better suited than another, depending on the purpose. For instance, it would seem that for constructive and intuitionistic logic topos theory provides a very natural setting, more so than classical set theory would. For classical logic it is debatable how much merit there is in adopting the topo theoretic approach. Classical techniques such as Cohen forcing can be understood quite nicely via topos theory but one may argue that the insight provided is not significant enough to justify abandoning standard techniques for new ones. It's a matter of taste.
Particularly in homology theory a language that allows one to easily speak of processes, processes between processes, and comparisons between such is crucial. Everything can be stated in $ZFC$ but than one would not see the forest for the trees (or rather one would not see the structure for the objects). When the language talks about morphisms and not objects one can ignore the objects and concentrate on the processes and thus starting seeing the structure.


text:
Q: Syntax Error JSON.parse ajax.responsetext (Spring,jquery,ajax,gson) I am using Netbeans & spring framework4.0.1,without annotation only normal model&view
When i try to send a JSON to the jsp page & using ajax function call back , i am unable to parse the response text, gives me this error
"SyntaxError: JSON.parse: unexpected character at line 12 column 1 of the JSON data"
This is the controller code
 public ModelAndView contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
            ModelAndView mv = new ModelAndView("createsettings");
           List<Content> contents = new ArrayList<>();
     //       JSONObject obj = new JSONObject();
           try {
             DriverManagerDataSource dataSource;
            dataSource = (DriverManagerDataSource)this.getBean("dataSource",hsr.getServletContext());
            this.cn = dataSource.getConnection();
                 Statement st = this.cn.createStatement();
                 String objectiveid = null;
                    objectiveid = hsr.getParameter("seleccion3");
              ResultSet rs1 = st.executeQuery("SELECT name,id FROM         public.content where public.content.id IN (select public.objective_content.content_id from public.objective_content where public.objective_content.objective_id = "+objectiveid+")");

           while (rs1.next())
            {
     Content eq = new Content();
     contents.add(eq);
//   obj.put("name", rs1.getString("name"));

            }

        } catch (SQLException ex) {
            System.out.println("Error leyendo contents: " + ex);
        }
       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       String json = gson.toJson(contents);
       hsr1.setContentType("application/json");

//      System.out.print(json);
//      json = json.replaceAll("\n", "");
//      json = json.trim();
//      json = json.substring(1,json.length()-1);
//      json = json.replace("\\","");
       mv.addObject(json);
        return mv;
    }

When i debug json that i am returning has this value
[
  {
    "name": "newspaper"
  },
  {
    "name": "novel"
  }
]
Below is the JSP code
function comboSelectionObjective()
            {
                if (window.XMLHttpRequest) //mozilla
                {
                    ajax = new XMLHttpRequest(); //No Internet explorer
                } else
                {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                }

                ajax.onreadystatechange = funcionCallBackContent;
             var seleccion3 = document.getElementById("objective").value;
                ajax.open("GET", "createsetting.htm?select=contentlistObjective&seleccion3=" + seleccion3, true);
                ajax.send("");
}
function funcionCallBackContent()
            {
                if (ajax.readyState === 4) {
                    if (ajax.status===200){
                   var data =JSON.parse(ajax.responseText);
                 console.log(data);
                 }

i am using gson library, i used before it Json simple but it gave exactly the same error
also i tried to replace all escape characters and did not work either
Is the problem that i am not using annotations?
Appreciate your help

A: You need to return the json string instead of a ModelAndView object.
When calling the method addOjbect at the ModelAndView object what you are doing is add or overwrite an attribute to the model.
ModelAndView api
Returning the ModelAndView you are returning basically a string with the view name you want to show back, so you are returning a html page, not a json object.
What you need to do is return a json string. So it should be something like:
@ResponseBody
public String contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {

  .... your code

  hsr1.setContentType("application/json");

  //You should double check before returning. Just an example.
  return gson.toJson(contents);
}

Mapping the response body with the @ResponseBody annotation

The @ResponseBody annotation [...] can be put on a method and
  indicates that the return type should be written straight to the HTTP
  response body (and not placed in a Model, or interpreted as a view
  name).

If you do not want to use any anotation at all and go with the old fashioned way, then you have to put the json content directly in the response output. Something like:
String json = new Gson().toJson(contents);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

I hope you get the idea.


text:
Q: Optional related paths with neo4j and cypher on a more complex MATCH statement I have a query which is going over a graph of companies, groups, watchlists and members. See the gist of dummy data in geoff format for the data in the database. I've also setup a console neo4j for anyone to play with.
The aim of the query is to get a list of groups as well as the number of members (a member is a generic term for a person or a company) that have a relationship with the group and its related watchlists.
With the query below I'm getting the correct alert numbers but I'm missing "Empty group" because it doesn't have any members or watchlists. I've tried to make various relationships optional but it ends up getting the count of alerts wrong because it's using watchlists that are related to the group. I've tried countless ways of writing the query but just can't get around the problem.
START company=node(233), group=node:node_auto_index("_type:group")
MATCH company-[:OWNS]->group-[?:LINKED_TO]->watchlist-[:WATCHING|APPOINTMENT*1..2]-member<-[:WATCHING]-group
RETURN group, COUNT(DISTINCT(member)) as alerts
ORDER BY group.name

Ideally I'd like to make the entire path segment which connects a group to members and then onto watchlists as optional however I can't find out how to do that in the docs or it's just not possible. Is there any other way around this other than doing two queries?
The correct results are that the groups and alerts should be:
Big Dot Coms, 1
Big Hitters, 4
Empty group, 0
Old CEOs, 1

A: I hope i understood correctly, but i think this is what you are looking for:
START company=node:node_auto_index("name:\"Finance Ltd\""), group=node:node_auto_index("_type:group")
MATCH company-[:OWNS]->group-[?:WATCHING]->member,group-[?:LINKED_TO]->watchlist
WITH group, member, watchlist
MATCH watchlist-[:WATCHING|APPOINTMENT*1..2]-member
RETURN group, count(distinct( member))
ORDER BY group.name

Basically you can use the WITH keyword to gradually build up your query. Firstly get all group<->member pairings including non existing ones. Then optionally match in watchlists and then use a final match to apply your condition and return the results.

A: i'm afraid this will never be possible with cypher, because of the traversal pattern :
- you want to count empty groups, this means that there is no node member. imagine this simple backtrack: as soon as the search algorithm has no more node to step into, it simply returns one step back. since there is no node member the match pattern will never match the whole pattern company-[:OWNS]->group-[?:LINKED_TO]->watchlist-[:WATCHING|APPOINTMENT*1..2]-member<-[:WATCHING]-group but only company-[:OWNS]->group-[?:LINKED_TO]->watchlist. thus, when the match pattern is not found, there is also no data in the result.
-i suggest to finish the match pattern at the counted nodes, i.e. something like company-[:OWNS]->group-[?:LINKED_TO]->watchlist-[:WATCHING|APPOINTMENT*1..2]-member. than you may get the zero in the count result. i tried to play with the console but it seems it does not have any empty group in its data, so i can't create the final query for you.


text:
Q: Data not getting saved in database Here is my bean.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- Turn on AspectJ @Configurable support -->

<context:spring-configured />
<context:property-placeholder location="classpath*:*.properties" />
<context:component-scan base-package="your.intermedix"/>
<context:annotation-config/>

<!-- Turn on @Autowired, @PostConstruct etc support -->
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>your.intermedix.domain.Contact</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"/>
        <property name="username" value="monty"/>
        <property name="password" value="indian"/>
    </bean>

    <tx:annotation-driven transaction-manager="txManager"/>

    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
      <property name="sessionFactory" ref="mySessionFactory" />
    </bean>

</beans>

My Service class
package your.intermedix.services;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import your.intermedix.domain.Contact;
import your.intermedix.services.IContact;

@Service
@Transactional
public class ContactSerImpl extends HibernateDaoSupport implements IContact {

        public Contact saveContact(Contact contact) {
            System.out.println(contact);
            getHibernateTemplate().saveOrUpdate(contact);
            return contact;
        }

        public void hello() {
            System.out.println("Hello Guru");
        }
}

My Frontend
package your.intermedix;

import java.util.logging.Logger;

import your.intermedix.domain.Contact;
import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Form;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.Sizeable;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.Window;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Controller;

import your.intermedix.domain.ContactValdiation;
import your.intermedix.services.IContact;

/**
 * The Application's "main" class
 */
@SuppressWarnings("serial")
@Configurable(preConstruction = true)
@Controller
public class MyVaadinApplication extends Application implements Button.ClickListener
{

    @Autowired
    private transient IContact icontact;

    private Window window;
    private Button save = new Button("Save", (ClickListener) this);
    private Button cancel = new Button("Cancel", (ClickListener) this);
    private Contact contact = new Contact();
    private Form form = new Form();
    private BeanItem item = new BeanItem(contact);
    private GridLayout ourLayout;

        public void init(){
            loadForm();
        }

        private void loadForm(){
            window = new Window("InterMedix Application");
            setMainWindow(window);
                final Panel panel = new Panel("Contact Information");
                panel.addStyleName("panelexample");
            // The width of a Panel is 100% by default, make it
            // shrink to fit the contents.
                panel.setWidth(Sizeable.SIZE_UNDEFINED, 0);
                form.setWriteThrough(false);
                form.setInvalidCommitted(false);
                form.setImmediate(true);
                form.setFormFieldFactory(new ContactValdiation());
                form.setRequired(true);
                form.setItemDataSource(item);
                form.setVisibleItemProperties(new Object[] {"name","lastname","email","designation","date","comments"});
                form.setValidationVisibleOnCommit(true);
                form.setFooter(new VerticalLayout());
                // Have a button bar in the footer.
                HorizontalLayout buttons = new HorizontalLayout();
                form.getLayout().addComponent(buttons);
                buttons.addComponent(save);
                buttons.addComponent(cancel);
                panel.addComponent(form);

            window.addComponent(panel);

        }

        public void buttonClick(ClickEvent event) {

            if (event.getSource() == save) {
                try {
                    form.commit();
                    icontact.hello();
                    icontact.saveContact(contact);
                }
                 catch (Exception e)    {

                 }
                }
            }
        }

The Error below:

2011-01-04 21:57:46.331:WARN::Failed startup of context org.mortbay.jetty.plugin.Jetty6PluginWebAppContext@14ce5eb{/sampleproject,file:/C:/projects/sampleproject/src/main/webapp/;file:/C:/projects/sampleproject/target/sampleproject-1.0/;}
      org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myVaadinApplication': Unsatisfied dependency expressed through bean property 'user': No unique bean of type [java.lang.Object] is defined: expected single matching bean but found 15: [org.springframework.context.config.internalBeanConfigurerAspect, org.springframework.beans.factory.config.PropertyPlace
      holderConfigurer#0, contactSerImpl, org.springframework.context.annotation.internalRequiredAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.annotation.internalPersistenceAnnotationProcessor, org.springframework.context.annotation.CommonAnnotationBea
      nPostProcessor#0, mySessionFactory, myDataSource, org.springframework.aop.config.internalAutoProxyCreator, org.springframework.transaction.config.internalTransactionAdvisor, txManager, messageSource, applicationEventMulticaster]
              at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1119)

A: The error you get is caused by the fact that HibernateDaoSupport doesn't autowire SessionFactory by default, so you need to configure injection of SessionFactory explicitly, like this:
@Service @Transactional
public class ContactSerImpl extends HibernateDaoSupport implements IContact {
    @Autowired
    public ContactSerImpl(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }
    ...
}

A: I think you are doing several things multiple times:
This:
<context:annotation-config/>

already includes this:
<!-- Turn on @Autowired, @PostConstruct etc support -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

Remove the <bean> definitions and try again, perhaps that's the reason.
Reference: Annotation-based container configuration

Update: about your new error:
HibernateDaoSupport needs either a HibernateTemplate or a SessionFactory as dependency. You have a SessionFactory, but Spring can't wire it because by default, Spring doesn't autowire properties, so you need to either manually wire the property or set <beans default-autowire="byType"> (if you use byName, you will have to change your SessionFactory bean definition to id="sessionFactory")


text:
Q: Finding shortest snippet in a document for this problem I am trying to find out the minimum length of a string that a certain sequence can be found, e.g. in the string "122321" finding 1 and 3 my code should return index 3 as starting position and index 5 as the ending. The problem I'm having is when there are duplicates, then my position array is overwritten for that position.
What I have so far, given a document to search and a list of terms
for (String s : terms) {
     for (String find : document) {
          if (find.equals(s)) {
              positions[termsIndex] = documentIndex;
           }
           termsIndex++;
      }
      documentIndeX++;
 }

The problem with my algorithm right now is that it rewrites the positions when it encounters something twice. I'm looking for pointers on how to check the snippet I have to make sure it is the minimum, thanks.


text:
Q: scanning from file to create a BT using graph I need to create a binary tree using graph methods and I need to scan the number of nodes, each nodes index and the number of children from a file. I used this code and it keeps giving me an exception what should I do?
ps.(the graph should be an array of pointers to nodes)
#include<iostream>
#include<fstream>
using namespace std;
#define MAX_CHILD 2
struct NODE {
    int child[MAX_CHILD];
    int count_child;
};
void construct_graph(NODE* G[],int num)
{
    int n, index;
    ifstream fp("data.txt", ios::in);
    fp >> n;
    for (int i = 0; i < n; i++)
    {
        fp >> index;

        fp>>G[index]->count_child;
        for (int j = 0; j < G[index]->count_child; j++)
        {
            fp>>G[index]->child[j];
        }
    }
}
void df_visited(NODE *G[], bool visited[], int v, int*nw)
{
    if (visited[v])
        return;
    nw[v] = G[v]->count_child + 1;
    cout << nw[v];
    visited[v] = true;
    for (int i = 0; i < G[v]->count_child; i++)
    {
        df_visited(G, visited, G[v]->child[i], nw);
    }
}
void depth_first_print(NODE *G[], int size,int *nw)
{
    int i;
    bool *visited;
    visited = new bool[size];
    for (i = 0; i < size; i++)
        visited[i] = false;
    for (i = 0; i < size; i++)
    {
        if (!visited[i])
            df_visited(G, visited, i,nw);
    }

}
int main()
{
    NODE **G;
    int num;
    ifstream fp("data.txt", ios::in);
    fp >> num;
    G = new NODE*[num];
    construct_graph(G,num);
    int *node_weight;
    node_weight = new int[num];
    depth_first_print(G, num, node_weight);

    delete[]G;
    return 0;
}


text:
Q: javascript closures and prototypes I thought I have understood the idee of closures, but the following code
behaves surprisingly for me:
function A(x)
{
  this.getX1 = function () { return x; }
  A.prototype.getX2 = function () { return x; }
}
var a1 = new A(1);
var a2 = new A(2);
console.log ('a1.getX1()=%d', a1.getX1 ()); // 1
console.log ('a2.getX1()=%d', a2.getX1 ()); // 2
console.log ('a1.getX2()=%d', a1.getX2 ()); // 2 ???
console.log ('a2.getX2()=%d', a2.getX2 ()); // 2

I could understand if prototype methods behave differently from
instance methods, but this looks like x has become a static variable.
Changing the order of calls does not change results.

A: When you change the prototype you're changing the function for all instances of the given class, including those that already exist.
Therefore when you call...
A.prototype.getX2 = function () { return x; }

You're setting that for the existing a1 instance of A. So effectively you're ending up with the following pseudo code:
<all instances of A>.getX2 = function () {
    return <latest value of x passed to A constructor>;
}

A: The static member here is A.prototype.getX2. The second call to A.prototype.getX2 = function () { return x; } (due to var a2 = new A(2);) replaces the first one. To understand it you can reverse the order of instantiations:
var a2 = new A(2);
var a1 = new A(1);

Then you'll have:
a1.getX1()=1
a2.getX1()=2
a1.getX2()=1
a2.getX2()=1

A: You're defining getX2 twice, each time you create a new A. The result for that function will always be the last X. Considering rewriting your code like this:
function A(x) {

    this.x = x;
    this.getX1 = function() {
        return this.x;
    }
}
A.prototype.getX2 = function() {
    return this.x;
}
var a1 = new A(1);
var a2 = new A(2);
console.log('a1.getX1()=%d', a1.getX1()); // 1
console.log('a2.getX1()=%d', a2.getX1()); // 2
console.log('a1.getX2()=%d', a1.getX2()); // 1
console.log('a2.getX2()=%d', a2.getX2()); // 2

This way, you only define getX2 once and it works as expected.

A: You have written
function A(x)
{
  this.getX1 = function () { return x; }
  A.prototype.getX2 = function () { return x; }
}

This constructor overwrites A.prototype.getX2 each time.
So first
var a1 = new A(1); // This invokes A and adds a function `getX2` to the prototype of `A`which returns `x` that is `1`

var a2 = new A(2); // This invokes A and overwrites the function `getX2` in the prototype of `A` with a function which returns `x` that is `2` now.

So it should be like this
function A(x)
{
  this.getX1 = function () { return x; }
}

A.prototype.getX2 = function () { return this.getX1(); }


text:
Q: Jdiameter S13: Could not process request. Result Code = [3007], Error Message: [null] i am trying to make a diameter S13 Server,
and i have used mobicents dependencies as below :
<dependency>
    <groupId>org.mobicents.diameter</groupId>
    <artifactId>restcomm-diameter-mux-jar</artifactId>
    <version>1.7.0.180</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.mobicents.diameter</groupId>
    <artifactId>jdiameter-api</artifactId>
    <version>1.7.0.180</version>
</dependency>
<dependency>
    <groupId>org.mobicents.diameter</groupId>
    <artifactId>jdiameter-impl</artifactId>
    <version>1.7.0.180</version>
</dependency>

also i have created the client side to send CheckIMEImessage and receive it on the server side and return a response to the client,
but my problem is when i send the message to the server the stack returns this error and the message is not being received on my server application:
ResultCode.APPLICATION_UNSUPPORTED
and a diameter response with this code is returned to the client (diameter response = 3007)
this is the log:
DEBUG 2017-11-29 12:06:55 org.jdiameter.server.impl.PeerImpl$LocalActionConext.receiveMessage:343 - Receiving message in server.
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:379 - In getSingleApplicationId for application id [16777252]
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:381 - Application Ids in this message are:
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:386 - [AppId [Vendor-Id:10415; Auth-Application-Id:16777252; Acct-Application-Id:0]]
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:403 - Returning [AppId [Vendor-Id:10415; Auth-Application-Id:16777252; Acct-Application-Id:0]] as the first application id because its the first vendor specific one found
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:379 - In getSingleApplicationId for application id [16777252]
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:381 - Application Ids in this message are:
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:386 - [AppId [Vendor-Id:10415; Auth-Application-Id:16777252; Acct-Application-Id:0]]
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.parser.MessageImpl.getSingleApplicationId:403 - Returning [AppId [Vendor-Id:10415; Auth-Application-Id:16777252; Acct-Application-Id:0]] as the first application id because its the first vendor specific one found
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.controller.PeerImpl.sendErrorAnswer:677 - Could not process request. Result Code = [3007], Error Message: [null]
DEBUG 2017-11-29 12:06:55 org.jdiameter.client.impl.controller.PeerImpl.sendErrorAnswer:701 - Sending response indicating we could not process request

also i have tried the same implementation using jain-slee and everything works fine, and able to send checkIMEIResponse to the client side ...
please any idea?

A: I have figured it out, my problem was i am creating the ApplicationId without vendor id, like:
ApplicationId applicationId =ApplicationId.createByAuthAppId(16777252L);

solved Like
ApplicationId applicationId =ApplicationId.createByAuthAppId(10415L, 16777252L);

and this issue doesn't occur on jain-slee since it uses Multiplixer, and the multiplixer initiate the connection and handles all the messages...
if anyone needs the jdiameter-config.xml files i can share them here ...


text:
Q: Highlight Search (hls) matches of multiple search terms with different colors Many times when working on code, I search for the occurrences of variables with similar names. For examples, find all matches of var1 and var2 as:
/\<var1\>\|\<var2\>

Now I really like the Highlight Search feature of Vim, b/c once I do the search, all the matching instances pop out in yellow color.
Is there a way to assign different colors to different terms in the search string? That is, all matches of var1 be yellow and of var2 be green?

A: The built-in search cannot do that, but there are plugins that let you use different colors, for example my own Mark plugin. (The plugin page has links to alternative plugins.) Most of these use the matchadd() functionality, ensure that this is globally applied to all windows, and provide a search-like interface through mappings and commands.

A: With the 'hlsearch' option, no, they all have to appear in the same color.  However, you can use the :match feature instead.  For example:
:match TODO /var1/
:2match Type /var2/
:3match Comment /var3/

This, of course, is more cumbersome than straight 'hlsearch' matching, because it requires you to know what syntax coloring groups are already defined, or define your own.  Also, you can only do up to three separate matches this way.  If you need more, you'll have to use matchadd() instead.
See:
:help :match
:help :highlight
:help highlight-groups
:help matchadd()


text:
Q: Why does zipWith.zipWith work? I am implementing a function combine :: [[a]] -> [[b]] -> (a -> b -> c) -> [[c]] which given two 2D lists, applies a given function f :: a -> b -> c to the entries of the 2D list. In other words:
          [[a, b, c],    [[r, s, t],          [[f a r, f b s, f c t],
combine    [d, e, g],     [u, v, w],   f   =   [f d u, f e v, f g w],
           [h, i, j]]     [x, y, z]]           [f h x, f i y, f j z]]

Now I suspect that combine = zipWith . zipWith, because I have tried it out and it is giving me the intended results, e.g.
(zipWith . zipWith) (\x y -> x+y) [[1,2,3],[4,5,6]] [[7,8,9],[10,11,12]]

gives the expected result [[8,10,12],[14,16,18]], but I cannot understand why this works, because I don't understand how the type of zipWith . zipWith turns out to be (a -> b -> c) -> [[a]] -> [[b]] -> [[c]].
Is (.) here still carrying out the usual function composition? If so, can you explain how this applies to zipWith?

A: To infer the type of an expression such as zipWith . zipWith, you can simulate the unification in your head the following way.
The first zipWith has type (a -> b -> c) -> ([a] -> [b] -> [c]), the second (s -> t -> u) -> ([s] -> [t] -> [u]) and (.) has type (m -> n) -> (o -> m) -> (o -> n).
For it to typecheck, you need:

*

*m = (a -> b -> c)

*n = ([a] -> [b] -> [c])

*o = (s -> t -> u)

*m = ([s] -> [t] -> [u]) => a = [s], b = [t], c = [u] because of the first constraint

Then the returned type is o -> n which is (s -> t -> u) -> ([a] -> [b] -> [c]) from the constraints and going one step further (s -> t -> u) -> ([[s]] -> [[t]] -> [[u]]).

A: Another way of seeing it is that lists with the zipping operation form an Applicative, and the composition (nesting) of Applicatives is still Applicative:
λ import Control.Applicative
λ import Data.Functor.Compose
λ let l1 = ZipList [ZipList [1,2,3], ZipList [4,5,6]]
λ let l2 = ZipList [ZipList [7,8,9], ZipList [10,11,12]]
λ getCompose $ (+) <$> Compose l1 <*> Compose l2
ZipList {getZipList = [ZipList {getZipList = [8,10,12]},
                       ZipList {getZipList = [14,16,18]}]}

The ZipList newtype is required because "bare" lists have a different Applicative instance, which forms all combinations instead of zipping.

A: Yes, . is the normal function composition operator:
Prelude> :type (.)
(.) :: (b -> c) -> (a -> b) -> a -> c

One way to look at it is that it takes an a value, first calls the a -> b function, and then uses the return value of that function to call the b -> c function. The result is a c value.
Another way to look at (zipWith . zipWith), then, is to perform an eta expansion:
Prelude> :type (zipWith . zipWith)
(zipWith . zipWith) :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]

Prelude> :t (\x -> zipWith $ zipWith x)
(\x -> zipWith $ zipWith x)
  :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]

Prelude> :t (\x -> zipWith (zipWith x))
(\x -> zipWith (zipWith x))
  :: (a -> b -> c) -> [[a]] -> [[b]] -> [[c]]

The type of zipWith itself:
Prelude> :type zipWith
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

So, in the above lambda expression, x must be (a -> b -> c), and hence zipWith x must have the type [a] -> [b] -> [c].
The outer zipWith also needs a function (a1 -> b1 -> c1), which matches zipWith x if a1 is [a], b1 is [b], and c1 is [c].
So, by replacement, zipWith (zipWith x) must have the type [[a]] -> [[b]] -> [[c]], and therefore the type of the lambda expression is (a -> b -> c) -> [[a]] -> [[b]] -> [[c]].


text:
Q: Quantization on Lagrangian submanifold I am reading a paper by Karasev and quite confused with the abstract definition of quantization.
To begin with, we define a map from the phase space $\mathbb{R}^n_x\times\mathbb{R}^n_p$ to $\mathbb{C}^n$ by
$$
\mathcal{Z}:(x,p)\to x+ip.
$$
Let $\Lambda$ be a Lagrangian submianifold of the phase space and $T\Lambda^{\mathbb{C}}$ the complexification of its tangent bundle.
Then, the restriction of the differential
$$
d\mathcal{Z}:T\Lambda^{\mathbb{C}}\to\mathbb{C}^n
$$
is nondegenerate.
My first question is how to understand $T\Lambda^{\mathbb{C}}$. Since the tangent bundle $T\Lambda$ contains all tangent space of $\Lambda$, then we complexify these linear spaces. But is there any manifold structure for $T\Lambda^{\mathbb{C}}$?
Is it sufficient to prove that $d\mathcal{Z}$ is nondegenrate for each $(x,p)\in\Lambda$? Can we represent $d\mathcal{Z}$ in the matrix form by using the Catesian basis of the phase space and the projection map to $\Lambda$?
Next, we define two functions
$$
\mathcal{X}( \alpha, \eta)=X( \alpha)- id \mathcal{Z}( \alpha)^{-1*} \eta,\quad
\mathcal{P}( \alpha, \eta)=P( \alpha)+d \mathcal{Z}( \alpha)^{-1*} \eta,
$$
where
$$
\alpha\in \Lambda,\quad \eta\in T^*_ \alpha \Lambda^{\mathbb{C}},\quad X(\alpha)+iP(\alpha)=\mathcal{Z}(\alpha).
$$
Let $d\sigma$ be a smooth measure on $\Lambda$. For a differential operator $A$, we define its transpose with respect to the measure by $A^\sigma$.
Then we can define the quantization of $X(\alpha)$ and $P(\alpha)$ by an ordered calculus.
$$
\hat{\mathcal{X}}=\mathcal{X}( \alpha^{(2)},-\frac{ih}{2}(d^{(1)}-{d^{ \sigma}}^{(3)})),\quad
\hat{\mathcal{P}}=\mathcal{P}(\alpha^{(2)},-\frac{ih}{2}(d^{(1)}-{d^{ \sigma}}^{(3)})).
$$
The index in the () refers to the order of operator.
I think that this kind of formulation is a generalizaiton of Weyl quantization. But I hope to express it in a more concrete way.
I still have several questions.
First, since the differential operator $d$ maps $n$-form to $n+1$-form, is $d^{\sigma}$ maps $n+1$-form to $n$-form? If so, how can we sum them up?
Second, is there any other way to define the quantized operator $\hat{\mathcal{X}}$ and $\hat{\mathcal{P}}$ by using coordinate chart of $\Lambda$?
Is there any reference about this topic?
I am new to quantization theory and the topics of differential geometry, especially with complex manifold.
Any suggestion will be appreciated!
Thanks in advance.


text:
Q: Capistrano deploy:assets:precompile failed on rails 5 I'm getting error on running this tasks:
Tasks: TOP => deploy:assets:precompile
Error:
The deploy has failed with an error: Exception while executing as deployer@**.**.**.***: rake exit status: 1

Here is my Capfile:
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/nginx'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'capistrano/rvm'
require 'capistrano/rails'
require 'capistrano/rails/db'
require 'capistrano/rails/console'
require 'capistrano/upload-config'
require 'sshkit/sudo'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

This capfile running on Rails 4. I got the error when I migrated to rails 5.

A: This solved my error: My capfile now looks like this
require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/nginx'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
require 'capistrano/rvm'
require 'capistrano/rails/migrations'
require 'capistrano/rails/db'
require 'capistrano/rails/console'
require 'capistrano/upload-config'
require 'sshkit/sudo'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
I removed this line for asset compilation
 require 'capistrano/rails
And replaced to
 require 'capistrano/rails/migrations


text:
Q: How to load data in sqflite database? Database database = await openDatabase(
    dbPathWithDatabase,
    version: 1,
    onCreate: (Database database, int version) async {
    print("\n\nCalling database on create\n\n");

    ByteData data = await rootBundle.load(join("assets", "database.db"));
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    print(bytes);
    await new File(dbPathWithDatabase).writeAsBytes(bytes);
  },
);

The above code is not copying the data to my database. But the database is created successfully.
database.db already exist in assets folder and i want to copy all the data from it.
Here i am calling it from openDatabase which cause the problem.
I can move the code above openDatabase. But i want to know the correct way to populate the data


text:
Q: Magento - robots.txt may be blocking URLs on Google Webmaster Tools Basically my clients Magento website on Googles Webmaster Tools is showing some really odd results and we've noticed, that on the Indexed Status page we have 1,911 pages indexed. Now this bit seems correct, but when we click the Advanced tab it shows we have 6,947 URLs blocked. Now the question I need to ask is, how is there 6,947 URLs blocked, when the website only has around 1,911 pages indexed?
Now I read somewhere that the blocked URLs might be duplicated images that are within Magento. To me this makes sense as we do have a lot of duplicated images in our system, but I'm unsure if this is the cause of the blocked URLs.
Another problem might be down to the robots.txt file itself. So I decided to look into the file and everything looked fine, but each line such as 'Disallow: /404/' might be pointing in the wrong direction.
The clients website is based within the root of the server, so within the 'public_html' section of the website and I think the '/404/' section might be the root. So would I have to add the website folder name to the beginning of each line within the robots.txt file such as: /[Folder_Name]/404/?
Any help figuring this out would be greatly appreciated, I feel like I've hit a wall. I think the Magento version is 1.5 if that could help.
Thanks for the help again.
ROBOTS.TXT FILE CODE
User-agent: *

Allow: /
Sitemap: http://www.websitename/sitemap.xml

# Directories
Disallow: /404/
Disallow: /app/
Disallow: /cgi-bin/
Disallow: /downloader/
Disallow: /includes/
Disallow: /js/
Disallow: /lib/
Disallow: /magento/
Disallow: /pkginfo/
Disallow: /report/
Disallow: /skin/
Disallow: /stats/
Disallow: /var/
# Paths (clean URLs)
Disallow: /index.php/
Disallow: /catalog/product_compare/
Disallow: /catalog/category/view/
Disallow: /catalog/product/view/
Disallow: /catalogsearch/
Disallow: /checkout/
Disallow: /control/
Disallow: /contacts/
Disallow: /customer/
Disallow: /customize/
Disallow: /newsletter/
Disallow: /poll/
Disallow: /review/
Disallow: /sendfriend/
Disallow: /tag/
Disallow: /wishlist/
# Files
Disallow: /cron.php
Disallow: /cron.sh
Disallow: /error_log
Disallow: /install.php
Disallow: /LICENSE.html
Disallow: /LICENSE.txt
Disallow: /LICENSE_AFL.txt
Disallow: /STATUS.txt
# Paths (no clean URLs)
Disallow: /*?p=*&
Disallow: /*?SID=
Disallow: /*?invis=
Disallow: /*?tag=
Disallow: /*?osCsid=
Disallow: /*?manufacturers_id=
Disallow: /*?currency=

A: How your server handles folders doesn't matter.
If your robots.txt is accessible from http://example.com/robots.txt, a rule like Disallow: /404/ will block

*

*http://example.com/404/

*http://example.com/404/foo

*http://example.com/404/foo/bar

*etc.

Also note that you must not have line breaks in a record, so this
User-agent: *

Allow: /
Sitemap: http://www.websitename/sitemap.xml

# Directories
Disallow: /404/

should be:
User-agent: *
Allow: /
Sitemap: http://www.websitename/sitemap.xml
# Directories
Disallow: /404/

And it seems that you don't need Allow: / (it's not part of the original robots.txt specification, but even for parsers that understand Allow, it's the default that anything is allowed which is not disallowed).

Now the question I need to ask is, how is there 6,947 URLs blocked, when the website only has around 1,911 pages indexed?

I can't follow you here. While Google may still index but not crawl blocked URLs, it's not the case that this happens for all blocked URLs. So the number of indexed URLs wouldn't typically include all blocked URLs. As Google is not allowed to visit/crawl blockd URLs, it can't possibly know if or how many of those URLs exist. Google learns about them when finding links to these URLs (from within your site as well as from external sites).
So if there were 100 links to different URLs whose paths start with /poll/, Google might list these 100 URLs as blocked.

A: It is likely that your sitemap is conflicting with the robots.txt file.
Google tries to index everything that is in the sitemap.xml file, but it sees that it cannot index the pages that are blocked by the robots.txt file.
In my case www.workwearwebshop.nl, the sitemap contained pages starting with /catalog/product/view that were blocked by robots.txt.
If you comment out that line in robots.txt Google can spider these products.
Problem that remains is that magento should have better url's than these (starting with the category name instead of /catalog/product/view)


text:
Q: Passing complex types to a GET operation I use System.Net.Http.HttpClient to comunicate with my Web Api. But now I have the problem to pass a complex type with a GET method.
With POST I can do it like
Dim Client As New System.Net.Http.HttpClient()
Client.PostAsJsonAsync(Me.BaseUrl & "/api/my", new With { .Id = 5, ... })

Is there a similar possibility to do it with GET?

A: I'd question whether GET is the right verb here considering you need to pass a complex type, it sounds like it would be better served as a POST.
However, if you have to use a GET then you can either

*

*Embed the parameters in the URL e.g. /api/my?field1=1&field2=2&field3=3...

*Embed the data in a cookie / custom header