text:
Q: Convert Mat to vector  and Vector to mat in opencv i want to Convert Mat to vector  and Vector to mat in opencv .
my code :
     void mat_to_vector(Mat in,vector<float> &out){

        for (int i=0; i < in.rows; i++) {
             for (int j =0; j < in.cols; j++){
                //unsigned char temp;

                //file << Dst.at<float>(i,j)  << endl;
                 out.push_back(in.at<float>(i,j));
            }
        }

    }
void vector_to_mat(vector<float> in, Mat out,int cols , int rows){
    for (int i=rows-1; i >=0; i--) {
             for (int j =cols -1; j >=0; j--){

                 out.at<float>(i,j) = in.back();
                 in.pop_back();
                //file << Dst.at<float>(i,j)  << endl;
                // dst_temp.push_back(Dst.at<float>(i,j));
            }
        }
}

Above codes are slow.
are there  faster solutions?

A: I think my code will be useful for you:
// Generate some test data
int r=3;
int c=3;
Mat M(r,c,CV_32FC1);
for(int i=0;i<r*c;++i)
{
    M.at<float>(i)=i;
}
// print out matrix
cout << M << endl;

// Create vector from matrix data (data with data copying)
vector<float> V;
V.assign((float*)M.datastart, (float*)M.dataend);

// print out vector
cout << "Vector" << endl;
for(int i=0;i<r*c;++i)
{
    cout << V[i] << endl;
}

// Create matrix from vector

// Without copying data (only pointer assigned)
//Mat M2=Mat(r,c,CV_32FC1,(float*)V.data());

// With copying data
Mat M2=Mat(r,c,CV_32FC1);
memcpy(M2.data,V.data(),V.size()*sizeof(float));

// Print out matrix created from vector
cout << "Second matrix" << endl;
cout << M2 <<endl;
// wait for a key
getchar();

A: This is how I do it. The first function is inspired by https://stackoverflow.com/a/26685567 . The output of VectorToMat is in CV
_8U.
void MatToVector(const Mat& in, vector<float>& out)
// Convert a 1-channel Mat<float> object to a vector.
{
if (in.isContinuous()) { out.assign((float*)in.datastart, (float*)in.dataend); }
                else {
                for (int i = 0; i < in.rows; ++i)
                { out.insert(out.end(), in.ptr<float>(i), in.ptr<float>(i) + in.cols); }
                }     return;
}

void VectorToMat(const vector<float>& in,  Mat& out)
{
vector<float>::const_iterator it = in.begin();
MatIterator_<uchar> jt, end;
jt = out.begin<uchar>();
for (; it != in.end(); ++it) { *jt++ = (uchar)(*it * 255); }
}


text:
Q: Container lockdown I was reading about LXC vs OpenVZ and was wondering if this issue has already been solved in more recent updates:

OpenVZ has done quite a good job at this, but LXC still has issues
  here. Even with AppArmor enabled, in Ubuntu you still have access to
  dmesg from the guests and /proc/kcore and /proc/sysrq-trigger are
  still accessible, so a root user in a guest VM could easily restart
  the host machine. Improvements are planned for Ubuntu version 13.04.

source: http://www.janoszen.com/2013/01/22/lxc-vs-openvz/

A: By using echo 1 > /proc/sys/kernel/dmesg_restrict you can restrict the dmesg access to the root user of the host. Other users including the root user in the LXC have then no access.

A: To disable access to /proc/kcore:
lxc.cap.drop = sys_rawio
To disable access to dmesg load following file using lxc.seccomp option:

2
blacklist
[all]
syslog errno 1

Works fine for me on LXC-1.0.6, kernel 4.3.0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create random points outside polygons? The tool Create Random Point is able to generate a certain number of points within polygons. I am wondering, given a bounding box, is there any way that I can generate random points outside those polygon?

A: You are going to have to create a donut polygon with the donut hole representing the interior non-point space and some spatial extent representing the bounding area of the polygonal area.

A: Sorry, I just can't resist. Since it is always good to know what is going on under the hood with something like GME, here is a solution in actual R code.
require(sp)
require(rgeos)

# Create example polygon data
x <- readWKT("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))")
y <- readWKT("POLYGON ((3 3, 7 3, 7 7, 3 7, 3 3))")

# Calculate difference in polygon geometries to create null polygon
d <- gDifference(x,y)

# Create random sample in non-null polygon
rs <- spsample(d, 20, type="random")

# Plot results
plot(d, col="red")
  plot(rs,pch=19,col="black",add=TRUE)

This approach is likely very different than how GME does this but is using native R sp spatial classes and a fairly new topology library making the code very efficient. This also gives an example that can easily be wrapped in a for loop.

A: Personally I do not like the random point algorithm in ArcGIS. Alternatively, use Geospatial Modelling Environment's (GME) genrandompnts function. You will be able to identify specific polygons where random points will be excluded (see highlighted area in attached .jpg).  Best of all this software is free.

GME provides you with a suite of analysis and modelling tools, ranging
  from small 'building blocks' that you can use to construct a
  sophisticated work-flow, to completely self-contained analysis
  programs. It also uses the extraordinarily powerful open source
  software R as the statistical engine to drive some of the analysis
  tools. One of the many strengths of R is that it is open source,
  completely transparent and well documented: important characteristics
  for any scientific analytical software.


text:
Q: How to return 0 for rows which don't exisit I have the following query
SELECT `Product`,`Coverlvl`, `Datesold`, Count(*) AS `number`
FROM Policyinfo
WHERE `Product` = 'Outbacker-IDOL' && `Coverlvl` ='Gold' && `Datesold` >=
     ('2016-06-01')&& `Datesold` < ('2016-07-01') GROUP BY `Product`, `Coverlvl`

It returns data for only one day.  When I need is for the other days in the Month to return 0

A: Remove groupby because of it you get data for just one entry
 SELECT `Product`,`Coverlvl`, `Datesold`, Count(*) AS `number`
    FROM Policyinfo
    WHERE `Product` = 'Outbacker-IDOL' && `Coverlvl` ='Gold' && `Datesold` >=
         ('2016-06-01')&& `Datesold` < ('2016-07-01')

and for "0" wherever you need this you can use "case"
example of case is
SELECT
    customerName, state, country
FROM
    customers
ORDER BY (CASE
    WHEN state IS NULL THEN country
    ELSE 0
END);


text:
Q: Is it possible to get difference of count of two different activities in google analytics? I'm tracking two different events into GoogleAnalytics from my iOS app. I want to get the difference between these two events.

difference = sum of(Event A) - sum of (Event B).

Please guide me through the proper solution.

A: No, that's not possible. You would have to export the data (e.g via the API, or Google Apps Script, or simply using the export to spreadsheet function in GA) and calculate the difference e.g with a spreadsheet formula.
The closest you will get in the interface is via segmentation (something like "show uniqe events for EventA for users that do not also have EventB"). But as a simple number in the reports, no. GA does not do user defined calculations in the interface.


text:
Q: How close can I get C# to the performance of C++ for small intensive tasks? I was thinking about the speed difference of C++ to C# being mostly about C# compiling to byte-code that is taken in by the JIT compiler (is that correct?) and all the checks C# does.
I notice that it is possible to turn a lot of these functions off, both in the compile options, and possibly through using the unsafe keyword as unsafe code is not verifiable by the common language runtime.
Therefore if you were to write a simple console application in both languages, that flipped an imaginary coin an infinite number of times and displayed the results to the screen every 10,000 or so iterations, how much speed difference would there be? I chose this because it's a very simple program.
I'd like to test this but I don't know C++ or have the tools to compile it. This is my C# version though:
static void Main(string[] args)
{
    unsafe
    {
        Random rnd = new Random();
        int heads = 0, tails = 0;
        while (true)
        {
            if (rnd.NextDouble() > 0.5)
                heads++;
            else
                tails++;

            if ((heads + tails) % 1000000 == 0)
                Console.WriteLine("Heads: {0}  Tails:  {1}", heads, tails);
        }
    }
}

Is the difference enough to warrant deliberately compiling sections of code "unsafe" or into DLLs that do not have some of the compile options like overflow checking enabled? Or does it go the other way, where it would be beneficial to compile sections in C++? I'm sure interop speed comes into play too then.
To avoid subjectivity, I reiterate the specific parts of this question as:

*

*Does C# have a performance boost from using unsafe code?

*Do the compile options such as disabling overflow checking boost performance, and do they affect unsafe code?

*Would the program above be faster in C++ or negligably different?

*Is it worth compiling long intensive number-crunching tasks in a language such as C++ or using /unsafe for a bonus? Less subjectively, could I complete an intensive operation faster by doing this?

A: The example given is flawed because it does not show real life usage of both programming languages. Using simple datatypes to measure the speed of a language will not bring anything interesting. Instead, I suggest you create a template class in C++ and compare it with what is possible in C# for class generics. In the end, objects will bring some important results and you will see that C++ is faster than C#. Not to mention that you are comparing a lower level programming language with C#.

Does C# have a performance boost from
  using unsafe code?

Yes, it will have a boost but it is not suggested that you write only code with unsafe. Here is why: Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet. http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx

Would the program above be faster in
  C++ or negligably different?

Yes the program would be slightly faster in C++. C++ is a lower programming language and even faster if you start using the algorithm library (random_shuffle comes to mind).

Is it worth compiling long intensive
  number-crunching tasks in a language
  such as C++ or using /unsafe for a
  bonus? Less subjectively, could I
  complete an intensive operation faster
  by doing this?

It depends on the project...

A: Up to more than 100% of speed - depends a lot on the task, simply said.
More than 100% -  yes, because the just in time compiler knows your processor, and I doubt you actually optimize for your hardware platform ;)
No SSE is a problem if you do matrix operations.
FOr some things with tons of arrays (image manipulation) The array tests kill you, but pointers work (i.e. unsafe code) as they bypass this.
Regarding things like overflow checking - be carefull. As in: in C++ you have the same possibly. If you need overflow checking, the performance issue is not there ;)
I personally would not bother with C++ in most cases. Partially yes, especially when you can benefit from SSE:
So, at the end a lot depends on the NATURE if your calculations.


text:
Q: Regex is not working with Linq to Sql i have the following code
Regex R = new Regex("my regex");
var q = from c in db.tble1
        where R.IsMatch(c.text)
        select c;

and while debugging i saw in the q result this message

Method 'Boolean IsMatch(System.String)' has no supported translation to SQL."}    System.SystemException {System.NotSupportedException}

so what have i done wrong ?
Edit:I learned that the method has no supported translation to SQL
but how to solve this

A: Regex has no supported translation to SQL. The error says it all. You can't use regex in LINQ to SQL.
Try using a like or substring comparison instead:
var q = from c in db.tble1
        where c.text.StartsWith("x") && c.text.Substring(2, 1) == "y"
        select c;

Or, you could perform an in memory regex comparison. You can do this by calling ToList() before using the Regex:
Regex R = new Regex("my regex");
var q = from c in db.tble1.ToList()
        where R.IsMatch(c.text)
        select c;


text:
Q: Using IoC to provide a custom ModelMetadataProvider in MVC3 I'm currently overriding the default ModelMetadataProvider in the Global.asax file using this
ModelMetadataProviders.Current = new RedSandMetadataProvider(ModelMetadataProviders.Current);

and this works perfectly. But I'd like to use the IDependancyResolver feature of MVC3 to let IoC provide the ModelMetadataProvider implementation instead. I'm using StructureMap to do it (Just installed it into the project using NuGet) but for some reason it not behaving as expected.
x.For<ModelMetadataProvider>().Use(new RedSandMetadataProvider(ModelMetadataProviders.Current));

I put a breakpoint on the constructor of RedSandMetadataProvider() and it is getting hit. And I also put a breakpoint on the GetServices() function of the automatically added SmDependencyResolver.cs file to make sure it was IoC that was calling my constructor, and everything seems fine, the constructor gets called on the second page load I think, but it never calls my GetMetadataForProperty() function of my MetadataProvider. Now I KNOW this gets called correcetly when I set it up in the Global.asax, but every time I try to achieve the same result using IoC, I see the constructor called on my class and that's it. I tried adding a .Singleton() to the StrctureMap registration of the type and that causes my constructor to get called much sooner but it still never actually USES the object after it's constructed.
Am I missing something?

A: You need to implement IMvcServiceLocator and call MvcServiceLocator.SetCurrent() to tell MVC to use StructureMap: http://bradwilson.typepad.com/blog/2010/07/service-location-pt2-controllers.html

A: I solved my problem with this issue in another question.
Setting up DependancyResolver in MVC3 using StructureMap for ModelMetadataProvider & ModelValidatorProvider
Please see it if you're encountering problems with this as well.


text:
Q: Cordova iOS 3.6.3+ Issue - [__NSArrayI length]: unrecognized selector Im getting following error in Xcode console:
-[__NSArrayI length]: unrecognized selector sent to instance 0x174236680
*** WebKit discarded an uncaught exception in the webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: <NSInvalidArgumentException> -[__NSArrayI length]: unrecognized selector sent to instance 0x174236680

This causes the webView to stop responding to any touch events though the app remains working properly. For instance I can call a function from Safari web inspector console successfully.
Any ideas?

A: Ok I have found the problem. My fault.
There were wrong count of parameters for navigator.notification.confirm().
Small tip for cordova developers: Use JSON object as parameter for functions, then there will be no need for parameters such as null (because of the correct order and position of multiple parameters).

A: I had the same error in an app for the iPhone. I am porting an app from BlackBerry 10 to iOS. By the way we updated the cordova version.
The cordova API in cordova 4.0.0 has changed or is different on iOS.
In the BB10 app this code is working:
navigator.notification.alert("Test", function() {}, ["Info"]);
On iOS the array had to be removed:
navigator.notification.alert("Test", function() {}, "Info");


text:
Q: jQuery sortable with droppable My fiddle: http://jsfiddle.net/Yc9WY/42/
What you'll see here are two groups, each with 3 droppable containers defined. You can move events from group 1 to group 2, and into any slot. This works just fine.
Once a group is full, I would like to give the user the ability to sort that group by moving events up and down. They should still be able to move the event out of the group if they choose however.
You'll see my commented out code where I began to integrate the sortable library, but am getting odd behavior.
Note: I cannot replace my draggable/dropable with sortable solely. I need explicitly defined droppable areas (3 per group) so that an event can exist in slot 1 and 3 of group 1.
Here's my code
$(document).ready(function() {

// $(".sort").sortable({
//     revert: true
// });

$(".drag").draggable({
    //connectToSortable: ".sort",
    revert: true
    //helper: clone
});

$(".sort").droppable({
    drop: function(event, ui) {

        if (!($(this).children(".drag").size() == 1)) {
            $(this).append(ui.draggable);

            ui.draggable.css({
                left: 0,
                top: 0
            });
        }
    }

});
});

Group 1:

event 1

event 2

Group 2

event 3

event 4

I'm really struggling with this, thanks all!

A: I cracked it :)
Fiddle (and CSS): http://jsfiddle.net/jhogervorst/CPA5Y/
HTML:

Group 1

Item 1

Item 2

Group 2

Item 3

Item 4

JavaScript:
$(".draggable").draggable({
    revert: true,
    revertDuration: 0
});

$(".droppable").droppable({
    activeClass: "active",
    hoverClass: "hover",

    accept: function (draggable) {
        // The droppable (li element).
        var droppable = $(this);

        // The droppable which contains the draggable, i.e., the parent element of the draggable (li element).
        var draggablesDropable = draggable.parent();

        // Is the draggable being dragged/sorted to the same group?
        // => We could just sort it, because there's always enough space inside the group.
        if (droppable.parent().is(draggablesDropable.parent())) {
           return true;
        }

        // Nope, the draggable is being dragged/sorted to another group.
        // => Is there an empty droppable left in the group to which the draggable is being dragged/sorted?
        else if (droppable.parent().find(".draggable").size() < droppable.parent().find(".droppable").size()) {
            return true;
        }

        // Nothing true?
        return false;
    },

    drop: function(event, ui) {
        // The droppable (li element).
        var droppable = $(this);

        // The draggable (span element).
        var draggable = ui.draggable;

        // The droppable which contains the draggable, i.e., the parent element of the draggable (li element).
        var draggablesDropable = draggable.parent();

        // Is the draggable being dragged to it's own droppable?
        // => Abort, there's nothing to drag/sort!
        if (droppable.is(draggablesDropable)) {
            return;
        }

        // Is the draggable being dragged to an empty droppable?
        else if (!droppable.find(".draggable").size()) {
            // Just drop the draggable there.
            droppable.append(draggable);
        }

        // Is the draggable being dragged/sorted to the same group?
        // => We can just sort it, because there's always enough space inside the group.
        else if (droppable.parent().is(draggablesDropable.parent())) {
            // Is the draggable being dragged up?
            if (droppable.parent().find(".droppable").index(draggablesDropable) > droppable.parent().find(".droppable").index(droppable)) {
                // Add the dragged draggable's droppable before the droppable.
                draggablesDropable.insertBefore(droppable);
            }

            // No, the draggable is being dragged down.
            else {
                // Add the dragged draggable's droppable after the droppable.
                draggablesDropable.insertAfter(droppable);
            }
        }

        // Nope, the draggable is being dragged/sorted to another group.
        // => Is there an empty droppable left in the group to which the draggable is being dragged/sorted?
        else if (droppable.parent().find(".draggable").size() < droppable.parent().find(".droppable").size()) {
            // Find the first empty droppable in which the draggable is being dragged/sorted.
            var emptyDroppable = $($.grep(droppable.parent().find(".droppable"), function (item) {
                // Are there draggables inside this droppable?
                // => Return TRUE if not.
                return !$(item).find(".draggable").size();
            })).first();

            // Clone the dragged draggable's droppable before itself, because we need to remember it's position after moving it.
            var draggablesDropableClone = draggablesDropable.clone().insertBefore(draggablesDropable);

            // Is the draggable being dragged above the empty droppable?
            if (droppable.parent().find(".droppable").index(emptyDroppable) > droppable.parent().find(".droppable").index(droppable)) {
                // Add the dragged draggable's droppable before the droppable.
                draggablesDropable.insertBefore(droppable);
            }

            // No, the draggable is being dragged below the empty droppable.
            else {
                // Add the dragged draggable's droppable after the droppable.
                draggablesDropable.insertAfter(droppable);
            }

            // Remove the position of the dragged draggable, because there's still some css left of the dragging.
            draggable.css({"top": 0, "left": 0});

            // Add the first empty droppable before the cloned draggable's droppable. Remove the latter afterwards.
            draggablesDropableClone.before(emptyDroppable).remove();
        }
    }
});


text:
Q: Can we generalize Pythagorean theorem to more than $2$ vectors? In Linear algebra done right: the statement of pythagorean theorem is:
Suppose u and v are orthogonal vectors in V, then $||u+v||^{2}=||u||^{2}+||v||^{2}$
And can we generalize the statement to:
Suppose $u_{1},...,u_{n}$ are orthogonal vectors in V, then $||u_{1}+...+u_{n}||^{2}=||u_{1}||^{2}+...+||u_{n}||^{2}$
If it is true, could someone please tell me how to prove it? If it is false, could someone tell me why?

A: It is true. You can easily prove it by induction.

A: We know it is true for two orthogonal vectors $v, w \in V$.
Then, let $v_1=u_1+\dots+u_{n-1}$, we have
$$||u_1+\dots+u_n||^2=||v+u_n||^2=||v_1||^2+||u_n||^2=||u_1+\dots+u_{n-1}||^2+||u_n||^2$$
because $v_1$ and $u_n$ are orthogonals.
Repeating the argument with $v_2=u_1+\dots+u_{n-2}$ and $u_{n-1}$ to obtain
$$||u_1+\dots+u_n||^2=||v_2+u_{n-1}||^2+||u_n||^2=||u_1+\dots+u_{n-2}||^2+||u_{n-1}||^2+||u_{n}||^2.$$
Iterating this argument we can easily prove the thesis by induction.
You can look here for more details.


text:
Q: Predicate looking for ID that doesn't exist? I have a method like so:
func syncSectors(sectors: [SectorsModel]){

    BackgroundContext.performAndWait {
        //Fetch results from the database
        let matchingSectorRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Sectors")
        //Delete Sector ids
        let deleteSectorIds = sectors.map { $0.ID }.compactMap { $0 }

        matchingSectorRequest.predicate = NSPredicate(format: " !(ANY sector_id IN %@) AND (sector_id != nil)", argumentArray: [deleteSectorIds])

        let batchDeleteRequest = NSBatchDeleteRequest.init(fetchRequest: matchingSectorRequest)
        batchDeleteRequest.resultType = .resultTypeObjectIDs

        // Execute the request to do batch delete and merge the changes to viewContext, which triggers the UI update
        do {
            let batchDeleteResult: NSBatchDeleteResult = try BackgroundContext.execute(batchDeleteRequest) as! NSBatchDeleteResult

            if let deletedObjectIDs = batchDeleteResult.result as? [NSManagedObjectID] {
                NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSDeletedObjectsKey: deletedObjectIDs], into: [Context])
            }

        } catch {
            print("Error: \(error)\nCould not batch delete existing records.")
            return
        }
        //******************** End of Delete Sectors *****************************

        // Insert new SubSectors
        for sector in sectors where !sector.exists {
            _ =  saveSectors(sectors: sectors)
        }

        do {
            // Save all changes on background context
            try BackgroundContext.save()

            Context.performAndWait {
                do {
                    // Saves the data from the background to the main context
                    try Context.save()
                } catch {
                    print("Failure to save context: \(error)")
                }
            }
        } catch {
            print("Error: \(error)\nCould not save new records.")

            BackgroundContext.rollback()

            return
        }

        //******************** End of Insert new Sectors *****************************

        //Update Sectors
        for sector in sectors where !sector.ID.isNilOrEmpty{

            let batchUpdateRequest = NSBatchUpdateRequest.init(entityName: "Sectors")
            batchUpdateRequest.resultType = .updatedObjectIDsResultType
            batchUpdateRequest.predicate = NSPredicate.init(format: "sector_id == %@", sector.ID)

            //Perform the inital update
            batchUpdateRequest.propertiesToUpdate = ["sector_id" :sector.ID, "SECTOR_NAME" : sector.SECTOR_NAME]

            // Execute the request to do batch update and merge the changes to viewContext, which triggers the UI update
            do {
                let batchUpdateResult: NSBatchUpdateResult = try BackgroundContext.execute(batchUpdateRequest) as! NSBatchUpdateResult

                if let UpdatedObjectIDs = batchUpdateResult.result as? [NSManagedObjectID] {
                    NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSUpdatedObjectsKey: UpdatedObjectIDs],
                                                        into: [Context])
                }
            } catch {
                print("Error: \(error)\nCould not batch update existing records.")
                return
            }
            //******************** End of Update Sectors *****************************

        }
    }

}

My app crashes when I reach this point:
if let deletedObjectIDs = batchDeleteResult.result as? [NSManagedObjectID] {
                    NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSDeletedObjectsKey: deletedObjectIDs], into: [Context])
                }
the IDs that I have in my Array are as follows:
Printing description of deleteSectorIds:
▿ 24 elements
  - 0 : "8"
  - 1 : "9"
  - 2 : "11"
  - 3 : "12"
  - 4 : "13"
  - 5 : "14"
  - 6 : "15"
  - 7 : "16"
  - 8 : "17"
  - 9 : "18"
  - 10 : "19"
  - 11 : "20"
  - 12 : "21"
  - 13 : "22"
  - 14 : "23"
  - 15 : "24"
  - 16 : "25"
  - 17 : "27"
  - 18 : "28"
  - 19 : "29"
  - 20 : "30"
  - 21 : "31"
  - 22 : "32"
  - 23 : "33"
And I cant seem to figure out why I am getting this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath ID not found in entity '
when I clearly do not have an ID with the value 7 in my array?
Anyone who can break it down for me whats really going on?
My model is as follows:
import Foundation
import ObjectMapper
enum SectorsModelEnum: String {
case SECTOR_NAME = "SECTOR_NAME"
case ID = "ID"
case SECTOR = "SECTOR"

}
struct SectorsModel: Mappable {
var SECTOR_NAME: String!
var ID: String!
var SECTOR: [SubSectorsModel]!

init?(map: Map) {

}

init(SECTOR_NAME: String, ID: String, SECTOR: [SubSectorsModel] ) {

    self.SECTOR_NAME = SECTOR_NAME
    self.ID = ID
    self.SECTOR = SECTOR

}

init() {
    self.SECTOR = []
    self.SECTOR_NAME = ""
    self.ID = ""
}

mutating func mapping(map: Map) {

    SECTOR_NAME <- map[SectorsModelEnum.SECTOR_NAME.rawValue]
    ID <- map[SectorsModelEnum.ID.rawValue]
    SECTOR <- map[SectorsModelEnum.SECTOR.rawValue]

}

var exists: Bool {
    let fetchRequest = Sectors.sectorsFetchRequest()
    fetchRequest.predicate = NSPredicate(format: "ID == %@", ID )
    var sectors: [Sectors] = []
    do {
        sectors = try Context.fetch(fetchRequest)
    } catch {
        print("Could not fetch data \(error)")
    }
    return sectors.first != nil ? true : false
}

}


text:
Q: Apache HTTPD 2.4 URL Rewrite Rules I've upgraded from Apache 2.2 to 2.4 and all but one type of my URL rewrite rules are working as expected.  It appears that the following rule isn't working.  I removed the IP address for security purposes.
RequestHeader unset Authorization
RewriteEngine On
RewriteRule /xmldb/VATIncidentPoint/(.*)$   http://x.x.x.x:8080/exist/rest/db/VATIncidentPoint/${user2group:%{LA-U:REMOTE_USER}}/$1 [P]
It appears what's happening is that the section including user2group is not getting replaced with the group that the user is a part of.  This results in 2 slashes at the end of the url instead of getting replaced with the group '//'.  Is there a different way to do this in 2.4 than there was in 2.2?
Thanks in advance!

A: The issue was that in the Location block there was 2 require statements.
Require all granted AND Require valid-user
This was causing the REMOTE_USER value to never be looked up and therefore causing nothing to be returned from the map.  Removing 'Require all granted' and leaving 'Require valid-user' solved the issue.


text:
Q: jQuery submit validate post I'm using the standard jQuery validation plugin to validate a form when the user clicks "submit."
After the form is validated, I want it to post data to a database and reveal a "success" message.
The validation part is working fine, but I can't get my two commands to happen. I'm sure I'm missing something obvious.
Here's my code:
<script type="text/javascript">

$("#formname").validate({
        submitHandler: function (form) {

            $.post('https://www.custom.api.url.com', $(this).serialize(), function () {
                    success.show();
                    $('input[type=text]').val('');

                }
            });

</script>

OK, take two. This one isn't working, either:
<script type="text/javascript">

$(document).ready(function(){
                  var success = $('.success');

                           $("#formname").validate( {
                           submitHandler: function(form) {

                           $.post('https://www.custom.api', $(this).serialize(), function(){
                           success.show(); $('input[type=text]').val('');

                                  });
                             });
                  });

</script>

A: Here is your valid code. It looks like that is also your main problem, Invalid syntax.
<script type="text/javascript">
$(document).ready(function(){
    $("#formname").validate({
        submitHandler: function(form) {
            $.post('https://www.custom.api.url.com', $(form).serialize(), function () {
                success.show(); //Undefined
                $('input[type=text]').val('');
            });
        }
    });
});
</script>

$(this).serialize() also has to be replaced with $(form).serialize().
Then additionally success is undefined so there will be another error. But I'm not sure what exactly success should be.
You should use your browsers console to get notified about javascript errors. To validate your javascript you can also use jsHint.


text:
Q: Handling "dyld: lazy symbol binding failed: Symbol not found" error when nm does not find symbol I have a fat (32- and 64-bit) Intel binary called myBinary that fails to run on another workstation running Mac OS X 10.8.2:
$ myBinary
dyld: lazy symbol binding failed: Symbol not found: __ZNSt8__detail15_List_node_base7_M_hookEPS0_
  Referenced from: /usr/local/bin/myBinary
  Expected in: /usr/lib/libstdc++.6.dylib

dyld: Symbol not found: __ZNSt8__detail15_List_node_base7_M_hookEPS0_
  Referenced from: /usr/local/bin/myBinary
  Expected in: /usr/lib/libstdc++.6.dylib

Trace/BPT trap: 5

I compiled it from a Mac OS X 10.8.2 workstation running GCC 4.7.2:
$ gcc --version
gcc (MacPorts gcc47 4.7.2_2+universal) 4.7.2

I ran nm and the symbol is undefined:
$ nm /usr/local/bin/myBinary | grep __ZNSt8__detail15_List_node_base7_M_hookEPS0_
     U __ZNSt8__detail15_List_node_base7_M_hookEPS0_

What did I miss or do wrong when compiling myBinary? I'm not sure what I can do about a missing symbol in /usr/lib/libstdc++.6.dylib — should I have statically compiled the C++ library into myBinary?

A: yeah you have 2 options, either not use libraries that the customer won't have... (you can provide them as a dyld or framework.)
or just statically link the library... this will actually end up being smaller in memory and disk space if your package is only one process, because you can strip symbols that you don't use.

A: Each C++ compiler has its own implementation of Standard C++ Library. Since you're using external compiler (GCC 4.7) its library is not available among standard installations of Mac OS X.
Your only options is to either bundle the library within your app or statically link it.
To bundle the library with the app:

*

*Update install name of the library using install_name_tool

*Ensure your app will find it when needed
E.g. you can put the dylib into .app/Contents/Frameworks, set its install name to @rpath and compile you app with the -rpath @executable_path/../Frameworks.

A: I ran into this same issue when compiling on 10.6 with MacPorts GCC 4.8, and then trying to run my application on a fresh 10.9 install without MacPorts.  Luckily I found your question, and Kentzo's answer steered me in the right direction as to why the problem occurred... but it didn't really provide the solution I was looking for.
First, I'll explain why it runs on your system correctly: MacPorts has provided your system with the version of libstdc++ that GCC 4.7 is providing symbols for, under /opt/local/lib rather than /usr/lib.  Here's what it looks like for me (with GCC 4.8 universal):
$ find /opt/local/lib -name 'libstdc++.*'
/opt/local/lib/gcc48/i386/libstdc++.6.dylib
/opt/local/lib/gcc48/i386/libstdc++.a
/opt/local/lib/gcc48/i386/libstdc++.a-gdb.py
/opt/local/lib/gcc48/i386/libstdc++.dylib
/opt/local/lib/gcc48/i386/libstdc++.la
/opt/local/lib/gcc48/libstdc++.6.dylib
/opt/local/lib/gcc48/libstdc++.a
/opt/local/lib/gcc48/libstdc++.a-gdb.py
/opt/local/lib/gcc48/libstdc++.dylib
/opt/local/lib/gcc48/libstdc++.la
/opt/local/lib/libgcc/libstdc++.6.dylib
/opt/local/lib/libstdc++.6.dylib

And you can see what your application is linking to with otool -L:
$ otool -L myBinary
myBinary:
    /opt/local/lib/libgcc/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.18.0)
    /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 832.0.0)
    /opt/local/lib/libgcc/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.11)

The easiest way to improve portability is -static-libstdc++ -static-libgcc in your final gcc build step (the one that calls the linker).  You need both because dynamic libgcc will bring dynamic libstdc++ binding with it, so it's not enough to simply request static libstdc++.  For a simple application, here's what your gcc line might look like:
g++ -static-libstdc++ -static-libgcc myBinary.cpp -o myBinary

However, according to the gcc man page about linker options, statically linking libgcc can cause problems when handling exceptions across libraries.  I haven't run into issues with it, but you might.
So, to do it Kentzo's way, first you should get the newest install_name_tool from MacPorts so it won't be confused by unknown load commands:
sudo port install cctools +universal

Now, let's change the path so it searches the executable's directory:
/opt/local/bin/install_name_tool -change /opt/local/lib/libgcc/libstdc++.6.dylib '@executable_path/libstdc++.6.dylib'
/opt/local/bin/install_name_tool -change /opt/local/lib/libgcc/libgcc_s.1.dylib '@executable_path/libgcc_s.1.dylib'

Now you just need to distribute these dylibs with the application.  If you're making a .app, copy the dylibs to myBinary.app/Contents/MacOS/.
One final note: If you're having trouble making a good universal binary, it is possible to build the architectures separately (with different compilers and options) and then merge them with lipo:
/usr/bin/g++ -arch i686 -mmacosx-version-min=10.5 -isysroot /Developer/SDKs/MacOSX10.5.sdk myBinary.cpp -o myBinary_32
/opt/local/bin/g++ -arch x86_64 -static-libstdc++ -static-libgcc myBinary.cpp -o myBinary_64
lipo myBinary_32 myBinary_64 -create -output myBinary


text:
Q: React handling api params not showing This is my column.
I need the href from api that contains customers id. I'm currently using reactTable and everything is working fine. But only the params are not handled down when I look inside my console.
Can anyone tell me what's missing?
const columns = [
  {
    Header: '',
    accessor: 'links[0].href',
    filterable: false,
    sortable: false,
    Cell: ({params}) => <Button color="secondary" onClick={()=>deleteCustomer(params)}>Delete</Button>
  }
];

const deleteCustomer = (params) => {
  console.log(params)
};

const getCustomer = () => {
  fetch('https://customerrest.herokuapp.com/api/customers')
    .then(response => response.json())
    .then(data => setCustomer(data.content))
    .catch(err => console.error(err))
};

Here is an example API call:
    {
      "links" : [ {
        "rel" : "self",
        "href" : "https://customerrest.herokuapp.com/api/customers"
      }, {
        "rel" : "profile",
        "href" : "https://customerrest.herokuapp.com/api/profile/customers"
      } ],
      "content" : [ {
        "firstname" : "Mark",
        "lastname" : "Johnson",
        "streetaddress" : "5th Street",
        "postcode" : "23110",
        "city" : "Flintsone",
        "email" : "john@mail.com",
        "phone" : "232-2345540",
        "content" : [ ],
        "links" : [ {
          "rel" : "self",
          "href" : "https://customerrest.herokuapp.com/api/customers/620"
        }, {
          "rel" : "customer",
          "href" : "https://customerrest.herokuapp.com/api/customers/620"
        }, {
          "rel" : "trainings",
          "href" : "https://customerrest.herokuapp.com/api/customers/620/trainings"
        } ]
      }

A: I don't think react-table provides "params" in the callback of Cell option. try to pass the param without curly bracket, and then pick the data that you need
Cell: (params) => <Button color="secondary" onClick={()=>deleteCustomer(params)}>Delete</Button>

A: Pass params in your onClick handle func.:
Cell: ({params}) => <Button color="secondary" onClick={(params)=>deleteCustomer(params)}>Delete</Button>


text:
Q: ng-token-auth not persisting I have a pretty bare-bones application at the moment using ng-token-auth and rails' devise-token-auth.  It is running fine and the $auth methods are working well (for example, logging in).  However, upon page refresh the access-token doesn't persist and doesn't get written to the cookie using ipCookie.
My rails app is forwarding the proper headers as seen below:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, DELETE, PUT, OPTIONS, HEAD
Access-Control-Allow-Origin:http://localhost
Access-Control-Expose-Headers:
Access-Control-Max-Age:0
access-token:XXXXXXXXXXXXXX
Cache-Control:max-age=0, private, must-revalidate
client:nYMXLxnuO7BIGZkdXkZ_Xg
Connection:Keep-Alive
Content-Type:application/json; charset=utf-8
Date:Sat, 09 May 2015 21:41:56 GMT
ETag:"c16291f5079691a2528d5a7876627ede"
expiry:1431294116
Keep-Alive:timeout=5, max=99
Server:Apache/2.4.10 (Unix) PHP/5.5.20
token-type:Bearer
Transfer-Encoding:chunked
uid:tester53@mailinator.com
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:2b224904-944c-48f7-aa4e-d0407e26e893
X-Runtime:0.230242
X-XSS-Protection:1; mode=block

But when it gets run through the updateHeadersFromResponse method of ng-token-auth the headers are returning null-- specifically in lines 588 of ng-token-auth.js
updateHeadersFromResponse = function($auth, resp) {
  var key, newHeaders, val, _ref;
  newHeaders = {};
  _ref = $auth.getConfig().tokenFormat;
  for (key in _ref) {
    val = _ref[key];
    if (resp.headers(key)) {
      newHeaders[key] = resp.headers(key);
    }
  }
  if (tokenIsCurrent($auth, newHeaders)) {
    return $auth.setAuthHeaders(newHeaders);
  }
};

Has anyone encountered this?  Why would the header not be passed to this $httpProvider method?

A: I found the answer in this post Angular.js saying custom HTTP response header is null
I was using a multi-domain setup so the API domain needed to have some additional exposed headers in the CORS configuration.  So in the rails-cors gem I added an additional exposed value for the access-token:
config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins 'api.com'

    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :options, :head],
      :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
      :max_age => 0
  end
end

UPDATE: Exposed all fields required by angular, not just one ones that made it work.


text:
Q: Best Method for Logging Into QuickBooks Desktop on Locked Machine I am working on an automation project that involves opening an application, in this case QuickBooks Desktop, and entering in some information to login. The problem I am running into is that I cannot do this when the computer is locked (Windows Key + L), or put to sleep. I was wondering if anyone had any advice/solutions for trying to get this resolved. Below is my current code. It uses VBA to open the file, and a VBScript file with Task Scheduler to open the file at specific times. Any help is much appreciated.
VBA Code:
Public Sub openQB()
    Dim qbPathStr As String
    qbPathStr = "QuickBooks File Location"

    Dim Shex As Object
    Set Shex = CreateObject("Shell.Application")
    On Error Resume Next

    Shex.Open (qbPathStr)
    Application.Wait Now + #12:00:30 AM#

    AppActivate "QuickBooks Desktop Pro 2021"

    SendKeys ("Password")
    SendKeys ("~")
End Sub

VBScript Code:
Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True
objExcel.DisplayAlerts = False

Set objWorkbook = objExcel.Workbooks.Open("Excel file with VBA code")

objExcel.run "openQB"

objExcel.Quit

Set objExcel = Nothing
Set objWorkbook = Nothing

wcript.quit


text:
Q: push operation in a stack with scanf I am trying to simulate a stack using a doubly linked list.
When I write the following code the output is what it is supposed to be.
    push_ch(12, "TNT");
    push_ch(13, "ABC");
    push_ch(14, "ESPN");
    display();

OUTPUT
    12 TNT
    13 ABC
    14 ESPN

However, I have a problem when the arguments are provided from the stdin.
An example input is:
3 --> number of operations
push c 12 TNT
push c 13 ABC
push c 14 ESPN

In the main function, I have written these to get the arguments.
scanf("%d", &i);
while(i){
    scanf("%s ", temp1);
    if(!strcmp(temp1, "push")){
        scanf("%c ", &j);
        if(j == 'c'){
            scanf("%d %s[^\n]", &k, temp2);
            push_ch(k, temp2);
            display();
        }
     }
i--;
}

Here temp1, and temp2 are fixed size arrays. I have also called display function after each push operation to see what is happening. The output when the input is provided from  the stdin is this:
12 TNT
//stack after first push
12 ABC
13 ABC
//stack after second push
12 ESPN
13 ESPN
14 ESPN
//stack after third push

As you see, on the second push, the first element has changed. Similarly, on the third push, first two elements have been modified. There is no problem with their channel numbers. They are as what they should be somehow.
Here is the channel definition
typedef struct channel {
    struct channel * next;
    struct channel * back;
    int c_id;
    char * c_name;
    program * head_p;
    program * current_p;
} channel;

And this is the push_ch function I have written. Please ignore that it is not O(1).
void push_ch(int id, char *str){
    channel *temp;
    temp = head_c;
    if(temp == NULL){
        temp = malloc(sizeof(channel));
        temp->c_id = id;
        temp->c_name = str;
        temp->next = NULL;
        temp->back = NULL;
        temp->head_p = NULL;
        temp->current_p = NULL;
        head_c = temp;
    }
    else{
        while((temp->next) != NULL){
            temp = temp->next;
        }
        temp->next = malloc(sizeof(channel));
        temp->next->c_id = id;
        temp->next->c_name = str;
        temp->next->next = NULL;
        temp->next->head_p = NULL;
        temp->next->current_p = NULL;
        temp->next->back = temp;
    }
}

To sum up, there is no problem when I call the push function by hand several times to add items to the stack. However, if the input is provided from stdin, the string value of all nodes changes to the that of last node. I'd be glad if someone could show me where the problem is.

A: It appears that, scanf("%c ", &j);, should be scanf(" %c", &j); because otherwise it will read the white space left by the previous scanf(), which did not consume the one that you explicitly left after the "%s" specifier.
That only applies to the "%c" specifier, the "%s" specifier will stop when it encounters a white space, and it expects a " " i.e. a space character, while in " %c", any white space character as returned by isspace() will be consumed and then the input character you are trying to capture.

A: Code needs to replicate str in push_ch(int id, char *str)
Example:
char *str_dup = strdup(str);
...
temp->c_name = str_dup;
...
temp->next->c_name = str_dup;

If strdup() unavailable, make your own
char *my_strdup(const char *s) {
  if (s) {
    size_t length = strlen(s) + 1;
    char *newptr = malloc(length);
    if (newptr) {
      return memcpy(newptr, s, length);
    }
  }
  return NULL;
}

Also use @iharob answer to cope with user input.


text:
Q: How to Replace two slashes to one single slashe? C# I have a problem with somwthing about replace char. I tryied a lot of links but get the same problem to replace (\\) to (\)
here is my code:
 string mystringA = textBox.text
 string mystringB = mystringA.Replace("\\", "\"");

The result of mystringB stay the same as mystringA.
I am saying because I put a debug mode to see the result
My textBox.txt = C:\Users\Braulio Jose\Desktop\impressora\myfoto.png
I have to replace the double quotes because I want to delete this photo in another place but when I follow the path, mystringA put another quote, and I this path don't exist
I am using visual studio 2013 and C# Language.
Some help. thank you

A: Due to the fact, that your question is about quotes, but your code is about slashes, it's hard to guess what your real problem is.
But here is some sample code for both replacements:
var replaceQuotes = "Some text with \"\"double quotes\"\"";
var replacedQuotes = replaceQuotes.Replace("\"\"", "\"");
Console.WriteLine("Before: " + replaceQuotes);
Console.WriteLine("After:  " + replacedQuotes);

Console.WriteLine();

var replaceSlashes = "Some text with \\\\double slashes\\\\";
var replacedSlashes = replaceSlashes.Replace("\\\\", "\\");
Console.WriteLine("Before: " + replaceSlashes);
Console.WriteLine("After:  " + replacedSlashes);

And here the output:
Before: Some text with ""double quotes""
After:  Some text with "double quotes"

Before: Some text with \\double slashes\\
After:  Some text with \double slashes\


text:
Q: Laravel REST API "Status 404 Not Found" Currently we have a Laravel Rest API system running inside a Linux Server running with Apache, PHP and a remote database which is a SQL Server. My superiors asked me to create the same system but instead using Windows, IIS, and PHP. Now I've followed all installation instructions in the net and even arrived at the laravel 5 screen page. Now when I transferred laravel files and installed it in windows it did not have any error in the process. I even imported my .htaccess config to IIS. However when I made a request to the API it is returning a http status 404 error.
Here is my .htaccess file
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

     RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="true" />
        <rewrite>
            <rules>
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)/$" ignoreCase="false" />
                    <action type="Redirect" url="/{R:1}" redirectType="Permanent" />
                </rule>
                <rule name="Imported Rule 2" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
                <rule name="Imported Rule 3" stopProcessing="true">
                    <match url="^" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


text:
Q: Java: Succinct way to import multiple constants Is there a succinct way to import in Java which would be equivalent to the following statement:
import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

I know about this:
import android.view.View.*;

But I would like to be able to control what I import, and not just import everything in the View namespace.
ANSWER: The answer is No.

A: No, there's no quicker way to only import some constants.  You can get them all, or you can list each one you want separately.

Actually there is technically a third option, not that it's necessarily better.  You do have the option to import none of them and use their fully qualified name each time you refer to them.


text:
Q: Eclipse not seeing my updated classes explored all solutions to this, including clearing out metadata folder and making sure the compiler matches the project version. I also have build automatically checked.
When I save my files in eclipse they update in the filesystem, but when I attempt to run my maven project and deploy it to the JBoss server it runs and old version.
I've even put in compiler errors on purpose and it doesn't bother it at all.

A: Please try building your project with a clean command
mvn clean install

and also refresh your workspace in eclispe. Might help!

A: do maven clean install through eclipse maven plugin, to avoid different code base confusion, it seems you are editing some different code base on eclipse which is different when you build through maven.
recheck the path for both the cases.
At the end copy the jar from the eclipse project itself after refresh the project on eclipse.
I faced the same issue, due to eclipse was not loading the new jar, caching the old one. it's required to refresh the project on eclipse before taking the build jar.


text:
Q: Extract xmin/max, ymin/max for a tile from Mapbox API I am trying to harness the power of the Mapbox API (https://docs.mapbox.com/api/maps/raster-tiles/) to download some tiles. Easy enough.
I also though need to download some metadata about these tiles, namely - the coordinates of the four corners of each tile, in order to be able to place it in space.
According to the Mapbox API documentation, I've found the Retrieve information about a single tileset job request (https://docs.mapbox.com/api/maps/mapbox-tiling-service/), which returns, among other things, the layer_stats.zooms.ymin, layer_stats.zooms.ymax, layer_stats.zooms.xmin, layer_stats.zooms.xmax variables I am ultimately interested in.
In order to run this Retrieve... command I need the tileset and the job_id; the latter being the issue, as it is defined as The publish job's unique identifier. This identifier is returned in the jobId field of a Publish a tileset response.
I am having trouble understanding what this job_id is supposed to represent, as, per the definition, I infer that it can only be derived after a Publish a tileset command.
But I've never published any tilesets, I only wish to harvest them.
Can someone explain the proper usage of this command and its dependencies?
Or, if I am at a wrong path with my analysis of the API, can someone shed light on how this API if supposed to retrieve this kind of information?

A: With great thanks to @TomazicM, who provided the much needed js library (Mapbox tilebelt). I used the following commands the install the library:
#1. make sure you dont have any npm or nodejs. If you do, uninstall everything with:
sudo apt-get remove nodejs
sudo apt-get remove npm

#2. Then go to /etc/apt/sources.list.d and remove any node list if you have.
#3. Then do a:

sudo apt-get update

#4. check for any files somewhere
which nodejs
which npm
which node

#5. nuclear delete
rm -rf usr/local/bin/npm

#6. Ready to install
#7 (?) if working in docker and container is not connecting to ubuntu archive:

echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf > /dev/null

sudo apt-get update

#8. where to get the library from : https://github.com/mapbox/tilebelt

sudo apt install npm

#9. how to install nmp packafes with npm init - https://stackoverflow.com/questions/50895493/solving-the-npm-warn-saveerror-enoent-no-such-file-or-directory-open-users

npm init

#10. fill in all the details (most importantly the link provided to the library on github)

#11. (?) install library globally (if you want)
sudo npm install mapbox/tilebelt -g

#12. install locally (I used local installations)
sudo npm install mapbox/tilebelt

#13. install benchmark lib
sudo npm install benchmark

#14 (?). set the env variable if necessary
#export NODE_PATH=$(npm root --quiet -g)

After that i have a js script that looks like this:
const args = process.argv;

//console.log(args);

var x = args[2];
var y = args[3];
var z = args[4];

var tilebelt = require('@mapbox/tilebelt');

var tile = [x,y,z] // x,y,z

console.log(tilebelt.tileToBBOX(tile));

which can be called like so node getTileBBOX.js 10 15 8 and returns the bbox. The three arguments must be of the order x y z, where x = the x coordinate of the tile, as described in the slippy documentation (https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames), y = the y coordinate of the tile, z = the zoom level.

A: I've got another solution that doesn't require all these installations, written in R:
#convert radians to degrees
rad2deg <- function(rad) {(rad * 180) / (pi)}

#convert tile numbers to coordiantes in degrees
num2deg <- function(xtile, ytile, zoom){
  n <- 2.0 ** zoom
  lon_deg <- xtile / n * 360.0 - 180.0
  lat_rad <- atan(sinh(pi * ( 1-2 * ytile / n)))
  lat_deg <- rad2deg(lat_rad)

  return(c(lat_deg, lon_deg))
}

#This returns the NW-corner of the square.
#Use the function with xtile+1 and/or ytile+1 to get the other corners.
#With xtile+0.5 & ytile+0.5 it will return the center of the tile.

#use the num2deg function to get the four corners of the tile using +1 on tile numbers logic
getBBOX <- function(xtile, ytile, zoom, polygon_CW_CCW){

  NW_corner <- num2deg(xtile, ytile, zoom)
  NE_corner <- num2deg(xtile+1, ytile, zoom)
  SE_corner <- num2deg(xtile+1, ytile+1, zoom)
  SW_corner <- num2deg(xtile, ytile+1, zoom)

  #Clock-wise polygon defintion
  bbox_tile_cw <- c(NW_corner, NE_corner, SE_corner, SW_corner)

  #Counter-clock-wise polygon definition
  bbox_tile_ccw <- c(NW_corner, SW_corner, SE_corner, NE_corner)

  if(polygon_CW_CCW == 'cw'){
    return(bbox_tile_cw)
  }

  if(polygon_CW_CCW == 'ccw'){
    return(bbox_tile_ccw)
  }
}

This would work the same from any tile service that uses the slippy tile standard.


text:
Q: Error: "The method orderby must be called before the method skip" when trying to do Inner Join for ListView Goal: Get information from two different sql server tables to display into a ListView. Most come from the User table, and one value comes from the UserRole table(particularly the "Description" field).
I have been working through a series of errors. The current one being:
"the method skip is only supported  for sorted input in linq to entities. The method orderby must be called before the method skip"
I've tried adding OrderBy to the queries, as all the SO posts mention, but I am still getting the error.
Question:  Should it(OrderBy) be somewhere else? And am I going in the right diretion or if there is a better implementation for joining two tables into a single ListView?
aspx:
    <asp:ListView id="lstUsers" runat="server" ItemType="Project.Classes.UserWRole" DataKeyNames="ID" SelectMethod="listUsers_GetData"
    OnItemCommand="lstUsers_ItemCommand" DeleteMethod="lstUsers_DeleteItem" OnSorting="lstUsers_Sorting"
     OnItemDataBound="lstUsers_ItemDataBound"
    ItemPlaceholderID="litPlaceHolder">

    <LayoutTemplate>

                         Username
                        TAX ID
                        Role

                <asp:Literal ID="litPlaceHolder" runat="server" />

    </LayoutTemplate>

    <ItemTemplate>

            <%# Item.UserName %>
            <%# Item.Tax_ID %>
             <%# Item.Description %>

    </ItemTemplate>

default.aspx.cs:
public IQueryable<UserWithRole> listUsers_GetData()
        {
            IQueryable<User> users = Project.Classes.Helper.UsersForUser(
                db: db,
                UserID: SessionManager.CurrentUserID,
                Search_User: Search_User,
                aUserRoleShortcut: SessionManager.CurrentUserRole
                ).OrderBy(i=>i.UserRoleID);

            IQueryable<UserRole> userRoles = db.UserRoles.OrderBy(i=>i.ID);

            IQueryable<UserWRole> myQuery = from user in users
                        join userRole in userRoles on user.UserRoleID equals userRole.ID
                        select new UserWRole{ ID = user.ID, LastName = user.LastName, FirstName = user.FirstName, OrgName = user.OrgName, UserName = user.UserName, Description = userRole.Description, Tax_ID = user.Tax_ID, DateAdded = user.DateAdded };

            if (users != null)
            {
                listNumSearchResults.Text = string.Format("{0} Results Found", users.Count());
                if (users.Count() > 10)
                {
                    ddlRecordsPerPage.Visible = true;
                    ltItemsPerPage.Visible = true;
                    ddlRecordsPerPage2.Visible = true;
                    ltItemsPerPage2.Visible = true;
                    dp1.Visible = true;
                }
            }

            return myQuery;
        }

UserWithRole.cs:
namespace Project.Classes
{
    public class UserWRole
    {
        public string LastName, FirstName, OrganizationName, UserName, Description, Tax_ID;
        public DateTime DateAdded;
        public int ID;
    }
}

helper.cs:
public static IQueryable<d.User> UsersForUser(d.ProjectPE db, int UserID, string Search_User, e.UserRoleEnum? aUserRoleShortcut)
        {
            IQueryable<d.User> users = null;

            users = db.Users.OrderBy(a => a.LastName).AsQueryable();

            if (!string.IsNullOrEmpty(Search_User))
            {
                users = users.Where
                     (a =>
                          a.LastName.ToLower().StartsWith(Search_User.ToLower()) ||
                          a.FirstName.ToLower().StartsWith(Search_User.ToLower()) ||
                          a.UserName.ToLower().StartsWith(Search_User.ToLower())
                     ).AsQueryable();
            }

            users = users.Where(a => a.IsActive).AsQueryable();
            return users;
        }

I expected to see the column from the second Table to show in the ListView, but instead I am getting these errors

A: The following resolved the issue:
https://learn.microsoft.com/en-us/dotnet/csharp/linq/order-the-results-of-a-join-clause
I usually do the method syntax, and didn't realize I was formatting the orderby incorrectly with the syntax for this join. I put the orderby in between the join and select and it works now:
join uR in uRs on u.URID equals uR.ID
                    orderby uR.ID
                    select new UserWRole


text:
Q: Command blocks executing w/out required parameters met I'm trying to use command blocks to spawn a Grinder mob once at a certain spot whenever the player's "Grinders" score is equal to the set ammount. Eg. 1.
I'm using this command (With differences for each amount and position):

execute @p[score_Grinders=20] ~ ~ ~ setblock 17 5 22 redstone_block

The setblock sets a block of redstone above a set of command blocks that spawn the Grinder, and those work. However, even when the Grinders score is not met, it places the block, and I can't delete it without first disabling the command block. When inspecting the command block it says it can't execute the command as the player. Please help!

A: score_NAME is the maximum score, not exact score (so 20 or lower), while score_NAME_min is minimum. If you want an exact score, you must include both minimum and maximum:
/execute @p[score_Grinders_min=20,score_Grinders=20] ~ ~ ~ setblock 17 5 22 redstone_block


text:
Q: Add new column with values depending on other columns I have a dataframe:
type                 value
message            Warning messages ID(34140)
eof                EOF within quoted string
message            Warning messages ID(4525)
message_error      Warning messages ID(4525) error
package            Attaching package: 'jsonlite'
object             object in message

I want to add column  type2 which has values depending on other columns values.
The value on that column must be:

*

*"message_case" if:

*

*column type is "message"

*column value has substring  "Warning messages ID(" in it

*"eof_case" if:

*

*column type is "eof"

So, desired result is:
type                 value                              type1
message            Warning messages ID(34140)        message_case
eof                EOF within quoted string            eof_case
message            Warning messages ID(4525)         message_case
message_error      Warning messages ID(4525) error      NA
package            Attaching package: 'jsonlite'        NA
object             object in message                    NA

How could i do that?

A: Does this work:
library(dplyr)
library(stringr)
df %>% mutate(type1 = case_when(type == 'message' & str_detect(value,'Warning messages ID') ~ 'message_case',
                                type == 'eof' ~ 'eof_case',
                                TRUE ~ NA_character_))
# A tibble: 6 x 3
  type          value                                 type1
  <chr>         <chr>                                 <chr>
1 message       "Warning messages ID(34140)"          message_case
2 eof           "EOF within quoted string"            eof_case
3 message       "Warning messages ID(4525)"           message_case
4 message_error "Warning messages ID(4525) error"     NA
5 package       "Attaching package: \x91jsonlite\x92" NA
6 object        "object in message"                   NA


text:
Q: Select * from to_tsvector - joining tables I want to set the to_tsvector language (e.g.: 'French') so it uses the proper dictionary when rendering the FTS vector.
Table messages has a locale_id column, which is on the locales table. Which I then need to join the locales table to the languages table on locale_id to get the actual language name. But I'm getting an ambiguous ; error:
select * from to_tsvector(t3.language, t1.message)
inner join message as t1
inner join locales as t2 on (t1.locale_id = t2.id)
inner join languages as t3 on (t2.language_id = t3.id);

ERROR:  syntax error at or near ";" LINE 1: ....id)
inner join languages as t3 on (t2.language_id = t3.id);

A: newer code:
select to_tsvector(t3.language, t1.message)
from message as t1
inner join locales as t2 on (t1.locale_id = t2.id)
inner join languages as t3 on (t2.language_id = t3.id);

original fix:
select * from to_tsvector(t3.language, t1.message)
inner join message as t1 on 1 = 1 /* an ON join criteria is mandatory here even if you are doing an implicit cross join */
inner join locales as t2 on (t1.locale_id = t2.id)
inner join languages as t3 on (t2.language_id = t3.id);


text:
Q: The a tag href is not my expectant url I have a project(pyProject), and in it have a APP(app02).
And in the pyProject/urls.py, I routed the app02:
from app02 import views as app02_v

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    ...
    url(r'^app02/', include("app02.urls")),
]

In the app02/urls.py:
import views

urlpatterns = [
    url(r'^index/$', views.Index.as_view()),
    ...
    url(r'^userinfo/', views.userinfo),
]

the app02/views.py:
def userinfo(request):

    # QuerySet
    user_list = models.UserInfo.objects.all()
    print (user_list.query)
    return render(request, 'app02/userinfo.html', {'user_list':user_list})

And in the templates:
templates/index.html:

    用户管理
    用户组管理

But when I click the 用户管理 tag, print the error:

Not Found: /index/app02/userinfo/

Why it is not the /app02/userinfo/? why there is /index more ?
My expert is request the /app02/userinfo/.

A: In the a tag href you should use the absolute path:
用户管理

If use the relative path, it will append after to your current url.

A: Add a name keyword argument to your urls like this:
urlpatterns = [
    url(r'^index/$', views.Index.as_view()), name='index',
    ...
    url(r'^userinfo/', views.userinfo), name='user_info',
]

And then use the Django url template tag to render your URL's automatically like this:

    用户管理
    用户组管理

The syntax is {% url '<view_name>' %} where view_name is the name defined in the url.


text:
Q: Show Progress bar or spinner when ajax is running I am trying to add a progress bar or a spinner when the ajax is running, but the progress bar and spinner will only appear at same time with the success alert from ajax.
Note: I am using JSP and the ajax is used to update the database data through servlet. The progress bar is using bootstrap.
    $('#sync').click(function () {

        var start = $('#startdate').val();

        var end = $('#enddate').val();

        if ((start !== "") && (end !== "")) {

            var startDate = new Date(start);

            var endDate = new Date(end);

            $('#cover').show();
            $.ajax({
                type: "post",
                url: "PRSync",
                data: "start=" + startDate.yyyymmdd() +
                        "&end=" + endDate.yyyymmdd(),
                async: false,
                beforeSend: function () {

                },
                success: function (data) {
                    var arr = data.split('|');
                    if (arr[0] === "0") {
                        alert("Sync fail");
                    } else {
                        alert("Sync Succesfull. Total rows of " + arr[1] + " affected.");
                    }
                },
                error: function (jqXHR, textStatus, errorThrown, err4) { // if error occured
                    alert(jqXHR + " _ " + textStatus + " _ " + errorThrown + " _ " + err4);
                },
                complete: function () {
                    $('#cover').fadeOut(1000);
                }
            });

        }
    });
    $(document).ajaxStart(function () {
        // show loader on start
        showbusy();
    }).ajaxSuccess(function () {
        // hide loader on success
        hidebusy();
    });

    Date.prototype.yyyymmdd = function () {
        var yyyy = this.getFullYear().toString();
        var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
        var dd = this.getDate().toString();
        return yyyy + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + (dd[1] ? dd : "0" + dd[0]); // padding
    };

    var myApp;
    myApp = myApp || (function () {
        var pleaseWaitDiv = $('

Synchronizing is processing

');
        return {
            showPleaseWait: function () {
                pleaseWaitDiv.modal();
            },
            hidePleaseWait: function () {
                pleaseWaitDiv.modal('hide');
            },
        };
    })();
    function showbusy() {
        myApp.showPleaseWait();
    }
    function hidebusy() {
        myApp.hidePleaseWait();
    }

A: You can use jquery.blockUI.js.
You can initialize it like this in your code:
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);

A: Have you tried this:
$(document).bind("ajaxStart", function(){
    showbusy(); })
.bind("ajaxStop", function(){
    hidebusy();
});

Obviously, if your ajax call is processed very fast, it might seem that your function is triggered 'to late', however by binding the events to $(document) you make sure that they are not triggered once only.
If that still does not suite your needs, I would place the functions inside the ajax call:
$.ajax({
     beforeSend: showbusy(),
     complete: hidebusy()
});


text:
Q: Django Form not updating data in the model this is my first Django project and I am stuck. If not a solution, but just a hint on what I am doing wrong will be truly appreciated.
I have a model with one attribute set as Null by default and I want to use a Form to update that attribute with the ID taken from another model.
These are the 2 models:
models.py
class Squad(models.Model):
    squad_name = models.CharField(max_length=20)

    def __str__(self):
        return self.squad_name

class AvailablePlayer(models.Model):
    player_name = models.CharField(max_length=25)
    squad = models.ForeignKey(Squad, on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return self.player_name

This is the form:
forms.py
class AddSquadToPlayerForm(forms.Form):
    # squad the player will be added to
    squad_to_player = forms.ModelMultipleChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        super(AddSquadToPlayerForm, self).__init__()
        self.fields['squad_to_player'].queryset = AvailablePlayer.objects.all()

This is the view file, where I think something is missing/wrong:
views.py
def add_player_to_squad(request, squad_id):
    # player = AvailablePlayer.objects.get(id=squad_id)
    squad = Squad.objects.get(id=squad_id)
    if request.method == "POST":
        form = AddPlayerToSquadForm(request.POST)
        if form.is_valid():
            form.squad = form.cleaned_data['id']
            form.save()
            return redirect('fanta_soccer_app:squad', squad_id=squad_id)
    else:
        form = AddPlayerToSquadForm(queryset=AvailablePlayer.objects.all())
    context = {"squad": squad, "form": form}
    return render(request, 'fanta_soccer_app/add_player.html', context)

And finally, this is html file
add_player.html

Add a new player to the Squad:

{{ squad }}

<form action="{% url 'fanta_soccer_app:add_player' squad.id %}" method="POST">
    {% csrf_token %}

        {{ form.as_table }}

    <button name="submit" type="submit" >Add player</button>
</form>

The rendered html shows correctly a form with a drop down menu correctly populated with the objects in the database from the "AvailablePlayer" model, however when selecting one and clicking on "Add", nothing happens, and selected player is not added to the DB.
Thank you in advance for your time.
EDIT: the code in views.py has been modified according to a comment
ADDITIONAL INFO: to confirm the db is working, if I manually add the squad_id to one of the AvailablePlayer(s) in the DB, it will be correctly listed in the squad details view.

A: Based off the docs I think where you are going wrong is that you are trying to update an existing value, which requires you to pass an instance keyword argument to form.save().
So I think you need to do something like this:
if form.is_valid():
    a = Squad.objects.get(id=squad_id)
    form = AddSquadToPlayerForm(request.POST, instance=a)
    form.squad = form.cleaned_data['id']
    form.save()

A: I managed to fix it by myself, and sharing here the solution:

*

*I changed the form field from ModelMultipleChoiceField to ModelChoiceField. ModelMultipleChoiceField is for ManyToMany relationships model fields, while mine is a ForeignKey. I have also removed the init method:

squad_to_player = forms.ModelChoiceField(queryset=AvailablePlayer.objects.all())

*The view was pretty messed up,  as I was aware of, but after fixing the above, I started to have error logs, so I could eventually come up with the following solution:

view.py
def add_player_to_squad(request, squad_id):
    squad = Squad.objects.get(id=squad_id)
    if request.method == "POST":
        form = AddPlayerToSquadForm(request.POST)
        if form.is_valid():
            player_to_sign = form.cleaned_data['squad_to_player']
            player_to_sign.squad = squad
            player_to_sign.save()
            return redirect('fanta_soccer_app:squad', squad_id=squad_id)
    else:
        form = AddPlayerToSquadForm()
    context = {"squad": squad, "form": form}
    return render(request, 'fanta_soccer_app/add_player.html', context)


text:
Q: friction between 2 bodies There is a plank on which a block is kept. the block is given some velocity. Now if there is friction between block and plank it will act opposite to it's velocity for sure. but the plank is free to move. so where will the friction for the plank act? also if plank and block are the system is friction an internal force?? in other words will their centre of mass move??

A: Surely, friction is an internal force but that does not mean that it won't cause any motion. Friction may not produce any motion in some cases but in certain cases it does.
The friction on the plank will act due to that by the block as shown below,

As you can see, the plank is applying a frictional force on the block in the forward direction (which tends to move it). Simultaneously, the block is also applying an equal amount of frictional force on the plank in the opposite direction.
Now I will answer your last question. In those cases, in which the friction is not enough to make the block move (consider the pseudo force that acts in the backward direction and hence opposite to the friction), the block will simply fall off the back side and the plank will keep moving on its own and the block will keep moving in the opposite direction (of course, considering that the bottom plane is smooth). In this case the center of mass will not move.
But in case the block moves along with the plank, the center of mass will of course move.
Hope I could make it clear enough. If you have anything that needs clarification, please add it in comments.


text:
Q: Classifying Matlab Code and Pseudocodes Under List of Codes and Matlab and R Output under List of Output I am kindly requesting for assistance on how to put the headings Matlab Code and Pseudocodes under List of Codes and headings Matlab Output and R Output under List of Output using the below MWE. In other words, I am desiring to have two separate list of listings namely List of Codes and List of Output. However under List of Codes,I want to have sections (unnumbered) namely Matlab Code and Pseudocode, and under List of Output,I want to have sections (unnumbered) as well namely R Output and Matlab Output. Your help is going to be greatly appreciated. The suggested solution to my problem at Multiple listings styles is not producing the desired output since it does not address the following specifications:

*

*List of C++, List of R and List of Pseudocode are in chapter format using book document class which is something I do not like;

*List of C++, List of R and List of Pseudocode are supposed to be in an unnumbered section format under the chapter (unnumbered) by the name List of Codes;

*I also want to create a second independent listing by the chapter (unnumbered) name List of Output. Under this unnumbered chapter, I want to have unnumbered sections namely Matlab Output and R Output, and

*The suggested  solution does not work well under the new caption package. Actually, I had already tried that suggested solution and failed to get the desired output before @Tom pointed out the issue of the new caption package at Incorrect classification of multiple listings entries.

The output I am desiring is shown in the attached picture:

I would kindly appreciate if other users stop suggesting the solution at Multiple listings styles since it does not solve my problem as I have mentioned above. I may have not explained my case well and I would greatly appreciate if someone could improve this post so that other users may not consider it a duplicate or vote to close it. From my understanding, Tex.SE is meant to provide assistance to those with Latex problems given that they have tried something that did not work out, and not to close questions that are in need of a solution or solutions. I would also appreciate if I can get the solution to my problem.
My MWE takes into account the caption package updates:
\documentclass[openany]{book}
\usepackage{regexpatch}
\usepackage[nottoc]{tocbibind}
\usepackage{caption}
\usepackage{listings}

% --------------------------------------- C++
\newcommand{\lstlistmatlaboutputname}{List of Matlab Output}
\newcommand{\lstlistofmatlaboutput}{\begingroup
    \tocfile{\lstlistmatlaboutputname}{loc}
    \endgroup}

\newcommand{\lstlistroutputname}{List of R Output}
\newcommand{\lstlistofroutput}{\begingroup
    \tocfile{\lstlistroutputname}{loo}
    \endgroup}
% --------------------------------------- R
\newcommand{\lstlistmatlabcodename}{List of Matlab Code}
\newcommand{\lstlistofmatlabcode}{\begingroup
    \tocfile{\lstlistmatlabcodename}{lor}
    \endgroup}
% --------------------------------------- Pseudocode
\newcommand{\lstlistpseudocodename}{List of Pseudocode}
\newcommand{\lstlistofpseudocode}{\begingroup
    \tocfile{\lstlistpseudocodename}{lop}
    \endgroup}

\makeatletter
\lstnewenvironment{matlaboutput}[1][]{%
    \renewcommand{\lstlistingname}{Matlab Output}%
    \renewcommand{\ext@lstlisting}{loc}%
    %\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{loc}{}{}% use this with earlier version caption package
    \lstset{language=C++,#1}}%
{}

\lstnewenvironment{routput}[1][]{%
    \renewcommand{\lstlistingname}{R Output}%
    \renewcommand{\ext@lstlisting}{loo}%
    %\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{loc}{}{}% use this with earlier version caption package
    \lstset{language=R,#1}}%
{}

\lstnewenvironment{matlabcode}[1][]{%
    \renewcommand{\lstlistingname}{Matlab Code}%
    \renewcommand{\ext@lstlisting}{lor}%
    %\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{lor}{}{}% use this with earlier version caption package
    \lstset{language=R,#1}}
{}

\lstnewenvironment{pseudocode}[1][]{%
    \renewcommand{\lstlistingname}{Pseudocode}%
    \renewcommand{\ext@lstlisting}{lop}%
    %\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{lop}{}{}% use this with earlier version caption package
    \lstset{basicstyle=\ttfamily,#1}}%
{}
\makeatother

\begin{document}

    \lstlistofmatlaboutput
    \lstlistofroutput
    \lstlistofmatlabcode
    \lstlistofpseudocode

    \chapter{Listings}
    \begin{matlaboutput}[caption = {Some class definition}]
        % example matlab output
    \end{matlaboutput}

    \begin{routput}[caption = {Some class definition}]
        % example matlab output
    \end{routput}

    \begin{matlabcode}[caption = {For educational purposes}]
        % example matlab code 1
    \end{matlabcode}

    \begin{matlabcode}[caption = {Sample code from Matlab}]
        % example matlab code 2
    \end{matlabcode}

    \begin{pseudocode}[caption={Hello world}]
        % example pseudocode
    \end{pseudocode}
\end{document}

A: After some trial and error, I've come up with a solution to your first problem, I think.
Regarding your third and fourth points, I've got this to work:
I've tried to implement this answer to make the list of code and the list of output as sections and not as chapters, as you specified in your first point, without success. I hope this answer is helpful to you, at least in some way.
Finally, I've seen this other answer to the same question, and surprisingly it seems to work! Please check my updated code. There must be a way to simplify it, but I think it works fine.
Newer code:
\documentclass[openany]{book}
\usepackage{regexpatch}
\usepackage[nottoc]{tocbibind}
\usepackage{caption}
\usepackage{listings}
\usepackage{tocbasic}
% \setuptoc{loc}{leveldown}
% \setuptoc{loo}{leveldown} %these do not work

\newcommand{\lstlistcodesname}{List of codes}
\newcommand{\lstlistofcodes}{\begingroup
    \tocfile{\lstlistcodesname}{loc}
    \endgroup}

\newcommand{\lstlistoutputname}{List of output}
\newcommand{\lstlistofoutput}{\begingroup
    \tocfile{\lstlistoutputname}{loo}
    \endgroup}

\makeatletter
\lstnewenvironment{matlaboutput}[1][]{%
    \renewcommand{\lstlistingname}{Matlab Output}%
    \renewcommand{\ext@lstlisting}{loo}%
    \lstset{language=C++,#1}}%
{}

\lstnewenvironment{routput}[1][]{%
    \renewcommand{\lstlistingname}{R Output}%
    \renewcommand{\ext@lstlisting}{loo}%
    \lstset{language=R,#1}}%
{}

\lstnewenvironment{matlabcode}[1][]{%
    \renewcommand{\lstlistingname}{Matlab Code}%
    \renewcommand{\ext@lstlisting}{loc}%
    \lstset{language=R,#1}}
{}

\lstnewenvironment{pseudocode}[1][]{%
    \renewcommand{\lstlistingname}{Pseudocode}%
    \renewcommand{\ext@lstlisting}{loc}%
    \lstset{basicstyle=\ttfamily,#1}}%
{}
\makeatother

\makeatletter
\renewcommand{\lstlistofcodes}{%
  \begingroup
  \clearpage
  \section*{\lstlistcodesname% Taken from `article.cls`....
   \@mkboth{%
     \MakeUppercase\lstlistcodesname}{\MakeUppercase
     \lstlistcodesname}
   }%
  \@starttoc{loc}
  \endgroup
}
\makeatother
\makeatletter
\renewcommand{\lstlistofoutput}{%
  \begingroup
  \clearpage
  \section*{\lstlistoutputname% Taken from `article.cls`....
   \@mkboth{%
     \MakeUppercase\lstlistoutputname}{\MakeUppercase
     \lstlistoutputname}
   }%
  \@starttoc{loo}
  \endgroup
}
\makeatother

\begin{document}

    \lstlistofcodes
    \lstlistofoutput

    \chapter{Listings}
    \begin{matlaboutput}[caption = {Some class definition}]
        % example matlab output
    \end{matlaboutput}

    \begin{routput}[caption = {Some class definition}]
        % example matlab output
    \end{routput}

    \begin{matlabcode}[caption = {For educational purposes}]
        % example matlab code 1
    \end{matlabcode}

    \begin{matlabcode}[caption = {Sample code from Matlab}]
        % example matlab code 2
    \end{matlabcode}

    \begin{pseudocode}[caption={Hello world}]
        % example pseudocode
    \end{pseudocode}
\end{document}

Earlier code:
\documentclass[openany]{book}
\usepackage{regexpatch}
\usepackage[nottoc]{tocbibind}
\usepackage{caption}
\usepackage{listings}
\usepackage{tocbasic}
\setuptoc{loc}{leveldown}
\setuptoc{loo}{leveldown}

\newcommand{\lstlistcodesname}{List of codes}
\newcommand{\lstlistofcodes}{\begingroup
    \tocfile{\lstlistcodesname}{loc}
    \endgroup}

\newcommand{\lstlistoutputname}{List of output}
\newcommand{\lstlistofoutput}{\begingroup
    \tocfile{\lstlistoutputname}{loo}
    \endgroup}

\makeatletter
\lstnewenvironment{matlaboutput}[1][]{%
    \renewcommand{\lstlistingname}{Matlab Output}%
    \renewcommand{\ext@lstlisting}{loo}%
    \lstset{language=C++,#1}}%
{}

\lstnewenvironment{routput}[1][]{%
    \renewcommand{\lstlistingname}{R Output}%
    \renewcommand{\ext@lstlisting}{loo}%
    \lstset{language=R,#1}}%
{}

\lstnewenvironment{matlabcode}[1][]{%
    \renewcommand{\lstlistingname}{Matlab Code}%
    \renewcommand{\ext@lstlisting}{loc}%
    \lstset{language=R,#1}}
{}

\lstnewenvironment{pseudocode}[1][]{%
    \renewcommand{\lstlistingname}{Pseudocode}%
    \renewcommand{\ext@lstlisting}{loc}%
    \lstset{basicstyle=\ttfamily,#1}}%
{}
\makeatother

\begin{document}

    \lstlistofcodes
    \lstlistofoutput

    \chapter{Listings}
    \begin{matlaboutput}[caption = {Some class definition}]
        % example matlab output
    \end{matlaboutput}

    \begin{routput}[caption = {Some class definition}]
        % example matlab output
    \end{routput}

    \begin{matlabcode}[caption = {For educational purposes}]
        % example matlab code 1
    \end{matlabcode}

    \begin{matlabcode}[caption = {Sample code from Matlab}]
        % example matlab code 2
    \end{matlabcode}

    \begin{pseudocode}[caption={Hello world}]
        % example pseudocode
    \end{pseudocode}
\end{document}


text:
Q: Embedding BandCamp player in UIWebView? I'm trying to embed a bandcamp music player into my app. Although their players are generally Flash-based, they are HTML5 when loaded in iOS mobile Safari. Trouble is, it only seems to work in mobile Safari itself... when I try to embed a player in a UIWebView, it tells me my browser is unsupported. Is there any way around this or am I hosed?
Example URL (obtained from the "Share" button on any bandcamp player):
http://bandcamp.com/EmbeddedPlayer/album=355390343/size=grande3/bgcol=000000/linkcol=1275c4/

A: This is, because the user agent the UIWebView sends by default is another one than the one MobileSafari uses. The default is WebApps/1.0 CFNetwork/339.3 Darwin/9.4.1 and the one used by MobileSafari Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3
You can change the user agent sent by using the method
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field

Take a look at the documentation to find out more.
This should solve your problem.


text:
Q: Grammar question, problem with FIRST Consider following grammar:
A → BC
B → Ba | epsilon
C → bD | epsilon
D → …
…

The problem here is that rule B can derive epsilon and left-recursive as well.
In order to find FIRST(A) I am searching FIRST(B).
But I stuck on FIRST(B), because it is left-recursive.
So what is FIRST(B)?  And FIRST(A)?
My version is:
FIRST(B) → {a, epsilon}
FIRST(A) → {a, b, epsilon}

Is that correct?

A: Yes, you have it right. A left-recursion does not contribute to FIRST, because when Ba is matched for B, the B in Ba must start with something that B can start with - because it's a B, after all. :)
You could also instead factor out the left-recursion first.


text:
Q: Pandas - KeyError: ('var', 'occurred at index 1414') - looping with a for I have a dataframe with this columns
Gestor  No.Obligacion   Descripcion Codigo Gestion  Fecha Gestion   Fecha pago1 Fecha pago2 Fecha pago3 Fecha pago4 Fecha pago5 Fecha pago6 Fecha pago7 Fecha pago8 Fecha pago9

And i want to compare Fecha pago1 with Fecha pago2
I have this for with a function
for x in range(1, 8):
    def cambiarrepetidos(row):
        if row['Fecha pago{0}'.format(x)] == row['Fecha pago{0}'.format(x+1)]:
            return "Sin Pago"
        else:
            pass
    RS2['Fecha pago1'] = RS.apply(cambiarrepetidos, axis=1)

input

FechaPago1  FechaPago2
12/09/2018   12/09/2018
11/09/2018   12/09/2018
09/09/2018   10/09/2018

output

FechaPago1   FechaPago2
12/09/2018   Sin Pago
11/09/2018   12/09/2018
09/09/2018   10/09/2018

I want to do the same with FechaPago1 FechaPago2 FechaPago3 to FechaPago9
But i run it and i get this
KeyError: ('Fecha pago1', 'occurred at index 1414')

Can you help me please?, sorry for my english

A: If I understand correctly, you are comparing the values in two columns and if they are same, replace the value in column 2 with 'Sin Pago'.
You can do that without a loop. The first statement in loc is the condition, and if the condition is true, assign a value to column specified after the condition.
df.loc[df['FechaPago1'] == df['FechaPago2'], 'FechaPago2'] = 'Sin Pago'

    FechaPago1  FechaPago2
0   12/09/2018  Sin Pago
1   11/09/2018  12/09/2018
2   09/09/2018  10/09/2018


text:
Q: Rust: How to Match against Any I would like to store any type in a Vec, and match against the actual type that is stored in the Vec.
Here is my attempt:
use std::any::Any;

fn main() {
    let mut a = Vec::<Box<dyn Any>>::new();
    a.push(Box::new(42));
    a.push(Box::new("hello"));
    a.push(Box::new(99));
    for n in a {
        let type_id = (&*n).type_id();
        println!("{type_id:?}");
        match n {
            i32 => println!("i32"),
            str => println!("str"),
            _ => println!("unhandled type")
        }
    }
}

However this always prints "i32", and I get an unreachable pattern warning.
How do I match against Any?

A: You cannot match the type per se, but you can ask if it is of any specific type with Any::is:
use std::any::Any;

fn main() {
    let mut a = Vec::<Box<dyn Any>>::new();
    a.push(Box::new(42));
    a.push(Box::new("hello"));
    a.push(Box::new(99));
    for n in a {
        let type_id = (&*n).type_id();
        println!("{type_id:?}");
        if n.is::<i32>() {
            println!("i32")
        } else if n.is::<&str>(){
            println!("str")
        } else {
            println!("unhandled type")
        }
    }
}

Playground

A: In your example, i32 and str are acting as "identifiers" (i.e. variable names), rather than types.
To work with Any, you generally use downcast_*. For example:
fn handle(any: Box<dyn Any>) {
  if let Some(s) = any.downcast_ref::<String>() {
    println!("found a string: {}", s);
  }

  if let Some(i) = any.downcast_ref::<i32>() {
    println!("found an int: {}", i);
  }
}

If you don't care about the contained value, you can also use any.is::<T>()


text:
Q: Magento 2 core session variable unable to fetch first time when user comes from 3rd party website We have to fetch and set a session variable when the user redirects to our magento2 website using session-id from 3rd party site.
It looks like http://magento2.com/?SID=322e00bfqm3g6rfpjumah3939n
For this, we have written a custom router & match method but it's not triggering properly at the first time.
Could you please review the below logic and files and advise please.
Note: The implementation is in the same module only.
 The concept of this implementation is if the user redirecting to the M2 website from 3rd party we need to save fetch the SID (session-id) & and the user will browse the products on the M2 website. who are coming from 3rd party we don't want to display proceed to checkout button.
I have written a custom router and setting array value in the core session and trying to fetch that value in the plugin which is in the same module.

*

*app/code/Vendor/ModuleName/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\App\RouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="redirect_if_sid" xsi:type="array">
                    <item name="class" xsi:type="string">Vendor\ModuleName\Controller\Router\RewriteSID</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">20</item>
                </item>
            </argument>
            <argument name="cacheable" xsi:type="boolean">false</argument>
        </arguments>
    </type>
    <! -- For Proceed to checkout button -->
    <type name="Magento\Checkout\Helper\Data">
        <plugin name="CartPageProceeedtoToCheckoutButton" type="Vendor\ModuleName\Plugin\AfterProceedToCheckoutButton" disabled="false"/>
    </type>
</config>

*Vendor/ModuleName/Controller/Router/RewriteSID.php

<?php
namespace Vendor\ModuleName\Controller\Router;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Session\SessionManagerInterface;
class RewriteSID implements \Magento\Framework\App\RouterInterface
{

    private $logger;
    private $actionFactory;
    private $response;
    private $formKey;
    private $coreSession;

    public function __construct(
        LoggerInterface $logger,
        ActionFactory $actionFactory,
        ResponseInterface $response,
        FormKey $formKey,
        SessionManagerInterface $coreSession

    ) {
        $this->logger = $logger;
        $this->actionFactory = $actionFactory;
        $this->response = $response;
        $this->formKey = $formKey;
        $this->coreSession = $coreSession;

    }

    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $identifier = $request->getOriginalPathInfo();
        $condition = new \Magento\Framework\DataObject(['identifier' => $identifier, 'continue' => true]);
        $identifier = $condition->getIdentifier();
        if ($condition->getRedirectUrl()) {
            $this->response->setRedirect($condition->getRedirectUrl());
            $request->setDispatched(true);
            return $this->actionFactory->create('Magento\Framework\App\Action\Redirect');
        }
        if (!$condition->getContinue()) {
            return null;
        }
        if ($request->getParam('SID')) {

            $sessionData = array("Volvo", "BMW", "Toyota");
           try {
                    $this->coreSession->setVIEUserData($sessionData);
            }catch(\Exception $e) {
                    $this->logger->info("Something went wrong");
                    $this->logger->info($e->getMessage());
            }

        }//get params ends here
        else
        {
            return null;
        }
    }

}

*app/code/Vendor/ModuleName/Plugin/AfterProceedToCheckoutButton.php

<?php
namespace Vendor\ModuleName\Plugin;
use Magento\Framework\Session\SessionManager;
class AfterProceedToCheckoutButton
{

    private $coreSession;

    public function __construct(
        SessionManager $sessionManager
    ) {
        $this->coreSession = $sessionManager;
    }

    /**
     * @param $subject
     * @param $result
     * @return mixed
    */
    public function afterCanOnepageCheckout(\Magento\Checkout\Helper\Data $subject, $result)
    {
        //Here $this->coreSession->getVIEUserData() unable to fetch here

        if($result) {
            if($this->coreSession->getVIEUserData()) {
                return false;
            }
            return $result;
        }

    }
}

A: I see you are using sort_order 20 in your router declaration, try decreasing it to sortOrder 15. Since order 20 is used by URL Rewrites, it could be picking up a URL rewrite instead of your controller on the first visit. Such as redirecting http to https etc.
If that doesn't work, i would advice checking the following things.

*

*Controller is actually firing on first load

*Correct execution order (Controller then plugin)

*Try a controller_action_predispatch event

A: We have fixed the issue by creating and handling by custom controller in my custom module instead of the custom router.
Now we are providing the redirect URL to 3rd party system as mentioned below
 http://magento2.com/vie/index/redirect/sid/322e00bfqm3g6rfpjumah3939n instead of http://magento2.com/?SID=322e00bfqm3g6rfpjumah3939n so that 3rd party user will call this redirect controller.
From the controller, we are fetching unique id sid & processing further. So we are able to avoid the set session-id issues for the first time.
As well we have unset that session-id once after submitting the cart data to 3rd party on the checkout cart page.


text:
Q: (Java) Google Calendar format error when inserting Event I'm using Java Google API client and I'm trying to create a Google Calendar Event.
I'm able to login and fetch events I already have created.
I've been following the API examples and I'm getting the following error and looked at the other similar questions and still can't get it working:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
"domain" : "global",
"message" : "Invalid value for: \"T\" found, can only parse bare date string: 2017-08-31T12:00:00.000-01:00 Have you accidentally used DateTime instead of a Date?",
"reason" : "invalid"
  } ],
  "message" : "Invalid value for: \"T\" found, can only parse bare date string: 2017-08-31T12:00:00.000-01:00 Have you accidentally used DateTime instead of a Date?"
}

This is my code, I'm passing Strings into my DateTimes:
DateTime startDate = new DateTime(startData);
    EventDateTime start = new EventDateTime();
    start.setDate(startDate);
    start.setTimeZone("Europe/Stockholm");
    DateTime endDate = new DateTime(endData);
    EventDateTime end = new EventDateTime();
    end.setDate(endDate);
    end.setTimeZone("Europe/Stockholm");
    Event event = new Event();
    event.setDescription(lessons.get(i).getDescription());
    event.setStart(start);
    event.setEnd(end);
    event.setLocation(lessons.get(i).getLocation());
    event.setSummary(lessons.get(i).getName())

Any idea what's going wrong?

A: Possible duplicate.
However, shortly - Yes, you are trying to use a function which require a DateTime format, but you feed as a parameter a date object which is different.
"new DateTime(startData);" startData isn't DateTime, but date.
Please checkout this post: Google Calendar API (Java) - Invalid time format when creating Google Calendar Event
it has your problem and two solutions for it.